hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
0c21ad1abc5fe86808e695667638f6272d38fc2400599cfbe7571c7172383eb6 | from sympy.core import S
from sympy.core.relational import Eq, Ne
from sympy.logic.boolalg import BooleanFunction
from sympy.utilities.misc import func_name
class Contains(BooleanFunction):
"""
Asserts that x is an element of the set S.
Examples
========
>>> from sympy import Symbol, Integer, S
>>> from sympy.sets.contains import Contains
>>> Contains(Integer(2), S.Integers)
True
>>> Contains(Integer(-2), S.Naturals)
False
>>> i = Symbol('i', integer=True)
>>> Contains(i, S.Naturals)
Contains(i, Naturals)
References
==========
.. [1] https://en.wikipedia.org/wiki/Element_%28mathematics%29
"""
@classmethod
def eval(cls, x, s):
from sympy.sets.sets import Set
if not isinstance(s, Set):
raise TypeError('expecting Set, not %s' % func_name(s))
ret = s.contains(x)
if not isinstance(ret, Contains) and (
ret in (S.true, S.false) or isinstance(ret, Set)):
return ret
@property
def binary_symbols(self):
return set().union(*[i.binary_symbols
for i in self.args[1].args
if i.is_Boolean or i.is_Symbol or
isinstance(i, (Eq, Ne))])
def as_set(self):
raise NotImplementedError()
|
4cf826ec0b92bfdd329a32c7d391250e9ceb1cd179c231181ea5f0ae71e44d07 | from sympy.core import Basic, Integer
import operator
class OmegaPower(Basic):
"""
Represents ordinal exponential and multiplication terms one of the
building blocks of the Ordinal class.
In OmegaPower(a, b) a represents exponent and b represents multiplicity.
"""
def __new__(cls, a, b):
if isinstance(b, int):
b = Integer(b)
if not isinstance(b, Integer) or b <= 0:
raise TypeError("multiplicity must be a positive integer")
if not isinstance(a, Ordinal):
a = Ordinal.convert(a)
return Basic.__new__(cls, a, b)
@property
def exp(self):
return self.args[0]
@property
def mult(self):
return self.args[1]
def _compare_term(self, other, op):
if self.exp == other.exp:
return op(self.mult, other.mult)
else:
return op(self.exp, other.exp)
def __eq__(self, other):
if not isinstance(other, OmegaPower):
try:
other = OmegaPower(0, other)
except TypeError:
return NotImplemented
return self.args == other.args
def __hash__(self):
return Basic.__hash__(self)
def __lt__(self, other):
if not isinstance(other, OmegaPower):
try:
other = OmegaPower(0, other)
except TypeError:
return NotImplemented
return self._compare_term(other, operator.lt)
class Ordinal(Basic):
"""
Represents ordinals in Cantor normal form.
Internally, this class is just a list of instances of OmegaPower.
Examples
========
>>> from sympy.sets import Ordinal, OmegaPower
>>> from sympy.sets.ordinals import omega
>>> w = omega
>>> w.is_limit_ordinal
True
>>> Ordinal(OmegaPower(w + 1 ,1), OmegaPower(3, 2))
w**(w + 1) + w**3*2
>>> 3 + w
w
>>> (w + 1) * w
w**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Ordinal_arithmetic
"""
def __new__(cls, *terms):
obj = super().__new__(cls, *terms)
powers = [i.exp for i in obj.args]
if not all(powers[i] >= powers[i+1] for i in range(len(powers) - 1)):
raise ValueError("powers must be in decreasing order")
return obj
@property
def terms(self):
return self.args
@property
def leading_term(self):
if self == ord0:
raise ValueError("ordinal zero has no leading term")
return self.terms[0]
@property
def trailing_term(self):
if self == ord0:
raise ValueError("ordinal zero has no trailing term")
return self.terms[-1]
@property
def is_successor_ordinal(self):
try:
return self.trailing_term.exp == ord0
except ValueError:
return False
@property
def is_limit_ordinal(self):
try:
return not self.trailing_term.exp == ord0
except ValueError:
return False
@property
def degree(self):
return self.leading_term.exp
@classmethod
def convert(cls, integer_value):
if integer_value == 0:
return ord0
return Ordinal(OmegaPower(0, integer_value))
def __eq__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
return self.terms == other.terms
def __hash__(self):
return hash(self.args)
def __lt__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
for term_self, term_other in zip(self.terms, other.terms):
if term_self != term_other:
return term_self < term_other
return len(self.terms) < len(other.terms)
def __le__(self, other):
return (self == other or self < other)
def __gt__(self, other):
return not self <= other
def __ge__(self, other):
return not self < other
def __str__(self):
net_str = ""
plus_count = 0
if self == ord0:
return 'ord0'
for i in self.terms:
if plus_count:
net_str += " + "
if i.exp == ord0:
net_str += str(i.mult)
elif i.exp == 1:
net_str += 'w'
elif len(i.exp.terms) > 1 or i.exp.is_limit_ordinal:
net_str += 'w**(%s)'%i.exp
else:
net_str += 'w**%s'%i.exp
if not i.mult == 1 and not i.exp == ord0:
net_str += '*%s'%i.mult
plus_count += 1
return(net_str)
__repr__ = __str__
def __add__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
if other == ord0:
return self
a_terms = list(self.terms)
b_terms = list(other.terms)
r = len(a_terms) - 1
b_exp = other.degree
while r >= 0 and a_terms[r].exp < b_exp:
r -= 1
if r < 0:
terms = b_terms
elif a_terms[r].exp == b_exp:
sum_term = OmegaPower(b_exp, a_terms[r].mult + other.leading_term.mult)
terms = a_terms[:r] + [sum_term] + b_terms[1:]
else:
terms = a_terms[:r+1] + b_terms
return Ordinal(*terms)
def __radd__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
return other + self
def __mul__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
if ord0 in (self, other):
return ord0
a_exp = self.degree
a_mult = self.leading_term.mult
sum = []
if other.is_limit_ordinal:
for arg in other.terms:
sum.append(OmegaPower(a_exp + arg.exp, arg.mult))
else:
for arg in other.terms[:-1]:
sum.append(OmegaPower(a_exp + arg.exp, arg.mult))
b_mult = other.trailing_term.mult
sum.append(OmegaPower(a_exp, a_mult*b_mult))
sum += list(self.terms[1:])
return Ordinal(*sum)
def __rmul__(self, other):
if not isinstance(other, Ordinal):
try:
other = Ordinal.convert(other)
except TypeError:
return NotImplemented
return other * self
def __pow__(self, other):
if not self == omega:
return NotImplemented
return Ordinal(OmegaPower(other, 1))
class OrdinalZero(Ordinal):
"""The ordinal zero.
OrdinalZero can be imported as ``ord0``.
"""
pass
class OrdinalOmega(Ordinal):
"""The ordinal omega which forms the base of all ordinals in cantor normal form.
OrdinalOmega can be imported as ``omega``.
Examples
========
>>> from sympy.sets.ordinals import omega
>>> omega + omega
w*2
"""
def __new__(cls):
return Ordinal.__new__(cls)
@property
def terms(self):
return (OmegaPower(1, 1),)
ord0 = OrdinalZero()
omega = OrdinalOmega()
|
7b998574ceaf0ea57dea378c2be8c817b9b18019332e508b87cfbb830e13589b | from sympy.core import Expr
from sympy.core.decorators import call_highest_priority, _sympifyit
from sympy.sets import ImageSet
from sympy.sets.sets import set_add, set_sub, set_mul, set_div, set_pow, set_function
class SetExpr(Expr):
"""An expression that can take on values of a set.
Examples
========
>>> from sympy import Interval, FiniteSet
>>> from sympy.sets.setexpr import SetExpr
>>> a = SetExpr(Interval(0, 5))
>>> b = SetExpr(FiniteSet(1, 10))
>>> (a + b).set
Union(Interval(1, 6), Interval(10, 15))
>>> (2*a + b).set
Interval(1, 20)
"""
_op_priority = 11.0
def __new__(cls, setarg):
return Expr.__new__(cls, setarg)
set = property(lambda self: self.args[0])
def _latex(self, printer):
return r"SetExpr\left({}\right)".format(printer._print(self.set))
@_sympifyit('other', NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return _setexpr_apply_operation(set_add, self, other)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return _setexpr_apply_operation(set_add, other, self)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return _setexpr_apply_operation(set_mul, self, other)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return _setexpr_apply_operation(set_mul, other, self)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return _setexpr_apply_operation(set_sub, self, other)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return _setexpr_apply_operation(set_sub, other, self)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
return _setexpr_apply_operation(set_pow, self, other)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
return _setexpr_apply_operation(set_pow, other, self)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return _setexpr_apply_operation(set_div, self, other)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
return _setexpr_apply_operation(set_div, other, self)
def _eval_func(self, func):
# TODO: this could be implemented straight into `imageset`:
res = set_function(func, self.set)
if res is None:
return SetExpr(ImageSet(func, self.set))
return SetExpr(res)
def _setexpr_apply_operation(op, x, y):
if isinstance(x, SetExpr):
x = x.set
if isinstance(y, SetExpr):
y = y.set
out = op(x, y)
return SetExpr(out)
|
37825f6e4742a2aec3ffc05719a25f96493efd2f0229cced08b8cddeeaf8cb5f | from functools import reduce
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Lambda
from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_and
from sympy.core.numbers import oo, Integer
from sympy.core.relational import Eq
from sympy.core.singleton import Singleton, S
from sympy.core.symbol import Dummy, symbols, Symbol
from sympy.core.sympify import _sympify, sympify, converter
from sympy.logic.boolalg import And
from sympy.sets.sets import (Set, Interval, Union, FiniteSet,
ProductSet)
from sympy.utilities.misc import filldedent
from sympy.utilities.iterables import cartes
class Rationals(Set, metaclass=Singleton):
"""
Represents the rational numbers. This set is also available as
the Singleton, S.Rationals.
Examples
========
>>> from sympy import S
>>> S.Half in S.Rationals
True
>>> iterable = iter(S.Rationals)
>>> [next(iterable) for i in range(12)]
[0, 1, -1, 1/2, 2, -1/2, -2, 1/3, 3, -1/3, -3, 2/3]
"""
is_iterable = True
_inf = S.NegativeInfinity
_sup = S.Infinity
is_empty = False
is_finite_set = False
def _contains(self, other):
if not isinstance(other, Expr):
return False
return other.is_rational
def __iter__(self):
from sympy.core.numbers import igcd, Rational
yield S.Zero
yield S.One
yield S.NegativeOne
d = 2
while True:
for n in range(d):
if igcd(n, d) == 1:
yield Rational(n, d)
yield Rational(d, n)
yield Rational(-n, d)
yield Rational(-d, n)
d += 1
@property
def _boundary(self):
return S.Reals
class Naturals(Set, metaclass=Singleton):
"""
Represents the natural numbers (or counting numbers) which are all
positive integers starting from 1. This set is also available as
the Singleton, S.Naturals.
Examples
========
>>> from sympy import S, Interval, pprint
>>> 5 in S.Naturals
True
>>> iterable = iter(S.Naturals)
>>> next(iterable)
1
>>> next(iterable)
2
>>> next(iterable)
3
>>> pprint(S.Naturals.intersect(Interval(0, 10)))
{1, 2, ..., 10}
See Also
========
Naturals0 : non-negative integers (i.e. includes 0, too)
Integers : also includes negative integers
"""
is_iterable = True
_inf = S.One
_sup = S.Infinity
is_empty = False
is_finite_set = False
def _contains(self, other):
if not isinstance(other, Expr):
return False
elif other.is_positive and other.is_integer:
return True
elif other.is_integer is False or other.is_positive is False:
return False
def _eval_is_subset(self, other):
return Range(1, oo).is_subset(other)
def _eval_is_superset(self, other):
return Range(1, oo).is_superset(other)
def __iter__(self):
i = self._inf
while True:
yield i
i = i + 1
@property
def _boundary(self):
return self
def as_relational(self, x):
from sympy.functions.elementary.integers import floor
return And(Eq(floor(x), x), x >= self.inf, x < oo)
class Naturals0(Naturals):
"""Represents the whole numbers which are all the non-negative integers,
inclusive of zero.
See Also
========
Naturals : positive integers; does not include 0
Integers : also includes the negative integers
"""
_inf = S.Zero
def _contains(self, other):
if not isinstance(other, Expr):
return S.false
elif other.is_integer and other.is_nonnegative:
return S.true
elif other.is_integer is False or other.is_nonnegative is False:
return S.false
def _eval_is_subset(self, other):
return Range(oo).is_subset(other)
def _eval_is_superset(self, other):
return Range(oo).is_superset(other)
class Integers(Set, metaclass=Singleton):
"""
Represents all integers: positive, negative and zero. This set is also
available as the Singleton, S.Integers.
Examples
========
>>> from sympy import S, Interval, pprint
>>> 5 in S.Naturals
True
>>> iterable = iter(S.Integers)
>>> next(iterable)
0
>>> next(iterable)
1
>>> next(iterable)
-1
>>> next(iterable)
2
>>> pprint(S.Integers.intersect(Interval(-4, 4)))
{-4, -3, ..., 4}
See Also
========
Naturals0 : non-negative integers
Integers : positive and negative integers and zero
"""
is_iterable = True
is_empty = False
is_finite_set = False
def _contains(self, other):
if not isinstance(other, Expr):
return S.false
return other.is_integer
def __iter__(self):
yield S.Zero
i = S.One
while True:
yield i
yield -i
i = i + 1
@property
def _inf(self):
return S.NegativeInfinity
@property
def _sup(self):
return S.Infinity
@property
def _boundary(self):
return self
def as_relational(self, x):
from sympy.functions.elementary.integers import floor
return And(Eq(floor(x), x), -oo < x, x < oo)
def _eval_is_subset(self, other):
return Range(-oo, oo).is_subset(other)
def _eval_is_superset(self, other):
return Range(-oo, oo).is_superset(other)
class Reals(Interval, metaclass=Singleton):
"""
Represents all real numbers
from negative infinity to positive infinity,
including all integer, rational and irrational numbers.
This set is also available as the Singleton, S.Reals.
Examples
========
>>> from sympy import S, Rational, pi, I
>>> 5 in S.Reals
True
>>> Rational(-1, 2) in S.Reals
True
>>> pi in S.Reals
True
>>> 3*I in S.Reals
False
>>> S.Reals.contains(pi)
True
See Also
========
ComplexRegion
"""
def __new__(cls):
return Interval.__new__(cls, S.NegativeInfinity, S.Infinity)
def __eq__(self, other):
return other == Interval(S.NegativeInfinity, S.Infinity)
def __hash__(self):
return hash(Interval(S.NegativeInfinity, S.Infinity))
class ImageSet(Set):
"""
Image of a set under a mathematical function. The transformation
must be given as a Lambda function which has as many arguments
as the elements of the set upon which it operates, e.g. 1 argument
when acting on the set of integers or 2 arguments when acting on
a complex region.
This function is not normally called directly, but is called
from `imageset`.
Examples
========
>>> from sympy import Symbol, S, pi, Dummy, Lambda
>>> from sympy.sets.sets import FiniteSet, Interval
>>> from sympy.sets.fancysets import ImageSet
>>> x = Symbol('x')
>>> N = S.Naturals
>>> squares = ImageSet(Lambda(x, x**2), N) # {x**2 for x in N}
>>> 4 in squares
True
>>> 5 in squares
False
>>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersect(squares)
FiniteSet(1, 4, 9)
>>> square_iterable = iter(squares)
>>> for i in range(4):
... next(square_iterable)
1
4
9
16
If you want to get value for `x` = 2, 1/2 etc. (Please check whether the
`x` value is in `base_set` or not before passing it as args)
>>> squares.lamda(2)
4
>>> squares.lamda(S(1)/2)
1/4
>>> n = Dummy('n')
>>> solutions = ImageSet(Lambda(n, n*pi), S.Integers) # solutions of sin(x) = 0
>>> dom = Interval(-1, 1)
>>> dom.intersect(solutions)
FiniteSet(0)
See Also
========
sympy.sets.sets.imageset
"""
def __new__(cls, flambda, *sets):
if not isinstance(flambda, Lambda):
raise ValueError('First argument must be a Lambda')
signature = flambda.signature
if len(signature) != len(sets):
raise ValueError('Incompatible signature')
sets = [_sympify(s) for s in sets]
if not all(isinstance(s, Set) for s in sets):
raise TypeError("Set arguments to ImageSet should of type Set")
if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)):
raise ValueError("Signature %s does not match sets %s" % (signature, sets))
if flambda is S.IdentityFunction and len(sets) == 1:
return sets[0]
if not set(flambda.variables) & flambda.expr.free_symbols:
is_empty = fuzzy_or(s.is_empty for s in sets)
if is_empty == True:
return S.EmptySet
elif is_empty == False:
return FiniteSet(flambda.expr)
return Basic.__new__(cls, flambda, *sets)
lamda = property(lambda self: self.args[0])
base_sets = property(lambda self: self.args[1:])
@property
def base_set(self):
# XXX: Maybe deprecate this? It is poorly defined in handling
# the multivariate case...
sets = self.base_sets
if len(sets) == 1:
return sets[0]
else:
return ProductSet(*sets).flatten()
@property
def base_pset(self):
return ProductSet(*self.base_sets)
@classmethod
def _check_sig(cls, sig_i, set_i):
if sig_i.is_symbol:
return True
elif isinstance(set_i, ProductSet):
sets = set_i.sets
if len(sig_i) != len(sets):
return False
# Recurse through the signature for nested tuples:
return all(cls._check_sig(ts, ps) for ts, ps in zip(sig_i, sets))
else:
# XXX: Need a better way of checking whether a set is a set of
# Tuples or not. For example a FiniteSet can contain Tuples
# but so can an ImageSet or a ConditionSet. Others like
# Integers, Reals etc can not contain Tuples. We could just
# list the possibilities here... Current code for e.g.
# _contains probably only works for ProductSet.
return True # Give the benefit of the doubt
def __iter__(self):
already_seen = set()
for i in self.base_pset:
val = self.lamda(*i)
if val in already_seen:
continue
else:
already_seen.add(val)
yield val
def _is_multivariate(self):
return len(self.lamda.variables) > 1
def _contains(self, other):
from sympy.solvers.solveset import _solveset_multi
def get_symsetmap(signature, base_sets):
'''Attempt to get a map of symbols to base_sets'''
queue = list(zip(signature, base_sets))
symsetmap = {}
for sig, base_set in queue:
if sig.is_symbol:
symsetmap[sig] = base_set
elif base_set.is_ProductSet:
sets = base_set.sets
if len(sig) != len(sets):
raise ValueError("Incompatible signature")
# Recurse
queue.extend(zip(sig, sets))
else:
# If we get here then we have something like sig = (x, y) and
# base_set = {(1, 2), (3, 4)}. For now we give up.
return None
return symsetmap
def get_equations(expr, candidate):
'''Find the equations relating symbols in expr and candidate.'''
queue = [(expr, candidate)]
for e, c in queue:
if not isinstance(e, Tuple):
yield Eq(e, c)
elif not isinstance(c, Tuple) or len(e) != len(c):
yield False
return
else:
queue.extend(zip(e, c))
# Get the basic objects together:
other = _sympify(other)
expr = self.lamda.expr
sig = self.lamda.signature
variables = self.lamda.variables
base_sets = self.base_sets
# Use dummy symbols for ImageSet parameters so they don't match
# anything in other
rep = {v: Dummy(v.name) for v in variables}
variables = [v.subs(rep) for v in variables]
sig = sig.subs(rep)
expr = expr.subs(rep)
# Map the parts of other to those in the Lambda expr
equations = []
for eq in get_equations(expr, other):
# Unsatisfiable equation?
if eq is False:
return False
equations.append(eq)
# Map the symbols in the signature to the corresponding domains
symsetmap = get_symsetmap(sig, base_sets)
if symsetmap is None:
# Can't factor the base sets to a ProductSet
return None
# Which of the variables in the Lambda signature need to be solved for?
symss = (eq.free_symbols for eq in equations)
variables = set(variables) & reduce(set.union, symss, set())
# Use internal multivariate solveset
variables = tuple(variables)
base_sets = [symsetmap[v] for v in variables]
solnset = _solveset_multi(equations, variables, base_sets)
if solnset is None:
return None
return fuzzy_not(solnset.is_empty)
@property
def is_iterable(self):
return all(s.is_iterable for s in self.base_sets)
def doit(self, **kwargs):
from sympy.sets.setexpr import SetExpr
f = self.lamda
sig = f.signature
if len(sig) == 1 and sig[0].is_symbol and isinstance(f.expr, Expr):
base_set = self.base_sets[0]
return SetExpr(base_set)._eval_func(f).set
if all(s.is_FiniteSet for s in self.base_sets):
return FiniteSet(*(f(*a) for a in cartes(*self.base_sets)))
return self
class Range(Set):
"""
Represents a range of integers. Can be called as Range(stop),
Range(start, stop), or Range(start, stop, step); when stop is
not given it defaults to 1.
`Range(stop)` is the same as `Range(0, stop, 1)` and the stop value
(juse as for Python ranges) is not included in the Range values.
>>> from sympy import Range
>>> list(Range(3))
[0, 1, 2]
The step can also be negative:
>>> list(Range(10, 0, -2))
[10, 8, 6, 4, 2]
The stop value is made canonical so equivalent ranges always
have the same args:
>>> Range(0, 10, 3)
Range(0, 12, 3)
Infinite ranges are allowed. ``oo`` and ``-oo`` are never included in the
set (``Range`` is always a subset of ``Integers``). If the starting point
is infinite, then the final value is ``stop - step``. To iterate such a
range, it needs to be reversed:
>>> from sympy import oo
>>> r = Range(-oo, 1)
>>> r[-1]
0
>>> next(iter(r))
Traceback (most recent call last):
...
TypeError: Cannot iterate over Range with infinite start
>>> next(iter(r.reversed))
0
Although Range is a set (and supports the normal set
operations) it maintains the order of the elements and can
be used in contexts where `range` would be used.
>>> from sympy import Interval
>>> Range(0, 10, 2).intersect(Interval(3, 7))
Range(4, 8, 2)
>>> list(_)
[4, 6]
Although slicing of a Range will always return a Range -- possibly
empty -- an empty set will be returned from any intersection that
is empty:
>>> Range(3)[:0]
Range(0, 0, 1)
>>> Range(3).intersect(Interval(4, oo))
EmptySet
>>> Range(3).intersect(Range(4, oo))
EmptySet
Range will accept symbolic arguments but has very limited support
for doing anything other than displaying the Range:
>>> from sympy import Symbol, pprint
>>> from sympy.abc import i, j, k
>>> Range(i, j, k).start
i
>>> Range(i, j, k).inf
Traceback (most recent call last):
...
ValueError: invalid method for symbolic range
Better success will be had when using integer symbols:
>>> n = Symbol('n', integer=True)
>>> r = Range(n, n + 20, 3)
>>> r.inf
n
>>> pprint(r)
{n, n + 3, ..., n + 17}
"""
is_iterable = True
def __new__(cls, *args):
from sympy.functions.elementary.integers import ceiling
if len(args) == 1:
if isinstance(args[0], range):
raise TypeError(
'use sympify(%s) to convert range to Range' % args[0])
# expand range
slc = slice(*args)
if slc.step == 0:
raise ValueError("step cannot be 0")
start, stop, step = slc.start or 0, slc.stop, slc.step or 1
try:
ok = []
for w in (start, stop, step):
w = sympify(w)
if w in [S.NegativeInfinity, S.Infinity] or (
w.has(Symbol) and w.is_integer != False):
ok.append(w)
elif not w.is_Integer:
raise ValueError
else:
ok.append(w)
except ValueError:
raise ValueError(filldedent('''
Finite arguments to Range must be integers; `imageset` can define
other cases, e.g. use `imageset(i, i/10, Range(3))` to give
[0, 1/10, 1/5].'''))
start, stop, step = ok
null = False
if any(i.has(Symbol) for i in (start, stop, step)):
if start == stop:
null = True
else:
end = stop
elif start.is_infinite:
span = step*(stop - start)
if span is S.NaN or span <= 0:
null = True
elif step.is_Integer and stop.is_infinite and abs(step) != 1:
raise ValueError(filldedent('''
Step size must be %s in this case.''' % (1 if step > 0 else -1)))
else:
end = stop
else:
oostep = step.is_infinite
if oostep:
step = S.One if step > 0 else S.NegativeOne
n = ceiling((stop - start)/step)
if n <= 0:
null = True
elif oostep:
end = start + 1
step = S.One # make it a canonical single step
else:
end = start + n*step
if null:
start = end = S.Zero
step = S.One
return Basic.__new__(cls, start, end, step)
start = property(lambda self: self.args[0])
stop = property(lambda self: self.args[1])
step = property(lambda self: self.args[2])
@property
def reversed(self):
"""Return an equivalent Range in the opposite order.
Examples
========
>>> from sympy import Range
>>> Range(10).reversed
Range(9, -1, -1)
"""
if self.has(Symbol):
_ = self.size # validate
if not self:
return self
return self.func(
self.stop - self.step, self.start - self.step, -self.step)
def _contains(self, other):
if not self:
return S.false
if other.is_infinite:
return S.false
if not other.is_integer:
return other.is_integer
if self.has(Symbol):
try:
_ = self.size # validate
except ValueError:
return
if self.start.is_finite:
ref = self.start
elif self.stop.is_finite:
ref = self.stop
else: # both infinite; step is +/- 1 (enforced by __new__)
return S.true
if self.size == 1:
return Eq(other, self[0])
res = (ref - other) % self.step
if res == S.Zero:
return And(other >= self.inf, other <= self.sup)
elif res.is_Integer: # off sequence
return S.false
else: # symbolic/unsimplified residue modulo step
return None
def __iter__(self):
if self.has(Symbol):
_ = self.size # validate
if self.start in [S.NegativeInfinity, S.Infinity]:
raise TypeError("Cannot iterate over Range with infinite start")
elif self:
i = self.start
step = self.step
while True:
if (step > 0 and not (self.start <= i < self.stop)) or \
(step < 0 and not (self.stop < i <= self.start)):
break
yield i
i += step
def __len__(self):
rv = self.size
if rv is S.Infinity:
raise ValueError('Use .size to get the length of an infinite Range')
return int(rv)
@property
def size(self):
if not self:
return S.Zero
dif = self.stop - self.start
if self.has(Symbol):
if dif.has(Symbol) or self.step.has(Symbol) or (
not self.start.is_integer and not self.stop.is_integer):
raise ValueError('invalid method for symbolic range')
if dif.is_infinite:
return S.Infinity
return Integer(abs(dif//self.step))
@property
def is_finite_set(self):
if self.start.is_integer and self.stop.is_integer:
return True
return self.size.is_finite
def __bool__(self):
return self.start != self.stop
def __getitem__(self, i):
from sympy.functions.elementary.integers import ceiling
ooslice = "cannot slice from the end with an infinite value"
zerostep = "slice step cannot be zero"
infinite = "slicing not possible on range with infinite start"
# if we had to take every other element in the following
# oo, ..., 6, 4, 2, 0
# we might get oo, ..., 4, 0 or oo, ..., 6, 2
ambiguous = "cannot unambiguously re-stride from the end " + \
"with an infinite value"
if isinstance(i, slice):
if self.size.is_finite: # validates, too
start, stop, step = i.indices(self.size)
n = ceiling((stop - start)/step)
if n <= 0:
return Range(0)
canonical_stop = start + n*step
end = canonical_stop - step
ss = step*self.step
return Range(self[start], self[end] + ss, ss)
else: # infinite Range
start = i.start
stop = i.stop
if i.step == 0:
raise ValueError(zerostep)
step = i.step or 1
ss = step*self.step
#---------------------
# handle infinite Range
# i.e. Range(-oo, oo) or Range(oo, -oo, -1)
# --------------------
if self.start.is_infinite and self.stop.is_infinite:
raise ValueError(infinite)
#---------------------
# handle infinite on right
# e.g. Range(0, oo) or Range(0, -oo, -1)
# --------------------
if self.stop.is_infinite:
# start and stop are not interdependent --
# they only depend on step --so we use the
# equivalent reversed values
return self.reversed[
stop if stop is None else -stop + 1:
start if start is None else -start:
step].reversed
#---------------------
# handle infinite on the left
# e.g. Range(oo, 0, -1) or Range(-oo, 0)
# --------------------
# consider combinations of
# start/stop {== None, < 0, == 0, > 0} and
# step {< 0, > 0}
if start is None:
if stop is None:
if step < 0:
return Range(self[-1], self.start, ss)
elif step > 1:
raise ValueError(ambiguous)
else: # == 1
return self
elif stop < 0:
if step < 0:
return Range(self[-1], self[stop], ss)
else: # > 0
return Range(self.start, self[stop], ss)
elif stop == 0:
if step > 0:
return Range(0)
else: # < 0
raise ValueError(ooslice)
elif stop == 1:
if step > 0:
raise ValueError(ooslice) # infinite singleton
else: # < 0
raise ValueError(ooslice)
else: # > 1
raise ValueError(ooslice)
elif start < 0:
if stop is None:
if step < 0:
return Range(self[start], self.start, ss)
else: # > 0
return Range(self[start], self.stop, ss)
elif stop < 0:
return Range(self[start], self[stop], ss)
elif stop == 0:
if step < 0:
raise ValueError(ooslice)
else: # > 0
return Range(0)
elif stop > 0:
raise ValueError(ooslice)
elif start == 0:
if stop is None:
if step < 0:
raise ValueError(ooslice) # infinite singleton
elif step > 1:
raise ValueError(ambiguous)
else: # == 1
return self
elif stop < 0:
if step > 1:
raise ValueError(ambiguous)
elif step == 1:
return Range(self.start, self[stop], ss)
else: # < 0
return Range(0)
else: # >= 0
raise ValueError(ooslice)
elif start > 0:
raise ValueError(ooslice)
else:
if not self:
raise IndexError('Range index out of range')
if i == 0:
if self.start.is_infinite:
raise ValueError(ooslice)
if self.has(Symbol):
if (self.stop > self.start) == self.step.is_positive and self.step.is_positive is not None:
pass
else:
_ = self.size # validate
return self.start
if i == -1:
if self.stop.is_infinite:
raise ValueError(ooslice)
n = self.stop - self.step
if n.is_Integer or (
n.is_integer and (
(n - self.start).is_nonnegative ==
self.step.is_positive)):
return n
_ = self.size # validate
rv = (self.stop if i < 0 else self.start) + i*self.step
if rv.is_infinite:
raise ValueError(ooslice)
if rv < self.inf or rv > self.sup:
raise IndexError("Range index out of range")
return rv
@property
def _inf(self):
if not self:
raise NotImplementedError
if self.has(Symbol):
if self.step.is_positive:
return self[0]
elif self.step.is_negative:
return self[-1]
_ = self.size # validate
if self.step > 0:
return self.start
else:
return self.stop - self.step
@property
def _sup(self):
if not self:
raise NotImplementedError
if self.has(Symbol):
if self.step.is_positive:
return self[-1]
elif self.step.is_negative:
return self[0]
_ = self.size # validate
if self.step > 0:
return self.stop - self.step
else:
return self.start
@property
def _boundary(self):
return self
def as_relational(self, x):
"""Rewrite a Range in terms of equalities and logic operators. """
from sympy.functions.elementary.integers import floor
if self.size == 1:
return Eq(x, self[0])
else:
return And(
Eq(x, floor(x)),
x >= self.inf if self.inf in self else x > self.inf,
x <= self.sup if self.sup in self else x < self.sup)
converter[range] = lambda r: Range(r.start, r.stop, r.step)
def normalize_theta_set(theta):
"""
Normalize a Real Set `theta` in the Interval [0, 2*pi). It returns
a normalized value of theta in the Set. For Interval, a maximum of
one cycle [0, 2*pi], is returned i.e. for theta equal to [0, 10*pi],
returned normalized value would be [0, 2*pi). As of now intervals
with end points as non-multiples of `pi` is not supported.
Raises
======
NotImplementedError
The algorithms for Normalizing theta Set are not yet
implemented.
ValueError
The input is not valid, i.e. the input is not a real set.
RuntimeError
It is a bug, please report to the github issue tracker.
Examples
========
>>> from sympy.sets.fancysets import normalize_theta_set
>>> from sympy import Interval, FiniteSet, pi
>>> normalize_theta_set(Interval(9*pi/2, 5*pi))
Interval(pi/2, pi)
>>> normalize_theta_set(Interval(-3*pi/2, pi/2))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-pi/2, pi/2))
Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi))
>>> normalize_theta_set(Interval(-4*pi, 3*pi))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-3*pi/2, -pi/2))
Interval(pi/2, 3*pi/2)
>>> normalize_theta_set(FiniteSet(0, pi, 3*pi))
FiniteSet(0, pi)
"""
from sympy.functions.elementary.trigonometric import _pi_coeff as coeff
if theta.is_Interval:
interval_len = theta.measure
# one complete circle
if interval_len >= 2*S.Pi:
if interval_len == 2*S.Pi and theta.left_open and theta.right_open:
k = coeff(theta.start)
return Union(Interval(0, k*S.Pi, False, True),
Interval(k*S.Pi, 2*S.Pi, True, True))
return Interval(0, 2*S.Pi, False, True)
k_start, k_end = coeff(theta.start), coeff(theta.end)
if k_start is None or k_end is None:
raise NotImplementedError("Normalizing theta without pi as coefficient is "
"not yet implemented")
new_start = k_start*S.Pi
new_end = k_end*S.Pi
if new_start > new_end:
return Union(Interval(S.Zero, new_end, False, theta.right_open),
Interval(new_start, 2*S.Pi, theta.left_open, True))
else:
return Interval(new_start, new_end, theta.left_open, theta.right_open)
elif theta.is_FiniteSet:
new_theta = []
for element in theta:
k = coeff(element)
if k is None:
raise NotImplementedError('Normalizing theta without pi as '
'coefficient, is not Implemented.')
else:
new_theta.append(k*S.Pi)
return FiniteSet(*new_theta)
elif theta.is_Union:
return Union(*[normalize_theta_set(interval) for interval in theta.args])
elif theta.is_subset(S.Reals):
raise NotImplementedError("Normalizing theta when, it is of type %s is not "
"implemented" % type(theta))
else:
raise ValueError(" %s is not a real set" % (theta))
class ComplexRegion(Set):
"""
Represents the Set of all Complex Numbers. It can represent a
region of Complex Plane in both the standard forms Polar and
Rectangular coordinates.
* Polar Form
Input is in the form of the ProductSet or Union of ProductSets
of the intervals of r and theta, & use the flag polar=True.
Z = {z in C | z = r*[cos(theta) + I*sin(theta)], r in [r], theta in [theta]}
* Rectangular Form
Input is in the form of the ProductSet or Union of ProductSets
of interval of x and y the of the Complex numbers in a Plane.
Default input type is in rectangular form.
Z = {z in C | z = x + I*y, x in [Re(z)], y in [Im(z)]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion
>>> from sympy.sets import Interval
>>> from sympy import S, I, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 6)
>>> c = Interval(1, 8)
>>> c1 = ComplexRegion(a*b) # Rectangular Form
>>> c1
CartesianComplexRegion(ProductSet(Interval(2, 3), Interval(4, 6)))
* c1 represents the rectangular region in complex plane
surrounded by the coordinates (2, 4), (3, 4), (3, 6) and
(2, 6), of the four vertices.
>>> c2 = ComplexRegion(Union(a*b, b*c))
>>> c2
CartesianComplexRegion(Union(ProductSet(Interval(2, 3), Interval(4, 6)), ProductSet(Interval(4, 6), Interval(1, 8))))
* c2 represents the Union of two rectangular regions in complex
plane. One of them surrounded by the coordinates of c1 and
other surrounded by the coordinates (4, 1), (6, 1), (6, 8) and
(4, 8).
>>> 2.5 + 4.5*I in c1
True
>>> 2.5 + 6.5*I in c1
False
>>> r = Interval(0, 1)
>>> theta = Interval(0, 2*S.Pi)
>>> c2 = ComplexRegion(r*theta, polar=True) # Polar Form
>>> c2 # unit Disk
PolarComplexRegion(ProductSet(Interval(0, 1), Interval.Ropen(0, 2*pi)))
* c2 represents the region in complex plane inside the
Unit Disk centered at the origin.
>>> 0.5 + 0.5*I in c2
True
>>> 1 + 2*I in c2
False
>>> unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
>>> upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
>>> intersection = unit_disk.intersect(upper_half_unit_disk)
>>> intersection
PolarComplexRegion(ProductSet(Interval(0, 1), Interval(0, pi)))
>>> intersection == upper_half_unit_disk
True
See Also
========
CartesianComplexRegion
PolarComplexRegion
Complexes
"""
is_ComplexRegion = True
def __new__(cls, sets, polar=False):
if polar is False:
return CartesianComplexRegion(sets)
elif polar is True:
return PolarComplexRegion(sets)
else:
raise ValueError("polar should be either True or False")
@property
def sets(self):
"""
Return raw input sets to the self.
Examples
========
>>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
>>> C1 = ComplexRegion(a*b)
>>> C1.sets
ProductSet(Interval(2, 3), Interval(4, 5))
>>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.sets
Union(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
"""
return self.args[0]
@property
def psets(self):
"""
Return a tuple of sets (ProductSets) input of the self.
Examples
========
>>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
>>> C1 = ComplexRegion(a*b)
>>> C1.psets
(ProductSet(Interval(2, 3), Interval(4, 5)),)
>>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.psets
(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
"""
if self.sets.is_ProductSet:
psets = ()
psets = psets + (self.sets, )
else:
psets = self.sets.args
return psets
@property
def a_interval(self):
"""
Return the union of intervals of `x` when, self is in
rectangular form, or the union of intervals of `r` when
self is in polar form.
Examples
========
>>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
>>> C1 = ComplexRegion(a*b)
>>> C1.a_interval
Interval(2, 3)
>>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.a_interval
Union(Interval(2, 3), Interval(4, 5))
"""
a_interval = []
for element in self.psets:
a_interval.append(element.args[0])
a_interval = Union(*a_interval)
return a_interval
@property
def b_interval(self):
"""
Return the union of intervals of `y` when, self is in
rectangular form, or the union of intervals of `theta`
when self is in polar form.
Examples
========
>>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
>>> C1 = ComplexRegion(a*b)
>>> C1.b_interval
Interval(4, 5)
>>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.b_interval
Interval(1, 7)
"""
b_interval = []
for element in self.psets:
b_interval.append(element.args[1])
b_interval = Union(*b_interval)
return b_interval
@property
def _measure(self):
"""
The measure of self.sets.
Examples
========
>>> from sympy import Interval, ComplexRegion, S
>>> a, b = Interval(2, 5), Interval(4, 8)
>>> c = Interval(0, 2*S.Pi)
>>> c1 = ComplexRegion(a*b)
>>> c1.measure
12
>>> c2 = ComplexRegion(a*c, polar=True)
>>> c2.measure
6*pi
"""
return self.sets._measure
@classmethod
def from_real(cls, sets):
"""
Converts given subset of real numbers to a complex region.
Examples
========
>>> from sympy import Interval, ComplexRegion
>>> unit = Interval(0,1)
>>> ComplexRegion.from_real(unit)
CartesianComplexRegion(ProductSet(Interval(0, 1), FiniteSet(0)))
"""
if not sets.is_subset(S.Reals):
raise ValueError("sets must be a subset of the real line")
return CartesianComplexRegion(sets * FiniteSet(0))
def _contains(self, other):
from sympy.functions import arg, Abs
from sympy.core.containers import Tuple
other = sympify(other)
isTuple = isinstance(other, Tuple)
if isTuple and len(other) != 2:
raise ValueError('expecting Tuple of length 2')
# If the other is not an Expression, and neither a Tuple
if not isinstance(other, Expr) and not isinstance(other, Tuple):
return S.false
# self in rectangular form
if not self.polar:
re, im = other if isTuple else other.as_real_imag()
return fuzzy_or(fuzzy_and([
pset.args[0]._contains(re),
pset.args[1]._contains(im)])
for pset in self.psets)
# self in polar form
elif self.polar:
if other.is_zero:
# ignore undefined complex argument
return fuzzy_or(pset.args[0]._contains(S.Zero)
for pset in self.psets)
if isTuple:
r, theta = other
else:
r, theta = Abs(other), arg(other)
if theta.is_real and theta.is_number:
# angles in psets are normalized to [0, 2pi)
theta %= 2*S.Pi
return fuzzy_or(fuzzy_and([
pset.args[0]._contains(r),
pset.args[1]._contains(theta)])
for pset in self.psets)
class CartesianComplexRegion(ComplexRegion):
"""
Set representing a square region of the complex plane.
Z = {z in C | z = x + I*y, x in [Re(z)], y in [Im(z)]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion
>>> from sympy.sets.sets import Interval
>>> from sympy import I
>>> region = ComplexRegion(Interval(1, 3) * Interval(4, 6))
>>> 2 + 5*I in region
True
>>> 5*I in region
False
See also
========
ComplexRegion
PolarComplexRegion
Complexes
"""
polar = False
variables = symbols('x, y', cls=Dummy)
def __new__(cls, sets):
if sets == S.Reals*S.Reals:
return S.Complexes
if all(_a.is_FiniteSet for _a in sets.args) and (len(sets.args) == 2):
# ** ProductSet of FiniteSets in the Complex Plane. **
# For Cases like ComplexRegion({2, 4}*{3}), It
# would return {2 + 3*I, 4 + 3*I}
# FIXME: This should probably be handled with something like:
# return ImageSet(Lambda((x, y), x+I*y), sets).rewrite(FiniteSet)
complex_num = []
for x in sets.args[0]:
for y in sets.args[1]:
complex_num.append(x + S.ImaginaryUnit*y)
return FiniteSet(*complex_num)
else:
return Set.__new__(cls, sets)
@property
def expr(self):
x, y = self.variables
return x + S.ImaginaryUnit*y
class PolarComplexRegion(ComplexRegion):
"""
Set representing a polar region of the complex plane.
Z = {z in C | z = r*[cos(theta) + I*sin(theta)], r in [r], theta in [theta]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion, Interval
>>> from sympy import oo, pi, I
>>> rset = Interval(0, oo)
>>> thetaset = Interval(0, pi)
>>> upper_half_plane = ComplexRegion(rset * thetaset, polar=True)
>>> 1 + I in upper_half_plane
True
>>> 1 - I in upper_half_plane
False
See also
========
ComplexRegion
CartesianComplexRegion
Complexes
"""
polar = True
variables = symbols('r, theta', cls=Dummy)
def __new__(cls, sets):
new_sets = []
# sets is Union of ProductSets
if not sets.is_ProductSet:
for k in sets.args:
new_sets.append(k)
# sets is ProductSets
else:
new_sets.append(sets)
# Normalize input theta
for k, v in enumerate(new_sets):
new_sets[k] = ProductSet(v.args[0],
normalize_theta_set(v.args[1]))
sets = Union(*new_sets)
return Set.__new__(cls, sets)
@property
def expr(self):
from sympy.functions.elementary.trigonometric import sin, cos
r, theta = self.variables
return r*(cos(theta) + S.ImaginaryUnit*sin(theta))
class Complexes(CartesianComplexRegion, metaclass=Singleton):
"""
The Set of all complex numbers
Examples
========
>>> from sympy import S, I
>>> S.Complexes
Complexes
>>> 1 + I in S.Complexes
True
See also
========
Reals
ComplexRegion
"""
is_empty = False
is_finite_set = False
# Override property from superclass since Complexes has no args
@property
def sets(self):
return ProductSet(S.Reals, S.Reals)
def __new__(cls):
return Set.__new__(cls)
def __str__(self):
return "S.Complexes"
def __repr__(self):
return "S.Complexes"
|
b1c00b48ec8c9ef6d6a356a51deb3fc8d38ed4c1daec6be7a1f0a07db90bbf49 | from typing import Optional
from collections import defaultdict
import inspect
from sympy.core.basic import Basic
from sympy.core.compatibility import iterable, ordered, reduce
from sympy.core.containers import Tuple
from sympy.core.decorators import (deprecated, sympify_method_args,
sympify_return)
from sympy.core.evalf import EvalfMixin, prec_to_dps
from sympy.core.parameters import global_parameters
from sympy.core.expr import Expr
from sympy.core.logic import (FuzzyBool, fuzzy_bool, fuzzy_or, fuzzy_and,
fuzzy_not)
from sympy.core.numbers import Float
from sympy.core.operations import LatticeOp
from sympy.core.relational import Eq, Ne, is_lt
from sympy.core.singleton import Singleton, S
from sympy.core.symbol import Symbol, Dummy, uniquely_named_symbol
from sympy.core.sympify import _sympify, sympify, converter
from sympy.logic.boolalg import And, Or, Not, Xor, true, false
from sympy.sets.contains import Contains
from sympy.utilities import subsets
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import iproduct, sift, roundrobin
from sympy.utilities.misc import func_name, filldedent
from mpmath import mpi, mpf
tfn = defaultdict(lambda: None, {
True: S.true,
S.true: S.true,
False: S.false,
S.false: S.false})
@sympify_method_args
class Set(Basic):
"""
The base class for any kind of set.
Explanation
===========
This is not meant to be used directly as a container of items. It does not
behave like the builtin ``set``; see :class:`FiniteSet` for that.
Real intervals are represented by the :class:`Interval` class and unions of
sets by the :class:`Union` class. The empty set is represented by the
:class:`EmptySet` class and available as a singleton as ``S.EmptySet``.
"""
is_number = False
is_iterable = False
is_interval = False
is_FiniteSet = False
is_Interval = False
is_ProductSet = False
is_Union = False
is_Intersection = None # type: Optional[bool]
is_UniversalSet = None # type: Optional[bool]
is_Complement = None # type: Optional[bool]
is_ComplexRegion = False
is_empty = None # type: FuzzyBool
is_finite_set = None # type: FuzzyBool
@property # type: ignore
@deprecated(useinstead="is S.EmptySet or is_empty",
issue=16946, deprecated_since_version="1.5")
def is_EmptySet(self):
return None
@staticmethod
def _infimum_key(expr):
"""
Return infimum (if possible) else S.Infinity.
"""
try:
infimum = expr.inf
assert infimum.is_comparable
infimum = infimum.evalf() # issue #18505
except (NotImplementedError,
AttributeError, AssertionError, ValueError):
infimum = S.Infinity
return infimum
def union(self, other):
"""
Returns the union of ``self`` and ``other``.
Examples
========
As a shortcut it is possible to use the '+' operator:
>>> from sympy import Interval, FiniteSet
>>> Interval(0, 1).union(Interval(2, 3))
Union(Interval(0, 1), Interval(2, 3))
>>> Interval(0, 1) + Interval(2, 3)
Union(Interval(0, 1), Interval(2, 3))
>>> Interval(1, 2, True, True) + FiniteSet(2, 3)
Union(FiniteSet(3), Interval.Lopen(1, 2))
Similarly it is possible to use the '-' operator for set differences:
>>> Interval(0, 2) - Interval(0, 1)
Interval.Lopen(1, 2)
>>> Interval(1, 3) - FiniteSet(2)
Union(Interval.Ropen(1, 2), Interval.Lopen(2, 3))
"""
return Union(self, other)
def intersect(self, other):
"""
Returns the intersection of 'self' and 'other'.
Examples
========
>>> from sympy import Interval
>>> Interval(1, 3).intersect(Interval(1, 2))
Interval(1, 2)
>>> from sympy import imageset, Lambda, symbols, S
>>> n, m = symbols('n m')
>>> a = imageset(Lambda(n, 2*n), S.Integers)
>>> a.intersect(imageset(Lambda(m, 2*m + 1), S.Integers))
EmptySet
"""
return Intersection(self, other)
def intersection(self, other):
"""
Alias for :meth:`intersect()`
"""
return self.intersect(other)
def is_disjoint(self, other):
"""
Returns True if ``self`` and ``other`` are disjoint.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 2).is_disjoint(Interval(1, 2))
False
>>> Interval(0, 2).is_disjoint(Interval(3, 4))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Disjoint_sets
"""
return self.intersect(other) == S.EmptySet
def isdisjoint(self, other):
"""
Alias for :meth:`is_disjoint()`
"""
return self.is_disjoint(other)
def complement(self, universe):
r"""
The complement of 'self' w.r.t the given universe.
Examples
========
>>> from sympy import Interval, S
>>> Interval(0, 1).complement(S.Reals)
Union(Interval.open(-oo, 0), Interval.open(1, oo))
>>> Interval(0, 1).complement(S.UniversalSet)
Complement(UniversalSet, Interval(0, 1))
"""
return Complement(universe, self)
def _complement(self, other):
# this behaves as other - self
if isinstance(self, ProductSet) and isinstance(other, ProductSet):
# If self and other are disjoint then other - self == self
if len(self.sets) != len(other.sets):
return other
# There can be other ways to represent this but this gives:
# (A x B) - (C x D) = ((A - C) x B) U (A x (B - D))
overlaps = []
pairs = list(zip(self.sets, other.sets))
for n in range(len(pairs)):
sets = (o if i != n else o-s for i, (s, o) in enumerate(pairs))
overlaps.append(ProductSet(*sets))
return Union(*overlaps)
elif isinstance(other, Interval):
if isinstance(self, Interval) or isinstance(self, FiniteSet):
return Intersection(other, self.complement(S.Reals))
elif isinstance(other, Union):
return Union(*(o - self for o in other.args))
elif isinstance(other, Complement):
return Complement(other.args[0], Union(other.args[1], self), evaluate=False)
elif isinstance(other, EmptySet):
return S.EmptySet
elif isinstance(other, FiniteSet):
from sympy.utilities.iterables import sift
sifted = sift(other, lambda x: fuzzy_bool(self.contains(x)))
# ignore those that are contained in self
return Union(FiniteSet(*(sifted[False])),
Complement(FiniteSet(*(sifted[None])), self, evaluate=False)
if sifted[None] else S.EmptySet)
def symmetric_difference(self, other):
"""
Returns symmetric difference of ``self`` and ``other``.
Examples
========
>>> from sympy import Interval, S
>>> Interval(1, 3).symmetric_difference(S.Reals)
Union(Interval.open(-oo, 1), Interval.open(3, oo))
>>> Interval(1, 10).symmetric_difference(S.Reals)
Union(Interval.open(-oo, 1), Interval.open(10, oo))
>>> from sympy import S, EmptySet
>>> S.Reals.symmetric_difference(EmptySet)
Reals
References
==========
.. [1] https://en.wikipedia.org/wiki/Symmetric_difference
"""
return SymmetricDifference(self, other)
def _symmetric_difference(self, other):
return Union(Complement(self, other), Complement(other, self))
@property
def inf(self):
"""
The infimum of ``self``.
Examples
========
>>> from sympy import Interval, Union
>>> Interval(0, 1).inf
0
>>> Union(Interval(0, 1), Interval(2, 3)).inf
0
"""
return self._inf
@property
def _inf(self):
raise NotImplementedError("(%s)._inf" % self)
@property
def sup(self):
"""
The supremum of ``self``.
Examples
========
>>> from sympy import Interval, Union
>>> Interval(0, 1).sup
1
>>> Union(Interval(0, 1), Interval(2, 3)).sup
3
"""
return self._sup
@property
def _sup(self):
raise NotImplementedError("(%s)._sup" % self)
def contains(self, other):
"""
Returns a SymPy value indicating whether ``other`` is contained
in ``self``: ``true`` if it is, ``false`` if it isn't, else
an unevaluated ``Contains`` expression (or, as in the case of
ConditionSet and a union of FiniteSet/Intervals, an expression
indicating the conditions for containment).
Examples
========
>>> from sympy import Interval, S
>>> from sympy.abc import x
>>> Interval(0, 1).contains(0.5)
True
As a shortcut it is possible to use the 'in' operator, but that
will raise an error unless an affirmative true or false is not
obtained.
>>> Interval(0, 1).contains(x)
(0 <= x) & (x <= 1)
>>> x in Interval(0, 1)
Traceback (most recent call last):
...
TypeError: did not evaluate to a bool: None
The result of 'in' is a bool, not a SymPy value
>>> 1 in Interval(0, 2)
True
>>> _ is S.true
False
"""
other = sympify(other, strict=True)
c = self._contains(other)
if isinstance(c, Contains):
return c
if c is None:
return Contains(other, self, evaluate=False)
b = tfn[c]
if b is None:
return c
return b
def _contains(self, other):
raise NotImplementedError(filldedent('''
(%s)._contains(%s) is not defined. This method, when
defined, will receive a sympified object. The method
should return True, False, None or something that
expresses what must be true for the containment of that
object in self to be evaluated. If None is returned
then a generic Contains object will be returned
by the ``contains`` method.''' % (self, other)))
def is_subset(self, other):
"""
Returns True if ``self`` is a subset of ``other``.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 0.5).is_subset(Interval(0, 1))
True
>>> Interval(0, 1).is_subset(Interval(0, 1, left_open=True))
False
"""
if not isinstance(other, Set):
raise ValueError("Unknown argument '%s'" % other)
# Handle the trivial cases
if self == other:
return True
is_empty = self.is_empty
if is_empty is True:
return True
elif fuzzy_not(is_empty) and other.is_empty:
return False
if self.is_finite_set is False and other.is_finite_set:
return False
# Dispatch on subclass rules
ret = self._eval_is_subset(other)
if ret is not None:
return ret
ret = other._eval_is_superset(self)
if ret is not None:
return ret
# Use pairwise rules from multiple dispatch
from sympy.sets.handlers.issubset import is_subset_sets
ret = is_subset_sets(self, other)
if ret is not None:
return ret
# Fall back on computing the intersection
# XXX: We shouldn't do this. A query like this should be handled
# without evaluating new Set objects. It should be the other way round
# so that the intersect method uses is_subset for evaluation.
if self.intersect(other) == self:
return True
def _eval_is_subset(self, other):
'''Returns a fuzzy bool for whether self is a subset of other.'''
return None
def _eval_is_superset(self, other):
'''Returns a fuzzy bool for whether self is a subset of other.'''
return None
# This should be deprecated:
def issubset(self, other):
"""
Alias for :meth:`is_subset()`
"""
return self.is_subset(other)
def is_proper_subset(self, other):
"""
Returns True if ``self`` is a proper subset of ``other``.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 0.5).is_proper_subset(Interval(0, 1))
True
>>> Interval(0, 1).is_proper_subset(Interval(0, 1))
False
"""
if isinstance(other, Set):
return self != other and self.is_subset(other)
else:
raise ValueError("Unknown argument '%s'" % other)
def is_superset(self, other):
"""
Returns True if ``self`` is a superset of ``other``.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 0.5).is_superset(Interval(0, 1))
False
>>> Interval(0, 1).is_superset(Interval(0, 1, left_open=True))
True
"""
if isinstance(other, Set):
return other.is_subset(self)
else:
raise ValueError("Unknown argument '%s'" % other)
# This should be deprecated:
def issuperset(self, other):
"""
Alias for :meth:`is_superset()`
"""
return self.is_superset(other)
def is_proper_superset(self, other):
"""
Returns True if ``self`` is a proper superset of ``other``.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).is_proper_superset(Interval(0, 0.5))
True
>>> Interval(0, 1).is_proper_superset(Interval(0, 1))
False
"""
if isinstance(other, Set):
return self != other and self.is_superset(other)
else:
raise ValueError("Unknown argument '%s'" % other)
def _eval_powerset(self):
from .powerset import PowerSet
return PowerSet(self)
def powerset(self):
"""
Find the Power set of ``self``.
Examples
========
>>> from sympy import EmptySet, FiniteSet, Interval
A power set of an empty set:
>>> A = EmptySet
>>> A.powerset()
FiniteSet(EmptySet)
A power set of a finite set:
>>> A = FiniteSet(1, 2)
>>> a, b, c = FiniteSet(1), FiniteSet(2), FiniteSet(1, 2)
>>> A.powerset() == FiniteSet(a, b, c, EmptySet)
True
A power set of an interval:
>>> Interval(1, 2).powerset()
PowerSet(Interval(1, 2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Power_set
"""
return self._eval_powerset()
@property
def measure(self):
"""
The (Lebesgue) measure of ``self``.
Examples
========
>>> from sympy import Interval, Union
>>> Interval(0, 1).measure
1
>>> Union(Interval(0, 1), Interval(2, 3)).measure
2
"""
return self._measure
@property
def boundary(self):
"""
The boundary or frontier of a set.
Explanation
===========
A point x is on the boundary of a set S if
1. x is in the closure of S.
I.e. Every neighborhood of x contains a point in S.
2. x is not in the interior of S.
I.e. There does not exist an open set centered on x contained
entirely within S.
There are the points on the outer rim of S. If S is open then these
points need not actually be contained within S.
For example, the boundary of an interval is its start and end points.
This is true regardless of whether or not the interval is open.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).boundary
FiniteSet(0, 1)
>>> Interval(0, 1, True, False).boundary
FiniteSet(0, 1)
"""
return self._boundary
@property
def is_open(self):
"""
Property method to check whether a set is open.
Explanation
===========
A set is open if and only if it has an empty intersection with its
boundary. In particular, a subset A of the reals is open if and only
if each one of its points is contained in an open interval that is a
subset of A.
Examples
========
>>> from sympy import S
>>> S.Reals.is_open
True
>>> S.Rationals.is_open
False
"""
return Intersection(self, self.boundary).is_empty
@property
def is_closed(self):
"""
A property method to check whether a set is closed.
Explanation
===========
A set is closed if its complement is an open set. The closedness of a
subset of the reals is determined with respect to R and its standard
topology.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).is_closed
True
"""
return self.boundary.is_subset(self)
@property
def closure(self):
"""
Property method which returns the closure of a set.
The closure is defined as the union of the set itself and its
boundary.
Examples
========
>>> from sympy import S, Interval
>>> S.Reals.closure
Reals
>>> Interval(0, 1).closure
Interval(0, 1)
"""
return self + self.boundary
@property
def interior(self):
"""
Property method which returns the interior of a set.
The interior of a set S consists all points of S that do not
belong to the boundary of S.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).interior
Interval.open(0, 1)
>>> Interval(0, 1).boundary.interior
EmptySet
"""
return self - self.boundary
@property
def _boundary(self):
raise NotImplementedError()
@property
def _measure(self):
raise NotImplementedError("(%s)._measure" % self)
@sympify_return([('other', 'Set')], NotImplemented)
def __add__(self, other):
return self.union(other)
@sympify_return([('other', 'Set')], NotImplemented)
def __or__(self, other):
return self.union(other)
@sympify_return([('other', 'Set')], NotImplemented)
def __and__(self, other):
return self.intersect(other)
@sympify_return([('other', 'Set')], NotImplemented)
def __mul__(self, other):
return ProductSet(self, other)
@sympify_return([('other', 'Set')], NotImplemented)
def __xor__(self, other):
return SymmetricDifference(self, other)
@sympify_return([('exp', Expr)], NotImplemented)
def __pow__(self, exp):
if not (exp.is_Integer and exp >= 0):
raise ValueError("%s: Exponent must be a positive Integer" % exp)
return ProductSet(*[self]*exp)
@sympify_return([('other', 'Set')], NotImplemented)
def __sub__(self, other):
return Complement(self, other)
def __contains__(self, other):
other = _sympify(other)
c = self._contains(other)
b = tfn[c]
if b is None:
# x in y must evaluate to T or F; to entertain a None
# result with Set use y.contains(x)
raise TypeError('did not evaluate to a bool: %r' % c)
return b
class ProductSet(Set):
"""
Represents a Cartesian Product of Sets.
Explanation
===========
Returns a Cartesian product given several sets as either an iterable
or individual arguments.
Can use '*' operator on any sets for convenient shorthand.
Examples
========
>>> from sympy import Interval, FiniteSet, ProductSet
>>> I = Interval(0, 5); S = FiniteSet(1, 2, 3)
>>> ProductSet(I, S)
ProductSet(Interval(0, 5), FiniteSet(1, 2, 3))
>>> (2, 2) in ProductSet(I, S)
True
>>> Interval(0, 1) * Interval(0, 1) # The unit square
ProductSet(Interval(0, 1), Interval(0, 1))
>>> coin = FiniteSet('H', 'T')
>>> set(coin**2)
{(H, H), (H, T), (T, H), (T, T)}
The Cartesian product is not commutative or associative e.g.:
>>> I*S == S*I
False
>>> (I*I)*I == I*(I*I)
False
Notes
=====
- Passes most operations down to the argument sets
References
==========
.. [1] https://en.wikipedia.org/wiki/Cartesian_product
"""
is_ProductSet = True
def __new__(cls, *sets, **assumptions):
if len(sets) == 1 and iterable(sets[0]) and not isinstance(sets[0], (Set, set)):
SymPyDeprecationWarning(
feature="ProductSet(iterable)",
useinstead="ProductSet(*iterable)",
issue=17557,
deprecated_since_version="1.5"
).warn()
sets = tuple(sets[0])
sets = [sympify(s) for s in sets]
if not all(isinstance(s, Set) for s in sets):
raise TypeError("Arguments to ProductSet should be of type Set")
# Nullary product of sets is *not* the empty set
if len(sets) == 0:
return FiniteSet(())
if S.EmptySet in sets:
return S.EmptySet
return Basic.__new__(cls, *sets, **assumptions)
@property
def sets(self):
return self.args
def flatten(self):
def _flatten(sets):
for s in sets:
if s.is_ProductSet:
yield from _flatten(s.sets)
else:
yield s
return ProductSet(*_flatten(self.sets))
def _contains(self, element):
"""
'in' operator for ProductSets.
Examples
========
>>> from sympy import Interval
>>> (2, 3) in Interval(0, 5) * Interval(0, 5)
True
>>> (10, 10) in Interval(0, 5) * Interval(0, 5)
False
Passes operation on to constituent sets
"""
if element.is_Symbol:
return None
if not isinstance(element, Tuple) or len(element) != len(self.sets):
return False
return fuzzy_and(s._contains(e) for s, e in zip(self.sets, element))
def as_relational(self, *symbols):
symbols = [_sympify(s) for s in symbols]
if len(symbols) != len(self.sets) or not all(
i.is_Symbol for i in symbols):
raise ValueError(
'number of symbols must match the number of sets')
return And(*[s.as_relational(i) for s, i in zip(self.sets, symbols)])
@property
def _boundary(self):
return Union(*(ProductSet(*(b + b.boundary if i != j else b.boundary
for j, b in enumerate(self.sets)))
for i, a in enumerate(self.sets)))
@property
def is_iterable(self):
"""
A property method which tests whether a set is iterable or not.
Returns True if set is iterable, otherwise returns False.
Examples
========
>>> from sympy import FiniteSet, Interval
>>> I = Interval(0, 1)
>>> A = FiniteSet(1, 2, 3, 4, 5)
>>> I.is_iterable
False
>>> A.is_iterable
True
"""
return all(set.is_iterable for set in self.sets)
def __iter__(self):
"""
A method which implements is_iterable property method.
If self.is_iterable returns True (both constituent sets are iterable),
then return the Cartesian Product. Otherwise, raise TypeError.
"""
return iproduct(*self.sets)
@property
def is_empty(self):
return fuzzy_or(s.is_empty for s in self.sets)
@property
def is_finite_set(self):
all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
return fuzzy_or([self.is_empty, all_finite])
@property
def _measure(self):
measure = 1
for s in self.sets:
measure *= s.measure
return measure
def __len__(self):
return reduce(lambda a, b: a*b, (len(s) for s in self.args))
def __bool__(self):
return all([bool(s) for s in self.sets])
class Interval(Set, EvalfMixin):
"""
Represents a real interval as a Set.
Usage:
Returns an interval with end points "start" and "end".
For left_open=True (default left_open is False) the interval
will be open on the left. Similarly, for right_open=True the interval
will be open on the right.
Examples
========
>>> from sympy import Symbol, Interval
>>> Interval(0, 1)
Interval(0, 1)
>>> Interval.Ropen(0, 1)
Interval.Ropen(0, 1)
>>> Interval.Ropen(0, 1)
Interval.Ropen(0, 1)
>>> Interval.Lopen(0, 1)
Interval.Lopen(0, 1)
>>> Interval.open(0, 1)
Interval.open(0, 1)
>>> a = Symbol('a', real=True)
>>> Interval(0, a)
Interval(0, a)
Notes
=====
- Only real end points are supported
- Interval(a, b) with a > b will return the empty set
- Use the evalf() method to turn an Interval into an mpmath
'mpi' interval instance
References
==========
.. [1] https://en.wikipedia.org/wiki/Interval_%28mathematics%29
"""
is_Interval = True
def __new__(cls, start, end, left_open=False, right_open=False):
start = _sympify(start)
end = _sympify(end)
left_open = _sympify(left_open)
right_open = _sympify(right_open)
if not all(isinstance(a, (type(true), type(false)))
for a in [left_open, right_open]):
raise NotImplementedError(
"left_open and right_open can have only true/false values, "
"got %s and %s" % (left_open, right_open))
# Only allow real intervals
if fuzzy_not(fuzzy_and(i.is_extended_real for i in (start, end, end-start))):
raise ValueError("Non-real intervals are not supported")
# evaluate if possible
if is_lt(end, start):
return S.EmptySet
elif (end - start).is_negative:
return S.EmptySet
if end == start and (left_open or right_open):
return S.EmptySet
if end == start and not (left_open or right_open):
if start is S.Infinity or start is S.NegativeInfinity:
return S.EmptySet
return FiniteSet(end)
# Make sure infinite interval end points are open.
if start is S.NegativeInfinity:
left_open = true
if end is S.Infinity:
right_open = true
if start == S.Infinity or end == S.NegativeInfinity:
return S.EmptySet
return Basic.__new__(cls, start, end, left_open, right_open)
@property
def start(self):
"""
The left end point of ``self``.
This property takes the same value as the 'inf' property.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).start
0
"""
return self._args[0]
_inf = left = start
@classmethod
def open(cls, a, b):
"""Return an interval including neither boundary."""
return cls(a, b, True, True)
@classmethod
def Lopen(cls, a, b):
"""Return an interval not including the left boundary."""
return cls(a, b, True, False)
@classmethod
def Ropen(cls, a, b):
"""Return an interval not including the right boundary."""
return cls(a, b, False, True)
@property
def end(self):
"""
The right end point of 'self'.
This property takes the same value as the 'sup' property.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1).end
1
"""
return self._args[1]
_sup = right = end
@property
def left_open(self):
"""
True if ``self`` is left-open.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1, left_open=True).left_open
True
>>> Interval(0, 1, left_open=False).left_open
False
"""
return self._args[2]
@property
def right_open(self):
"""
True if ``self`` is right-open.
Examples
========
>>> from sympy import Interval
>>> Interval(0, 1, right_open=True).right_open
True
>>> Interval(0, 1, right_open=False).right_open
False
"""
return self._args[3]
@property
def is_empty(self):
if self.left_open or self.right_open:
cond = self.start >= self.end # One/both bounds open
else:
cond = self.start > self.end # Both bounds closed
return fuzzy_bool(cond)
@property
def is_finite_set(self):
return self.measure.is_zero
def _complement(self, other):
if other == S.Reals:
a = Interval(S.NegativeInfinity, self.start,
True, not self.left_open)
b = Interval(self.end, S.Infinity, not self.right_open, True)
return Union(a, b)
if isinstance(other, FiniteSet):
nums = [m for m in other.args if m.is_number]
if nums == []:
return None
return Set._complement(self, other)
@property
def _boundary(self):
finite_points = [p for p in (self.start, self.end)
if abs(p) != S.Infinity]
return FiniteSet(*finite_points)
def _contains(self, other):
if (not isinstance(other, Expr) or other is S.NaN
or other.is_real is False):
return false
if self.start is S.NegativeInfinity and self.end is S.Infinity:
if other.is_real is not None:
return other.is_real
d = Dummy()
return self.as_relational(d).subs(d, other)
def as_relational(self, x):
"""Rewrite an interval in terms of inequalities and logic operators."""
x = sympify(x)
if self.right_open:
right = x < self.end
else:
right = x <= self.end
if self.left_open:
left = self.start < x
else:
left = self.start <= x
return And(left, right)
@property
def _measure(self):
return self.end - self.start
def to_mpi(self, prec=53):
return mpi(mpf(self.start._eval_evalf(prec)),
mpf(self.end._eval_evalf(prec)))
def _eval_evalf(self, prec):
return Interval(self.left._evalf(prec), self.right._evalf(prec),
left_open=self.left_open, right_open=self.right_open)
def _is_comparable(self, other):
is_comparable = self.start.is_comparable
is_comparable &= self.end.is_comparable
is_comparable &= other.start.is_comparable
is_comparable &= other.end.is_comparable
return is_comparable
@property
def is_left_unbounded(self):
"""Return ``True`` if the left endpoint is negative infinity. """
return self.left is S.NegativeInfinity or self.left == Float("-inf")
@property
def is_right_unbounded(self):
"""Return ``True`` if the right endpoint is positive infinity. """
return self.right is S.Infinity or self.right == Float("+inf")
def _eval_Eq(self, other):
if not isinstance(other, Interval):
if isinstance(other, FiniteSet):
return false
elif isinstance(other, Set):
return None
return false
class Union(Set, LatticeOp, EvalfMixin):
"""
Represents a union of sets as a :class:`Set`.
Examples
========
>>> from sympy import Union, Interval
>>> Union(Interval(1, 2), Interval(3, 4))
Union(Interval(1, 2), Interval(3, 4))
The Union constructor will always try to merge overlapping intervals,
if possible. For example:
>>> Union(Interval(1, 2), Interval(2, 3))
Interval(1, 3)
See Also
========
Intersection
References
==========
.. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29
"""
is_Union = True
@property
def identity(self):
return S.EmptySet
@property
def zero(self):
return S.UniversalSet
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs to merge intersections and iterables
args = _sympify(args)
# Reduce sets using known rules
if evaluate:
args = list(cls._new_args_filter(args))
return simplify_union(args)
args = list(ordered(args, Set._infimum_key))
obj = Basic.__new__(cls, *args)
obj._argset = frozenset(args)
return obj
@property
def args(self):
return self._args
def _complement(self, universe):
# DeMorgan's Law
return Intersection(s.complement(universe) for s in self.args)
@property
def _inf(self):
# We use Min so that sup is meaningful in combination with symbolic
# interval end points.
from sympy.functions.elementary.miscellaneous import Min
return Min(*[set.inf for set in self.args])
@property
def _sup(self):
# We use Max so that sup is meaningful in combination with symbolic
# end points.
from sympy.functions.elementary.miscellaneous import Max
return Max(*[set.sup for set in self.args])
@property
def is_empty(self):
return fuzzy_and(set.is_empty for set in self.args)
@property
def is_finite_set(self):
return fuzzy_and(set.is_finite_set for set in self.args)
@property
def _measure(self):
# Measure of a union is the sum of the measures of the sets minus
# the sum of their pairwise intersections plus the sum of their
# triple-wise intersections minus ... etc...
# Sets is a collection of intersections and a set of elementary
# sets which made up those intersections (called "sos" for set of sets)
# An example element might of this list might be:
# ( {A,B,C}, A.intersect(B).intersect(C) )
# Start with just elementary sets ( ({A}, A), ({B}, B), ... )
# Then get and subtract ( ({A,B}, (A int B), ... ) while non-zero
sets = [(FiniteSet(s), s) for s in self.args]
measure = 0
parity = 1
while sets:
# Add up the measure of these sets and add or subtract it to total
measure += parity * sum(inter.measure for sos, inter in sets)
# For each intersection in sets, compute the intersection with every
# other set not already part of the intersection.
sets = ((sos + FiniteSet(newset), newset.intersect(intersection))
for sos, intersection in sets for newset in self.args
if newset not in sos)
# Clear out sets with no measure
sets = [(sos, inter) for sos, inter in sets if inter.measure != 0]
# Clear out duplicates
sos_list = []
sets_list = []
for set in sets:
if set[0] in sos_list:
continue
else:
sos_list.append(set[0])
sets_list.append(set)
sets = sets_list
# Flip Parity - next time subtract/add if we added/subtracted here
parity *= -1
return measure
@property
def _boundary(self):
def boundary_of_set(i):
""" The boundary of set i minus interior of all other sets """
b = self.args[i].boundary
for j, a in enumerate(self.args):
if j != i:
b = b - a.interior
return b
return Union(*map(boundary_of_set, range(len(self.args))))
def _contains(self, other):
return Or(*[s.contains(other) for s in self.args])
def is_subset(self, other):
return fuzzy_and(s.is_subset(other) for s in self.args)
def as_relational(self, symbol):
"""Rewrite a Union in terms of equalities and logic operators. """
if all(isinstance(i, (FiniteSet, Interval)) for i in self.args):
if len(self.args) == 2:
a, b = self.args
if (a.sup == b.inf and a.inf is S.NegativeInfinity
and b.sup is S.Infinity):
return And(Ne(symbol, a.sup), symbol < b.sup, symbol > a.inf)
return Or(*[set.as_relational(symbol) for set in self.args])
raise NotImplementedError('relational of Union with non-Intervals')
@property
def is_iterable(self):
return all(arg.is_iterable for arg in self.args)
def _eval_evalf(self, prec):
try:
return Union(*(set._eval_evalf(prec) for set in self.args))
except (TypeError, ValueError, NotImplementedError):
import sys
raise (TypeError("Not all sets are evalf-able"),
None,
sys.exc_info()[2])
def __iter__(self):
return roundrobin(*(iter(arg) for arg in self.args))
class Intersection(Set, LatticeOp):
"""
Represents an intersection of sets as a :class:`Set`.
Examples
========
>>> from sympy import Intersection, Interval
>>> Intersection(Interval(1, 3), Interval(2, 4))
Interval(2, 3)
We often use the .intersect method
>>> Interval(1,3).intersect(Interval(2,4))
Interval(2, 3)
See Also
========
Union
References
==========
.. [1] https://en.wikipedia.org/wiki/Intersection_%28set_theory%29
"""
is_Intersection = True
@property
def identity(self):
return S.UniversalSet
@property
def zero(self):
return S.EmptySet
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs to merge intersections and iterables
args = list(ordered(set(_sympify(args))))
# Reduce sets using known rules
if evaluate:
args = list(cls._new_args_filter(args))
return simplify_intersection(args)
args = list(ordered(args, Set._infimum_key))
obj = Basic.__new__(cls, *args)
obj._argset = frozenset(args)
return obj
@property
def args(self):
return self._args
@property
def is_iterable(self):
return any(arg.is_iterable for arg in self.args)
@property
def is_finite_set(self):
if fuzzy_or(arg.is_finite_set for arg in self.args):
return True
@property
def _inf(self):
raise NotImplementedError()
@property
def _sup(self):
raise NotImplementedError()
def _contains(self, other):
return And(*[set.contains(other) for set in self.args])
def __iter__(self):
sets_sift = sift(self.args, lambda x: x.is_iterable)
completed = False
candidates = sets_sift[True] + sets_sift[None]
finite_candidates, others = [], []
for candidate in candidates:
length = None
try:
length = len(candidate)
except TypeError:
others.append(candidate)
if length is not None:
finite_candidates.append(candidate)
finite_candidates.sort(key=len)
for s in finite_candidates + others:
other_sets = set(self.args) - {s}
other = Intersection(*other_sets, evaluate=False)
completed = True
for x in s:
try:
if x in other:
yield x
except TypeError:
completed = False
if completed:
return
if not completed:
if not candidates:
raise TypeError("None of the constituent sets are iterable")
raise TypeError(
"The computation had not completed because of the "
"undecidable set membership is found in every candidates.")
@staticmethod
def _handle_finite_sets(args):
'''Simplify intersection of one or more FiniteSets and other sets'''
# First separate the FiniteSets from the others
fs_args, others = sift(args, lambda x: x.is_FiniteSet, binary=True)
# Let the caller handle intersection of non-FiniteSets
if not fs_args:
return
# Convert to Python sets and build the set of all elements
fs_sets = [set(fs) for fs in fs_args]
all_elements = reduce(lambda a, b: a | b, fs_sets, set())
# Extract elements that are definitely in or definitely not in the
# intersection. Here we check contains for all of args.
definite = set()
for e in all_elements:
inall = fuzzy_and(s.contains(e) for s in args)
if inall is True:
definite.add(e)
if inall is not None:
for s in fs_sets:
s.discard(e)
# At this point all elements in all of fs_sets are possibly in the
# intersection. In some cases this is because they are definitely in
# the intersection of the finite sets but it's not clear if they are
# members of others. We might have {m, n}, {m}, and Reals where we
# don't know if m or n is real. We want to remove n here but it is
# possibly in because it might be equal to m. So what we do now is
# extract the elements that are definitely in the remaining finite
# sets iteratively until we end up with {n}, {}. At that point if we
# get any empty set all remaining elements are discarded.
fs_elements = reduce(lambda a, b: a | b, fs_sets, set())
# Need fuzzy containment testing
fs_symsets = [FiniteSet(*s) for s in fs_sets]
while fs_elements:
for e in fs_elements:
infs = fuzzy_and(s.contains(e) for s in fs_symsets)
if infs is True:
definite.add(e)
if infs is not None:
for n, s in enumerate(fs_sets):
# Update Python set and FiniteSet
if e in s:
s.remove(e)
fs_symsets[n] = FiniteSet(*s)
fs_elements.remove(e)
break
# If we completed the for loop without removing anything we are
# done so quit the outer while loop
else:
break
# If any of the sets of remainder elements is empty then we discard
# all of them for the intersection.
if not all(fs_sets):
fs_sets = [set()]
# Here we fold back the definitely included elements into each fs.
# Since they are definitely included they must have been members of
# each FiniteSet to begin with. We could instead fold these in with a
# Union at the end to get e.g. {3}|({x}&{y}) rather than {3,x}&{3,y}.
if definite:
fs_sets = [fs | definite for fs in fs_sets]
if fs_sets == [set()]:
return S.EmptySet
sets = [FiniteSet(*s) for s in fs_sets]
# Any set in others is redundant if it contains all the elements that
# are in the finite sets so we don't need it in the Intersection
all_elements = reduce(lambda a, b: a | b, fs_sets, set())
is_redundant = lambda o: all(fuzzy_bool(o.contains(e)) for e in all_elements)
others = [o for o in others if not is_redundant(o)]
if others:
rest = Intersection(*others)
# XXX: Maybe this shortcut should be at the beginning. For large
# FiniteSets it could much more efficient to process the other
# sets first...
if rest is S.EmptySet:
return S.EmptySet
# Flatten the Intersection
if rest.is_Intersection:
sets.extend(rest.args)
else:
sets.append(rest)
if len(sets) == 1:
return sets[0]
else:
return Intersection(*sets, evaluate=False)
def as_relational(self, symbol):
"""Rewrite an Intersection in terms of equalities and logic operators"""
return And(*[set.as_relational(symbol) for set in self.args])
class Complement(Set, EvalfMixin):
r"""Represents the set difference or relative complement of a set with
another set.
`A - B = \{x \in A \mid x \notin B\}`
Examples
========
>>> from sympy import Complement, FiniteSet
>>> Complement(FiniteSet(0, 1, 2), FiniteSet(1))
FiniteSet(0, 2)
See Also
=========
Intersection, Union
References
==========
.. [1] http://mathworld.wolfram.com/ComplementSet.html
"""
is_Complement = True
def __new__(cls, a, b, evaluate=True):
if evaluate:
return Complement.reduce(a, b)
return Basic.__new__(cls, a, b)
@staticmethod
def reduce(A, B):
"""
Simplify a :class:`Complement`.
"""
if B == S.UniversalSet or A.is_subset(B):
return S.EmptySet
if isinstance(B, Union):
return Intersection(*(s.complement(A) for s in B.args))
result = B._complement(A)
if result is not None:
return result
else:
return Complement(A, B, evaluate=False)
def _contains(self, other):
A = self.args[0]
B = self.args[1]
return And(A.contains(other), Not(B.contains(other)))
def as_relational(self, symbol):
"""Rewrite a complement in terms of equalities and logic
operators"""
A, B = self.args
A_rel = A.as_relational(symbol)
B_rel = Not(B.as_relational(symbol))
return And(A_rel, B_rel)
@property
def is_iterable(self):
if self.args[0].is_iterable:
return True
@property
def is_finite_set(self):
A, B = self.args
a_finite = A.is_finite_set
if a_finite is True:
return True
elif a_finite is False and B.is_finite_set:
return False
def __iter__(self):
A, B = self.args
for a in A:
if a not in B:
yield a
else:
continue
class EmptySet(Set, metaclass=Singleton):
"""
Represents the empty set. The empty set is available as a singleton
as S.EmptySet.
Examples
========
>>> from sympy import S, Interval
>>> S.EmptySet
EmptySet
>>> Interval(1, 2).intersect(S.EmptySet)
EmptySet
See Also
========
UniversalSet
References
==========
.. [1] https://en.wikipedia.org/wiki/Empty_set
"""
is_empty = True
is_finite_set = True
is_FiniteSet = True
@property # type: ignore
@deprecated(useinstead="is S.EmptySet or is_empty",
issue=16946, deprecated_since_version="1.5")
def is_EmptySet(self):
return True
@property
def _measure(self):
return 0
def _contains(self, other):
return false
def as_relational(self, symbol):
return false
def __len__(self):
return 0
def __iter__(self):
return iter([])
def _eval_powerset(self):
return FiniteSet(self)
@property
def _boundary(self):
return self
def _complement(self, other):
return other
def _symmetric_difference(self, other):
return other
class UniversalSet(Set, metaclass=Singleton):
"""
Represents the set of all things.
The universal set is available as a singleton as S.UniversalSet.
Examples
========
>>> from sympy import S, Interval
>>> S.UniversalSet
UniversalSet
>>> Interval(1, 2).intersect(S.UniversalSet)
Interval(1, 2)
See Also
========
EmptySet
References
==========
.. [1] https://en.wikipedia.org/wiki/Universal_set
"""
is_UniversalSet = True
is_empty = False
is_finite_set = False
def _complement(self, other):
return S.EmptySet
def _symmetric_difference(self, other):
return other
@property
def _measure(self):
return S.Infinity
def _contains(self, other):
return true
def as_relational(self, symbol):
return true
@property
def _boundary(self):
return S.EmptySet
class FiniteSet(Set, EvalfMixin):
"""
Represents a finite set of discrete numbers.
Examples
========
>>> from sympy import FiniteSet
>>> FiniteSet(1, 2, 3, 4)
FiniteSet(1, 2, 3, 4)
>>> 3 in FiniteSet(1, 2, 3, 4)
True
>>> members = [1, 2, 3, 4]
>>> f = FiniteSet(*members)
>>> f
FiniteSet(1, 2, 3, 4)
>>> f - FiniteSet(2)
FiniteSet(1, 3, 4)
>>> f + FiniteSet(2, 5)
FiniteSet(1, 2, 3, 4, 5)
References
==========
.. [1] https://en.wikipedia.org/wiki/Finite_set
"""
is_FiniteSet = True
is_iterable = True
is_empty = False
is_finite_set = True
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
if evaluate:
args = list(map(sympify, args))
if len(args) == 0:
return S.EmptySet
else:
args = list(map(sympify, args))
# keep the form of the first canonical arg
dargs = {}
for i in reversed(list(ordered(args))):
if i.is_Symbol:
dargs[i] = i
else:
try:
dargs[i.as_dummy()] = i
except TypeError:
# e.g. i = class without args like `Interval`
dargs[i] = i
_args_set = set(dargs.values())
args = list(ordered(_args_set, Set._infimum_key))
obj = Basic.__new__(cls, *args)
obj._args_set = _args_set
return obj
def __iter__(self):
return iter(self.args)
def _complement(self, other):
if isinstance(other, Interval):
# Splitting in sub-intervals is only done for S.Reals;
# other cases that need splitting will first pass through
# Set._complement().
nums, syms = [], []
for m in self.args:
if m.is_number and m.is_real:
nums.append(m)
elif m.is_real == False:
pass # drop non-reals
else:
syms.append(m) # various symbolic expressions
if other == S.Reals and nums != []:
nums.sort()
intervals = [] # Build up a list of intervals between the elements
intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]
for a, b in zip(nums[:-1], nums[1:]):
intervals.append(Interval(a, b, True, True)) # both open
intervals.append(Interval(nums[-1], S.Infinity, True, True))
if syms != []:
return Complement(Union(*intervals, evaluate=False),
FiniteSet(*syms), evaluate=False)
else:
return Union(*intervals, evaluate=False)
elif nums == []: # no splitting necessary or possible:
if syms:
return Complement(other, FiniteSet(*syms), evaluate=False)
else:
return other
elif isinstance(other, FiniteSet):
unk = []
for i in self:
c = sympify(other.contains(i))
if c is not S.true and c is not S.false:
unk.append(i)
unk = FiniteSet(*unk)
if unk == self:
return
not_true = []
for i in other:
c = sympify(self.contains(i))
if c is not S.true:
not_true.append(i)
return Complement(FiniteSet(*not_true), unk)
return Set._complement(self, other)
def _contains(self, other):
"""
Tests whether an element, other, is in the set.
Explanation
===========
The actual test is for mathematical equality (as opposed to
syntactical equality). In the worst case all elements of the
set must be checked.
Examples
========
>>> from sympy import FiniteSet
>>> 1 in FiniteSet(1, 2)
True
>>> 5 in FiniteSet(1, 2)
False
"""
if other in self._args_set:
return True
else:
# evaluate=True is needed to override evaluate=False context;
# we need Eq to do the evaluation
return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True))
for e in self.args)
def _eval_is_subset(self, other):
return fuzzy_and(other._contains(e) for e in self.args)
@property
def _boundary(self):
return self
@property
def _inf(self):
from sympy.functions.elementary.miscellaneous import Min
return Min(*self)
@property
def _sup(self):
from sympy.functions.elementary.miscellaneous import Max
return Max(*self)
@property
def measure(self):
return 0
def __len__(self):
return len(self.args)
def as_relational(self, symbol):
"""Rewrite a FiniteSet in terms of equalities and logic operators. """
from sympy.core.relational import Eq
return Or(*[Eq(symbol, elem) for elem in self])
def compare(self, other):
return (hash(self) - hash(other))
def _eval_evalf(self, prec):
return FiniteSet(*[elem.evalf(n=prec_to_dps(prec)) for elem in self])
@property
def _sorted_args(self):
return self.args
def _eval_powerset(self):
return self.func(*[self.func(*s) for s in subsets(self.args)])
def _eval_rewrite_as_PowerSet(self, *args, **kwargs):
"""Rewriting method for a finite set to a power set."""
from .powerset import PowerSet
is2pow = lambda n: bool(n and not n & (n - 1))
if not is2pow(len(self)):
return None
fs_test = lambda arg: isinstance(arg, Set) and arg.is_FiniteSet
if not all(fs_test(arg) for arg in args):
return None
biggest = max(args, key=len)
for arg in subsets(biggest.args):
arg_set = FiniteSet(*arg)
if arg_set not in args:
return None
return PowerSet(biggest)
def __ge__(self, other):
if not isinstance(other, Set):
raise TypeError("Invalid comparison of set with %s" % func_name(other))
return other.is_subset(self)
def __gt__(self, other):
if not isinstance(other, Set):
raise TypeError("Invalid comparison of set with %s" % func_name(other))
return self.is_proper_superset(other)
def __le__(self, other):
if not isinstance(other, Set):
raise TypeError("Invalid comparison of set with %s" % func_name(other))
return self.is_subset(other)
def __lt__(self, other):
if not isinstance(other, Set):
raise TypeError("Invalid comparison of set with %s" % func_name(other))
return self.is_proper_subset(other)
converter[set] = lambda x: FiniteSet(*x)
converter[frozenset] = lambda x: FiniteSet(*x)
class SymmetricDifference(Set):
"""Represents the set of elements which are in either of the
sets and not in their intersection.
Examples
========
>>> from sympy import SymmetricDifference, FiniteSet
>>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5))
FiniteSet(1, 2, 4, 5)
See Also
========
Complement, Union
References
==========
.. [1] https://en.wikipedia.org/wiki/Symmetric_difference
"""
is_SymmetricDifference = True
def __new__(cls, a, b, evaluate=True):
if evaluate:
return SymmetricDifference.reduce(a, b)
return Basic.__new__(cls, a, b)
@staticmethod
def reduce(A, B):
result = B._symmetric_difference(A)
if result is not None:
return result
else:
return SymmetricDifference(A, B, evaluate=False)
def as_relational(self, symbol):
"""Rewrite a symmetric_difference in terms of equalities and
logic operators"""
A, B = self.args
A_rel = A.as_relational(symbol)
B_rel = B.as_relational(symbol)
return Xor(A_rel, B_rel)
@property
def is_iterable(self):
if all(arg.is_iterable for arg in self.args):
return True
def __iter__(self):
args = self.args
union = roundrobin(*(iter(arg) for arg in args))
for item in union:
count = 0
for s in args:
if item in s:
count += 1
if count % 2 == 1:
yield item
class DisjointUnion(Set):
""" Represents the disjoint union (also known as the external disjoint union)
of a finite number of sets.
Examples
========
>>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol
>>> A = FiniteSet(1, 2, 3)
>>> B = Interval(0, 5)
>>> DisjointUnion(A, B)
DisjointUnion(FiniteSet(1, 2, 3), Interval(0, 5))
>>> DisjointUnion(A, B).rewrite(Union)
Union(ProductSet(FiniteSet(1, 2, 3), FiniteSet(0)), ProductSet(Interval(0, 5), FiniteSet(1)))
>>> C = FiniteSet(Symbol('x'), Symbol('y'), Symbol('z'))
>>> DisjointUnion(C, C)
DisjointUnion(FiniteSet(x, y, z), FiniteSet(x, y, z))
>>> DisjointUnion(C, C).rewrite(Union)
ProductSet(FiniteSet(x, y, z), FiniteSet(0, 1))
References
==========
https://en.wikipedia.org/wiki/Disjoint_union
"""
def __new__(cls, *sets):
dj_collection = []
for set_i in sets:
if isinstance(set_i, Set):
dj_collection.append(set_i)
else:
raise TypeError("Invalid input: '%s', input args \
to DisjointUnion must be Sets" % set_i)
obj = Basic.__new__(cls, *dj_collection)
return obj
@property
def sets(self):
return self.args
@property
def is_empty(self):
return fuzzy_and(s.is_empty for s in self.sets)
@property
def is_finite_set(self):
all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
return fuzzy_or([self.is_empty, all_finite])
@property
def is_iterable(self):
if self.is_empty:
return False
iter_flag = True
for set_i in self.sets:
if not set_i.is_empty:
iter_flag = iter_flag and set_i.is_iterable
return iter_flag
def _eval_rewrite_as_Union(self, *sets):
"""
Rewrites the disjoint union as the union of (``set`` x {``i``})
where ``set`` is the element in ``sets`` at index = ``i``
"""
dj_union = EmptySet()
index = 0
for set_i in sets:
if isinstance(set_i, Set):
cross = ProductSet(set_i, FiniteSet(index))
dj_union = Union(dj_union, cross)
index = index + 1
return dj_union
def _contains(self, element):
"""
'in' operator for DisjointUnion
Examples
========
>>> from sympy import Interval, DisjointUnion
>>> D = DisjointUnion(Interval(0, 1), Interval(0, 2))
>>> (0.5, 0) in D
True
>>> (0.5, 1) in D
True
>>> (1.5, 0) in D
False
>>> (1.5, 1) in D
True
Passes operation on to constituent sets
"""
if not isinstance(element, Tuple) or len(element) != 2:
return False
if not element[1].is_Integer:
return False
if element[1] >= len(self.sets) or element[1] < 0:
return False
return element[0] in self.sets[element[1]]
def __iter__(self):
if self.is_iterable:
from sympy.core.numbers import Integer
iters = []
for i, s in enumerate(self.sets):
iters.append(iproduct(s, {Integer(i)}))
return iter(roundrobin(*iters))
else:
raise ValueError("'%s' is not iterable." % self)
def __len__(self):
"""
Returns the length of the disjoint union, i.e., the number of elements in the set.
Examples
========
>>> from sympy import FiniteSet, DisjointUnion, EmptySet
>>> D1 = DisjointUnion(FiniteSet(1, 2, 3, 4), EmptySet, FiniteSet(3, 4, 5))
>>> len(D1)
7
>>> D2 = DisjointUnion(FiniteSet(3, 5, 7), EmptySet, FiniteSet(3, 5, 7))
>>> len(D2)
6
>>> D3 = DisjointUnion(EmptySet, EmptySet)
>>> len(D3)
0
Adds up the lengths of the constituent sets.
"""
if self.is_finite_set:
size = 0
for set in self.sets:
size += len(set)
return size
else:
raise ValueError("'%s' is not a finite set." % self)
def imageset(*args):
r"""
Return an image of the set under transformation ``f``.
Explanation
===========
If this function can't compute the image, it returns an
unevaluated ImageSet object.
.. math::
\{ f(x) \mid x \in \mathrm{self} \}
Examples
========
>>> from sympy import S, Interval, imageset, sin, Lambda
>>> from sympy.abc import x
>>> imageset(x, 2*x, Interval(0, 2))
Interval(0, 4)
>>> imageset(lambda x: 2*x, Interval(0, 2))
Interval(0, 4)
>>> imageset(Lambda(x, sin(x)), Interval(-2, 1))
ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
>>> imageset(sin, Interval(-2, 1))
ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
>>> imageset(lambda y: x + y, Interval(-2, 1))
ImageSet(Lambda(y, x + y), Interval(-2, 1))
Expressions applied to the set of Integers are simplified
to show as few negatives as possible and linear expressions
are converted to a canonical form. If this is not desirable
then the unevaluated ImageSet should be used.
>>> imageset(x, -2*x + 5, S.Integers)
ImageSet(Lambda(x, 2*x + 1), Integers)
See Also
========
sympy.sets.fancysets.ImageSet
"""
from sympy.core import Lambda
from sympy.sets.fancysets import ImageSet
from sympy.sets.setexpr import set_function
if len(args) < 2:
raise ValueError('imageset expects at least 2 args, got: %s' % len(args))
if isinstance(args[0], (Symbol, tuple)) and len(args) > 2:
f = Lambda(args[0], args[1])
set_list = args[2:]
else:
f = args[0]
set_list = args[1:]
if isinstance(f, Lambda):
pass
elif callable(f):
nargs = getattr(f, 'nargs', {})
if nargs:
if len(nargs) != 1:
raise NotImplementedError(filldedent('''
This function can take more than 1 arg
but the potentially complicated set input
has not been analyzed at this point to
know its dimensions. TODO
'''))
N = nargs.args[0]
if N == 1:
s = 'x'
else:
s = [Symbol('x%i' % i) for i in range(1, N + 1)]
else:
s = inspect.signature(f).parameters
dexpr = _sympify(f(*[Dummy() for i in s]))
var = tuple(uniquely_named_symbol(
Symbol(i), dexpr) for i in s)
f = Lambda(var, f(*var))
else:
raise TypeError(filldedent('''
expecting lambda, Lambda, or FunctionClass,
not \'%s\'.''' % func_name(f)))
if any(not isinstance(s, Set) for s in set_list):
name = [func_name(s) for s in set_list]
raise ValueError(
'arguments after mapping should be sets, not %s' % name)
if len(set_list) == 1:
set = set_list[0]
try:
# TypeError if arg count != set dimensions
r = set_function(f, set)
if r is None:
raise TypeError
if not r:
return r
except TypeError:
r = ImageSet(f, set)
if isinstance(r, ImageSet):
f, set = r.args
if f.variables[0] == f.expr:
return set
if isinstance(set, ImageSet):
# XXX: Maybe this should just be:
# f2 = set.lambda
# fun = Lambda(f2.signature, f(*f2.expr))
# return imageset(fun, *set.base_sets)
if len(set.lamda.variables) == 1 and len(f.variables) == 1:
x = set.lamda.variables[0]
y = f.variables[0]
return imageset(
Lambda(x, f.expr.subs(y, set.lamda.expr)), *set.base_sets)
if r is not None:
return r
return ImageSet(f, *set_list)
def is_function_invertible_in_set(func, setv):
"""
Checks whether function ``func`` is invertible when the domain is
restricted to set ``setv``.
"""
from sympy import exp, log
# Functions known to always be invertible:
if func in (exp, log):
return True
u = Dummy("u")
fdiff = func(u).diff(u)
# monotonous functions:
# TODO: check subsets (`func` in `setv`)
if (fdiff > 0) == True or (fdiff < 0) == True:
return True
# TODO: support more
return None
def simplify_union(args):
"""
Simplify a :class:`Union` using known rules.
Explanation
===========
We first start with global rules like 'Merge all FiniteSets'
Then we iterate through all pairs and ask the constituent sets if they
can simplify themselves with any other constituent. This process depends
on ``union_sets(a, b)`` functions.
"""
from sympy.sets.handlers.union import union_sets
# ===== Global Rules =====
if not args:
return S.EmptySet
for arg in args:
if not isinstance(arg, Set):
raise TypeError("Input args to Union must be Sets")
# Merge all finite sets
finite_sets = [x for x in args if x.is_FiniteSet]
if len(finite_sets) > 1:
a = (x for set in finite_sets for x in set)
finite_set = FiniteSet(*a)
args = [finite_set] + [x for x in args if not x.is_FiniteSet]
# ===== Pair-wise Rules =====
# Here we depend on rules built into the constituent sets
args = set(args)
new_args = True
while new_args:
for s in args:
new_args = False
for t in args - {s}:
new_set = union_sets(s, t)
# This returns None if s does not know how to intersect
# with t. Returns the newly intersected set otherwise
if new_set is not None:
if not isinstance(new_set, set):
new_set = {new_set}
new_args = (args - {s, t}).union(new_set)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return Union(*args, evaluate=False)
def simplify_intersection(args):
"""
Simplify an intersection using known rules.
Explanation
===========
We first start with global rules like
'if any empty sets return empty set' and 'distribute any unions'
Then we iterate through all pairs and ask the constituent sets if they
can simplify themselves with any other constituent
"""
# ===== Global Rules =====
if not args:
return S.UniversalSet
for arg in args:
if not isinstance(arg, Set):
raise TypeError("Input args to Union must be Sets")
# If any EmptySets return EmptySet
if S.EmptySet in args:
return S.EmptySet
# Handle Finite sets
rv = Intersection._handle_finite_sets(args)
if rv is not None:
return rv
# If any of the sets are unions, return a Union of Intersections
for s in args:
if s.is_Union:
other_sets = set(args) - {s}
if len(other_sets) > 0:
other = Intersection(*other_sets)
return Union(*(Intersection(arg, other) for arg in s.args))
else:
return Union(*[arg for arg in s.args])
for s in args:
if s.is_Complement:
args.remove(s)
other_sets = args + [s.args[0]]
return Complement(Intersection(*other_sets), s.args[1])
from sympy.sets.handlers.intersection import intersection_sets
# At this stage we are guaranteed not to have any
# EmptySets, FiniteSets, or Unions in the intersection
# ===== Pair-wise Rules =====
# Here we depend on rules built into the constituent sets
args = set(args)
new_args = True
while new_args:
for s in args:
new_args = False
for t in args - {s}:
new_set = intersection_sets(s, t)
# This returns None if s does not know how to intersect
# with t. Returns the newly intersected set otherwise
if new_set is not None:
new_args = (args - {s, t}).union({new_set})
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return Intersection(*args, evaluate=False)
def _handle_finite_sets(op, x, y, commutative):
# Handle finite sets:
fs_args, other = sift([x, y], lambda x: isinstance(x, FiniteSet), binary=True)
if len(fs_args) == 2:
return FiniteSet(*[op(i, j) for i in fs_args[0] for j in fs_args[1]])
elif len(fs_args) == 1:
sets = [_apply_operation(op, other[0], i, commutative) for i in fs_args[0]]
return Union(*sets)
else:
return None
def _apply_operation(op, x, y, commutative):
from sympy.sets import ImageSet
from sympy import symbols,Lambda
d = Dummy('d')
out = _handle_finite_sets(op, x, y, commutative)
if out is None:
out = op(x, y)
if out is None and commutative:
out = op(y, x)
if out is None:
_x, _y = symbols("x y")
if isinstance(x, Set) and not isinstance(y, Set):
out = ImageSet(Lambda(d, op(d, y)), x).doit()
elif not isinstance(x, Set) and isinstance(y, Set):
out = ImageSet(Lambda(d, op(x, d)), y).doit()
else:
out = ImageSet(Lambda((_x, _y), op(_x, _y)), x, y)
return out
def set_add(x, y):
from sympy.sets.handlers.add import _set_add
return _apply_operation(_set_add, x, y, commutative=True)
def set_sub(x, y):
from sympy.sets.handlers.add import _set_sub
return _apply_operation(_set_sub, x, y, commutative=False)
def set_mul(x, y):
from sympy.sets.handlers.mul import _set_mul
return _apply_operation(_set_mul, x, y, commutative=True)
def set_div(x, y):
from sympy.sets.handlers.mul import _set_div
return _apply_operation(_set_div, x, y, commutative=False)
def set_pow(x, y):
from sympy.sets.handlers.power import _set_pow
return _apply_operation(_set_pow, x, y, commutative=False)
def set_function(f, x):
from sympy.sets.handlers.functions import _set_function
return _set_function(f, x)
|
bc24ff7a54fd7bfb75fa09c5a2e350bd115b076e58c36005f0743be80073d4ab | """Implicit plotting module for SymPy.
Explanation
===========
The module implements a data series called ImplicitSeries which is used by
``Plot`` class to plot implicit plots for different backends. The module,
by default, implements plotting using interval arithmetic. It switches to a
fall back algorithm if the expression cannot be plotted using interval arithmetic.
It is also possible to specify to use the fall back algorithm for all plots.
Boolean combinations of expressions cannot be plotted by the fall back
algorithm.
See Also
========
sympy.plotting.plot
References
==========
.. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
Mathematical Formulae with Two Free Variables.
.. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
Arithmetic. Master's thesis. University of Toronto, 1996
"""
from .plot import BaseSeries, Plot
from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
from .intervalmath import interval
from sympy.core.relational import (Equality, GreaterThan, LessThan,
Relational, StrictLessThan, StrictGreaterThan)
from sympy import Eq, Tuple, sympify, Symbol, Dummy
from sympy.external import import_module
from sympy.logic.boolalg import BooleanFunction
from sympy.polys.polyutils import _sort_gens
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import flatten
import warnings
class ImplicitSeries(BaseSeries):
""" Representation for Implicit plot """
is_implicit = True
def __init__(self, expr, var_start_end_x, var_start_end_y,
has_equality, use_interval_math, depth, nb_of_points,
line_color):
super().__init__()
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
self.start_x = float(var_start_end_x[1])
self.end_x = float(var_start_end_x[2])
self.var_y = sympify(var_start_end_y[0])
self.start_y = float(var_start_end_y[1])
self.end_y = float(var_start_end_y[2])
self.get_points = self.get_raster
self.has_equality = has_equality # If the expression has equality, i.e.
#Eq, Greaterthan, LessThan.
self.nb_of_points = nb_of_points
self.use_interval_math = use_interval_math
self.depth = 4 + depth
self.line_color = line_color
def __str__(self):
return ('Implicit equation: %s for '
'%s over %s and %s over %s') % (
str(self.expr),
str(self.var_x),
str((self.start_x, self.end_x)),
str(self.var_y),
str((self.start_y, self.end_y)))
def get_raster(self):
func = experimental_lambdify((self.var_x, self.var_y), self.expr,
use_interval=True)
xinterval = interval(self.start_x, self.end_x)
yinterval = interval(self.start_y, self.end_y)
try:
func(xinterval, yinterval)
except AttributeError:
# XXX: AttributeError("'list' object has no attribute 'is_real'")
# That needs fixing somehow - we shouldn't be catching
# AttributeError here.
if self.use_interval_math:
warnings.warn("Adaptive meshing could not be applied to the"
" expression. Using uniform meshing.")
self.use_interval_math = False
if self.use_interval_math:
return self._get_raster_interval(func)
else:
return self._get_meshes_grid()
def _get_raster_interval(self, func):
""" Uses interval math to adaptively mesh and obtain the plot"""
k = self.depth
interval_list = []
#Create initial 32 divisions
np = import_module('numpy')
xsample = np.linspace(self.start_x, self.end_x, 33)
ysample = np.linspace(self.start_y, self.end_y, 33)
#Add a small jitter so that there are no false positives for equality.
# Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
#which will draw a rectangle.
jitterx = (np.random.rand(
len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
jittery = (np.random.rand(
len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
xsample += jitterx
ysample += jittery
xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
xsample[1:])]
yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
ysample[1:])]
interval_list = [[x, y] for x in xinter for y in yinter]
plot_list = []
#recursive call refinepixels which subdivides the intervals which are
#neither True nor False according to the expression.
def refine_pixels(interval_list):
""" Evaluates the intervals and subdivides the interval if the
expression is partially satisfied."""
temp_interval_list = []
plot_list = []
for intervals in interval_list:
#Convert the array indices to x and y values
intervalx = intervals[0]
intervaly = intervals[1]
func_eval = func(intervalx, intervaly)
#The expression is valid in the interval. Change the contour
#array values to 1.
if func_eval[1] is False or func_eval[0] is False:
pass
elif func_eval == (True, True):
plot_list.append([intervalx, intervaly])
elif func_eval[1] is None or func_eval[0] is None:
#Subdivide
avgx = intervalx.mid
avgy = intervaly.mid
a = interval(intervalx.start, avgx)
b = interval(avgx, intervalx.end)
c = interval(intervaly.start, avgy)
d = interval(avgy, intervaly.end)
temp_interval_list.append([a, c])
temp_interval_list.append([a, d])
temp_interval_list.append([b, c])
temp_interval_list.append([b, d])
return temp_interval_list, plot_list
while k >= 0 and len(interval_list):
interval_list, plot_list_temp = refine_pixels(interval_list)
plot_list.extend(plot_list_temp)
k = k - 1
#Check whether the expression represents an equality
#If it represents an equality, then none of the intervals
#would have satisfied the expression due to floating point
#differences. Add all the undecided values to the plot.
if self.has_equality:
for intervals in interval_list:
intervalx = intervals[0]
intervaly = intervals[1]
func_eval = func(intervalx, intervaly)
if func_eval[1] and func_eval[0] is not False:
plot_list.append([intervalx, intervaly])
return plot_list, 'fill'
def _get_meshes_grid(self):
"""Generates the mesh for generating a contour.
In the case of equality, ``contour`` function of matplotlib can
be used. In other cases, matplotlib's ``contourf`` is used.
"""
equal = False
if isinstance(self.expr, Equality):
expr = self.expr.lhs - self.expr.rhs
equal = True
elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
expr = self.expr.lhs - self.expr.rhs
elif isinstance(self.expr, (LessThan, StrictLessThan)):
expr = self.expr.rhs - self.expr.lhs
else:
raise NotImplementedError("The expression is not supported for "
"plotting in uniform meshed plot.")
np = import_module('numpy')
xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
x_grid, y_grid = np.meshgrid(xarray, yarray)
func = vectorized_lambdify((self.var_x, self.var_y), expr)
z_grid = func(x_grid, y_grid)
z_grid[np.ma.where(z_grid < 0)] = -1
z_grid[np.ma.where(z_grid > 0)] = 1
if equal:
return xarray, yarray, z_grid, 'contour'
else:
return xarray, yarray, z_grid, 'contourf'
@doctest_depends_on(modules=('matplotlib',))
def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
points=300, line_color="blue", show=True, **kwargs):
"""A plot function to plot implicit equations / inequalities.
Arguments
=========
- ``expr`` : The equation / inequality that is to be plotted.
- ``x_var`` (optional) : symbol to plot on x-axis or tuple giving symbol
and range as ``(symbol, xmin, xmax)``
- ``y_var`` (optional) : symbol to plot on y-axis or tuple giving symbol
and range as ``(symbol, ymin, ymax)``
If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
expression will be assigned in the order they are sorted.
The following keyword arguments can also be used:
- ``adaptive`` Boolean. The default value is set to True. It has to be
set to False if you want to use a mesh grid.
- ``depth`` integer. The depth of recursion for adaptive mesh grid.
Default value is 0. Takes value in the range (0, 4).
- ``points`` integer. The number of points if adaptive mesh grid is not
used. Default value is 300.
- ``show`` Boolean. Default value is True. If set to False, the plot will
not be shown. See ``Plot`` for further information.
- ``title`` string. The title for the plot.
- ``xlabel`` string. The label for the x-axis
- ``ylabel`` string. The label for the y-axis
Aesthetics options:
- ``line_color``: float or string. Specifies the color for the plot.
See ``Plot`` to see how to set color for the plots.
Default value is "Blue"
plot_implicit, by default, uses interval arithmetic to plot functions. If
the expression cannot be plotted using interval arithmetic, it defaults to
a generating a contour using a mesh grid of fixed number of points. By
setting adaptive to False, you can force plot_implicit to use the mesh
grid. The mesh grid method can be effective when adaptive plotting using
interval arithmetic, fails to plot with small line width.
Examples
========
Plot expressions:
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import plot_implicit, symbols, Eq, And
>>> x, y = symbols('x y')
Without any ranges for the symbols in the expression:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
With the range for the symbols:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p2 = plot_implicit(
... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
With depth of recursion as argument:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p3 = plot_implicit(
... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
Using mesh grid and not using adaptive meshing:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p4 = plot_implicit(
... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
... adaptive=False)
Using mesh grid without using adaptive meshing with number of points
specified:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p5 = plot_implicit(
... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
... adaptive=False, points=400)
Plotting regions:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p6 = plot_implicit(y > x**2)
Plotting Using boolean conjunctions:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p7 = plot_implicit(And(y > x, y > -x))
When plotting an expression with a single variable (y - 1, for example),
specify the x or the y variable explicitly:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p8 = plot_implicit(y - 1, y_var=y)
>>> p9 = plot_implicit(x - 1, x_var=x)
"""
has_equality = False # Represents whether the expression contains an Equality,
#GreaterThan or LessThan
def arg_expand(bool_expr):
"""
Recursively expands the arguments of an Boolean Function
"""
for arg in bool_expr.args:
if isinstance(arg, BooleanFunction):
arg_expand(arg)
elif isinstance(arg, Relational):
arg_list.append(arg)
arg_list = []
if isinstance(expr, BooleanFunction):
arg_expand(expr)
#Check whether there is an equality in the expression provided.
if any(isinstance(e, (Equality, GreaterThan, LessThan))
for e in arg_list):
has_equality = True
elif not isinstance(expr, Relational):
expr = Eq(expr, 0)
has_equality = True
elif isinstance(expr, (Equality, GreaterThan, LessThan)):
has_equality = True
xyvar = [i for i in (x_var, y_var) if i is not None]
free_symbols = expr.free_symbols
range_symbols = Tuple(*flatten(xyvar)).free_symbols
undeclared = free_symbols - range_symbols
if len(free_symbols & range_symbols) > 2:
raise NotImplementedError("Implicit plotting is not implemented for "
"more than 2 variables")
#Create default ranges if the range is not provided.
default_range = Tuple(-5, 5)
def _range_tuple(s):
if isinstance(s, Symbol):
return Tuple(s) + default_range
if len(s) == 3:
return Tuple(*s)
raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
if len(xyvar) == 0:
xyvar = list(_sort_gens(free_symbols))
var_start_end_x = _range_tuple(xyvar[0])
x = var_start_end_x[0]
if len(xyvar) != 2:
if x in undeclared or not undeclared:
xyvar.append(Dummy('f(%s)' % x.name))
else:
xyvar.append(undeclared.pop())
var_start_end_y = _range_tuple(xyvar[1])
#Check whether the depth is greater than 4 or less than 0.
if depth > 4:
depth = 4
elif depth < 0:
depth = 0
series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
has_equality, adaptive, depth,
points, line_color)
#set the x and y limits
kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
# set the x and y labels
kwargs.setdefault('xlabel', var_start_end_x[0].name)
kwargs.setdefault('ylabel', var_start_end_y[0].name)
p = Plot(series_argument, **kwargs)
if show:
p.show()
return p
|
8a23704f3c221ecd10cbf60dfd25eb34a307709410c53024e434f43383dde61f | """Plotting module for Sympy.
A plot is represented by the ``Plot`` class that contains a reference to the
backend and a list of the data series to be plotted. The data series are
instances of classes meant to simplify getting points and meshes from sympy
expressions. ``plot_backends`` is a dictionary with all the backends.
This module gives only the essential. For all the fancy stuff use directly
the backend. You can get the backend wrapper for every plot from the
``_backend`` attribute. Moreover the data series classes have various useful
methods like ``get_points``, ``get_segments``, ``get_meshes``, etc, that may
be useful if you wish to use another plotting library.
Especially if you need publication ready graphs and this module is not enough
for you - just get the ``_backend`` attribute and add whatever you want
directly to it. In the case of matplotlib (the common way to graph data in
python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
which is the axis and work on them as you would on any other matplotlib object.
Simplicity of code takes much greater importance than performance. Don't use it
if you care at all about performance. A new backend instance is initialized
every time you call ``show()`` and the old one is left to the garbage collector.
"""
import warnings
from collections.abc import Callable
from sympy import sympify, Expr, Tuple, Dummy, Symbol
from sympy.external import import_module
from sympy.core.function import arity
from sympy.utilities.iterables import is_sequence
from .experimental_lambdify import (vectorized_lambdify, lambdify)
# N.B.
# When changing the minimum module version for matplotlib, please change
# the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
# Backend specific imports - textplot
from sympy.plotting.textplot import textplot
# Global variable
# Set to False when running tests / doctests so that the plots don't show.
_show = True
def unset_show():
"""
Disable show(). For use in the tests.
"""
global _show
_show = False
##############################################################################
# The public interface
##############################################################################
class Plot:
"""The central class of the plotting module.
Explanation
===========
For interactive work the function ``plot`` is better suited.
This class permits the plotting of sympy expressions using numerous
backends (matplotlib, textplot, the old pyglet module for sympy, Google
charts api, etc).
The figure can contain an arbitrary number of plots of sympy expressions,
lists of coordinates of points, etc. Plot has a private attribute _series that
contains all data series to be plotted (expressions for lines or surfaces,
lists of points, etc (all subclasses of BaseSeries)). Those data series are
instances of classes not imported by ``from sympy import *``.
The customization of the figure is on two levels. Global options that
concern the figure as a whole (eg title, xlabel, scale, etc) and
per-data series options (eg name) and aesthetics (eg. color, point shape,
line type, etc.).
The difference between options and aesthetics is that an aesthetic can be
a function of the coordinates (or parameters in a parametric plot). The
supported values for an aesthetic are:
- None (the backend uses default values)
- a constant
- a function of one variable (the first coordinate or parameter)
- a function of two variables (the first and second coordinate or
parameters)
- a function of three variables (only in nonparametric 3D plots)
Their implementation depends on the backend so they may not work in some
backends.
If the plot is parametric and the arity of the aesthetic function permits
it the aesthetic is calculated over parameters and not over coordinates.
If the arity does not permit calculation over parameters the calculation is
done over coordinates.
Only cartesian coordinates are supported for the moment, but you can use
the parametric plots to plot in polar, spherical and cylindrical
coordinates.
The arguments for the constructor Plot must be subclasses of BaseSeries.
Any global option can be specified as a keyword argument.
The global options for a figure are:
- title : str
- xlabel : str
- ylabel : str
- legend : bool
- xscale : {'linear', 'log'}
- yscale : {'linear', 'log'}
- axis : bool
- axis_center : tuple of two floats or {'center', 'auto'}
- xlim : tuple of two floats
- ylim : tuple of two floats
- aspect_ratio : tuple of two floats or {'auto'}
- autoscale : bool
- margin : float in [0, 1]
- backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend
- size : optional tuple of two floats, (width, height); default: None
The per data series options and aesthetics are:
There are none in the base series. See below for options for subclasses.
Some data series support additional aesthetics or options:
ListSeries, LineOver1DRangeSeries, Parametric2DLineSeries,
Parametric3DLineSeries support the following:
Aesthetics:
- line_color : function which returns a float.
options:
- label : str
- steps : bool
- integers_only : bool
SurfaceOver2DRangeSeries, ParametricSurfaceSeries support the following:
aesthetics:
- surface_color : function which returns a float.
"""
def __init__(self, *args,
title=None, xlabel=None, ylabel=None, aspect_ratio='auto',
xlim=None, ylim=None, axis_center='auto', axis=True,
xscale='linear', yscale='linear', legend=False, autoscale=True,
margin=0, annotations=None, markers=None, rectangles=None,
fill=None, backend='default', size=None, **kwargs):
super().__init__()
# Options for the graph as a whole.
# The possible values for each option are described in the docstring of
# Plot. They are based purely on convention, no checking is done.
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.aspect_ratio = aspect_ratio
self.axis_center = axis_center
self.axis = axis
self.xscale = xscale
self.yscale = yscale
self.legend = legend
self.autoscale = autoscale
self.margin = margin
self.annotations = annotations
self.markers = markers
self.rectangles = rectangles
self.fill = fill
# Contains the data objects to be plotted. The backend should be smart
# enough to iterate over this list.
self._series = []
self._series.extend(args)
# The backend type. On every show() a new backend instance is created
# in self._backend which is tightly coupled to the Plot instance
# (thanks to the parent attribute of the backend).
if isinstance(backend, str):
self.backend = plot_backends[backend]
elif (type(backend) == type) and issubclass(backend, BaseBackend):
self.backend = backend
else:
raise TypeError(
"backend must be either a string or a subclass of BaseBackend")
is_real = \
lambda lim: all(getattr(i, 'is_real', True) for i in lim)
is_finite = \
lambda lim: all(getattr(i, 'is_finite', True) for i in lim)
# reduce code repetition
def check_and_set(t_name, t):
if t:
if not is_real(t):
raise ValueError(
"All numbers from {}={} must be real".format(t_name, t))
if not is_finite(t):
raise ValueError(
"All numbers from {}={} must be finite".format(t_name, t))
setattr(self, t_name, (float(t[0]), float(t[1])))
self.xlim = None
check_and_set("xlim", xlim)
self.ylim = None
check_and_set("ylim", ylim)
self.size = None
check_and_set("size", size)
def show(self):
# TODO move this to the backend (also for save)
if hasattr(self, '_backend'):
self._backend.close()
self._backend = self.backend(self)
self._backend.show()
def save(self, path):
if hasattr(self, '_backend'):
self._backend.close()
self._backend = self.backend(self)
self._backend.save(path)
def __str__(self):
series_strs = [('[%d]: ' % i) + str(s)
for i, s in enumerate(self._series)]
return 'Plot object containing:\n' + '\n'.join(series_strs)
def __getitem__(self, index):
return self._series[index]
def __setitem__(self, index, *args):
if len(args) == 1 and isinstance(args[0], BaseSeries):
self._series[index] = args
def __delitem__(self, index):
del self._series[index]
def append(self, arg):
"""Adds an element from a plot's series to an existing plot.
Examples
========
Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
second plot's first series object to the first, use the
``append`` method, like so:
.. plot::
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot
>>> x = symbols('x')
>>> p1 = plot(x*x, show=False)
>>> p2 = plot(x, show=False)
>>> p1.append(p2[0])
>>> p1
Plot object containing:
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
[1]: cartesian line: x for x over (-10.0, 10.0)
>>> p1.show()
See Also
========
extend
"""
if isinstance(arg, BaseSeries):
self._series.append(arg)
else:
raise TypeError('Must specify element of plot to append.')
def extend(self, arg):
"""Adds all series from another plot.
Examples
========
Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
second plot to the first, use the ``extend`` method, like so:
.. plot::
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot
>>> x = symbols('x')
>>> p1 = plot(x**2, show=False)
>>> p2 = plot(x, -x, show=False)
>>> p1.extend(p2)
>>> p1
Plot object containing:
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
[1]: cartesian line: x for x over (-10.0, 10.0)
[2]: cartesian line: -x for x over (-10.0, 10.0)
>>> p1.show()
"""
if isinstance(arg, Plot):
self._series.extend(arg._series)
elif is_sequence(arg):
self._series.extend(arg)
else:
raise TypeError('Expecting Plot or sequence of BaseSeries')
class PlotGrid:
"""This class helps to plot subplots from already created sympy plots
in a single figure.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot, plot3d, PlotGrid
>>> x, y = symbols('x, y')
>>> p1 = plot(x, x**2, x**3, (x, -5, 5))
>>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
>>> p3 = plot(x**3, (x, -5, 5))
>>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
Plotting vertically in a single line:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> PlotGrid(2, 1 , p1, p2)
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: x for x over (-5.0, 5.0)
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
Plot[1]:Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
Plotting horizontally in a single line:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> PlotGrid(1, 3 , p2, p3, p4)
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
Plot[1]:Plot object containing:
[0]: cartesian line: x**3 for x over (-5.0, 5.0)
Plot[2]:Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Plotting in a grid form:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> PlotGrid(2, 2, p1, p2 ,p3, p4)
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: x for x over (-5.0, 5.0)
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
Plot[1]:Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
Plot[2]:Plot object containing:
[0]: cartesian line: x**3 for x over (-5.0, 5.0)
Plot[3]:Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
"""
def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
"""
Parameters
==========
nrows :
The number of rows that should be in the grid of the
required subplot.
ncolumns :
The number of columns that should be in the grid
of the required subplot.
nrows and ncolumns together define the required grid.
Arguments
=========
A list of predefined plot objects entered in a row-wise sequence
i.e. plot objects which are to be in the top row of the required
grid are written first, then the second row objects and so on
Keyword arguments
=================
show : Boolean
The default value is set to ``True``. Set show to ``False`` and
the function will not display the subplot. The returned instance
of the ``PlotGrid`` class can then be used to save or display the
plot by calling the ``save()`` and ``show()`` methods
respectively.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
"""
self.nrows = nrows
self.ncolumns = ncolumns
self._series = []
self.args = args
for arg in args:
self._series.append(arg._series)
self.backend = DefaultBackend
self.size = size
if show:
self.show()
def show(self):
if hasattr(self, '_backend'):
self._backend.close()
self._backend = self.backend(self)
self._backend.show()
def save(self, path):
if hasattr(self, '_backend'):
self._backend.close()
self._backend = self.backend(self)
self._backend.save(path)
def __str__(self):
plot_strs = [('Plot[%d]:' % i) + str(plot)
for i, plot in enumerate(self.args)]
return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
##############################################################################
# Data Series
##############################################################################
#TODO more general way to calculate aesthetics (see get_color_array)
### The base class for all series
class BaseSeries:
"""Base class for the data objects containing stuff to be plotted.
Explanation
===========
The backend should check if it supports the data series that it's given.
(eg TextBackend supports only LineOver1DRange).
It's the backend responsibility to know how to use the class of
data series that it's given.
Some data series classes are grouped (using a class attribute like is_2Dline)
according to the api they present (based only on convention). The backend is
not obliged to use that api (eg. The LineOver1DRange belongs to the
is_2Dline group and presents the get_points method, but the
TextBackend does not use the get_points method).
"""
# Some flags follow. The rationale for using flags instead of checking base
# classes is that setting multiple flags is simpler than multiple
# inheritance.
is_2Dline = False
# Some of the backends expect:
# - get_points returning 1D np.arrays list_x, list_y
# - get_segments returning np.array (done in Line2DBaseSeries)
# - get_color_array returning 1D np.array (done in Line2DBaseSeries)
# with the colors calculated at the points from get_points
is_3Dline = False
# Some of the backends expect:
# - get_points returning 1D np.arrays list_x, list_y, list_y
# - get_segments returning np.array (done in Line2DBaseSeries)
# - get_color_array returning 1D np.array (done in Line2DBaseSeries)
# with the colors calculated at the points from get_points
is_3Dsurface = False
# Some of the backends expect:
# - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
# - get_points an alias for get_meshes
is_contour = False
# Some of the backends expect:
# - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
# - get_points an alias for get_meshes
is_implicit = False
# Some of the backends expect:
# - get_meshes returning mesh_x (1D array), mesh_y(1D array,
# mesh_z (2D np.arrays)
# - get_points an alias for get_meshes
# Different from is_contour as the colormap in backend will be
# different
is_parametric = False
# The calculation of aesthetics expects:
# - get_parameter_points returning one or two np.arrays (1D or 2D)
# used for calculation aesthetics
def __init__(self):
super().__init__()
@property
def is_3D(self):
flags3D = [
self.is_3Dline,
self.is_3Dsurface
]
return any(flags3D)
@property
def is_line(self):
flagslines = [
self.is_2Dline,
self.is_3Dline
]
return any(flagslines)
### 2D lines
class Line2DBaseSeries(BaseSeries):
"""A base class for 2D lines.
- adding the label, steps and only_integers options
- making is_2Dline true
- defining get_segments and get_color_array
"""
is_2Dline = True
_dim = 2
def __init__(self):
super().__init__()
self.label = None
self.steps = False
self.only_integers = False
self.line_color = None
def get_segments(self):
np = import_module('numpy')
points = self.get_points()
if self.steps is True:
x = np.array((points[0], points[0])).T.flatten()[1:]
y = np.array((points[1], points[1])).T.flatten()[:-1]
points = (x, y)
points = np.ma.array(points).T.reshape(-1, 1, self._dim)
return np.ma.concatenate([points[:-1], points[1:]], axis=1)
def get_color_array(self):
np = import_module('numpy')
c = self.line_color
if hasattr(c, '__call__'):
f = np.vectorize(c)
nargs = arity(c)
if nargs == 1 and self.is_parametric:
x = self.get_parameter_points()
return f(centers_of_segments(x))
else:
variables = list(map(centers_of_segments, self.get_points()))
if nargs == 1:
return f(variables[0])
elif nargs == 2:
return f(*variables[:2])
else: # only if the line is 3D (otherwise raises an error)
return f(*variables)
else:
return c*np.ones(self.nb_of_points)
class List2DSeries(Line2DBaseSeries):
"""Representation for a line consisting of list of points."""
def __init__(self, list_x, list_y):
np = import_module('numpy')
super().__init__()
self.list_x = np.array(list_x)
self.list_y = np.array(list_y)
self.label = 'list'
def __str__(self):
return 'list plot'
def get_points(self):
return (self.list_x, self.list_y)
class LineOver1DRangeSeries(Line2DBaseSeries):
"""Representation for a line consisting of a SymPy expression over a range."""
def __init__(self, expr, var_start_end, **kwargs):
super().__init__()
self.expr = sympify(expr)
self.label = kwargs.get('label', None) or str(self.expr)
self.var = sympify(var_start_end[0])
self.start = float(var_start_end[1])
self.end = float(var_start_end[2])
self.nb_of_points = kwargs.get('nb_of_points', 300)
self.adaptive = kwargs.get('adaptive', True)
self.depth = kwargs.get('depth', 12)
self.line_color = kwargs.get('line_color', None)
self.xscale = kwargs.get('xscale', 'linear')
def __str__(self):
return 'cartesian line: %s for %s over %s' % (
str(self.expr), str(self.var), str((self.start, self.end)))
def get_segments(self):
"""
Adaptively gets segments for plotting.
Explanation
===========
The adaptive sampling is done by recursively checking if three
points are almost collinear. If they are not collinear, then more
points are added between those points.
References
==========
.. [1] Adaptive polygonal approximation of parametric curves,
Luiz Henrique de Figueiredo.
"""
if self.only_integers or not self.adaptive:
return super().get_segments()
else:
f = lambdify([self.var], self.expr)
list_segments = []
np = import_module('numpy')
def sample(p, q, depth):
""" Samples recursively if three points are almost collinear.
For depth < 6, points are added irrespective of whether they
satisfy the collinearity condition or not. The maximum depth
allowed is 12.
"""
# Randomly sample to avoid aliasing.
random = 0.45 + np.random.rand() * 0.1
if self.xscale == 'log':
xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) -
np.log10(p[0])))
else:
xnew = p[0] + random * (q[0] - p[0])
ynew = f(xnew)
new_point = np.array([xnew, ynew])
# Maximum depth
if depth > self.depth:
list_segments.append([p, q])
# Sample irrespective of whether the line is flat till the
# depth of 6. We are not using linspace to avoid aliasing.
elif depth < 6:
sample(p, new_point, depth + 1)
sample(new_point, q, depth + 1)
# Sample ten points if complex values are encountered
# at both ends. If there is a real value in between, then
# sample those points further.
elif p[1] is None and q[1] is None:
if self.xscale == 'log':
xarray = np.logspace(p[0], q[0], 10)
else:
xarray = np.linspace(p[0], q[0], 10)
yarray = list(map(f, xarray))
if any(y is not None for y in yarray):
for i in range(len(yarray) - 1):
if yarray[i] is not None or yarray[i + 1] is not None:
sample([xarray[i], yarray[i]],
[xarray[i + 1], yarray[i + 1]], depth + 1)
# Sample further if one of the end points in None (i.e. a
# complex value) or the three points are not almost collinear.
elif (p[1] is None or q[1] is None or new_point[1] is None
or not flat(p, new_point, q)):
sample(p, new_point, depth + 1)
sample(new_point, q, depth + 1)
else:
list_segments.append([p, q])
f_start = f(self.start)
f_end = f(self.end)
sample(np.array([self.start, f_start]),
np.array([self.end, f_end]), 0)
return list_segments
def get_points(self):
np = import_module('numpy')
if self.only_integers is True:
if self.xscale == 'log':
list_x = np.logspace(int(self.start), int(self.end),
num=int(self.end) - int(self.start) + 1)
else:
list_x = np.linspace(int(self.start), int(self.end),
num=int(self.end) - int(self.start) + 1)
else:
if self.xscale == 'log':
list_x = np.logspace(self.start, self.end, num=self.nb_of_points)
else:
list_x = np.linspace(self.start, self.end, num=self.nb_of_points)
f = vectorized_lambdify([self.var], self.expr)
list_y = f(list_x)
return (list_x, list_y)
class Parametric2DLineSeries(Line2DBaseSeries):
"""Representation for a line consisting of two parametric sympy expressions
over a range."""
is_parametric = True
def __init__(self, expr_x, expr_y, var_start_end, **kwargs):
super().__init__()
self.expr_x = sympify(expr_x)
self.expr_y = sympify(expr_y)
self.label = kwargs.get('label', None) or \
"(%s, %s)" % (str(self.expr_x), str(self.expr_y))
self.var = sympify(var_start_end[0])
self.start = float(var_start_end[1])
self.end = float(var_start_end[2])
self.nb_of_points = kwargs.get('nb_of_points', 300)
self.adaptive = kwargs.get('adaptive', True)
self.depth = kwargs.get('depth', 12)
self.line_color = kwargs.get('line_color', None)
def __str__(self):
return 'parametric cartesian line: (%s, %s) for %s over %s' % (
str(self.expr_x), str(self.expr_y), str(self.var),
str((self.start, self.end)))
def get_parameter_points(self):
np = import_module('numpy')
return np.linspace(self.start, self.end, num=self.nb_of_points)
def get_points(self):
param = self.get_parameter_points()
fx = vectorized_lambdify([self.var], self.expr_x)
fy = vectorized_lambdify([self.var], self.expr_y)
list_x = fx(param)
list_y = fy(param)
return (list_x, list_y)
def get_segments(self):
"""
Adaptively gets segments for plotting.
Explanation
===========
The adaptive sampling is done by recursively checking if three
points are almost collinear. If they are not collinear, then more
points are added between those points.
References
==========
.. [1] Adaptive polygonal approximation of parametric curves,
Luiz Henrique de Figueiredo.
"""
if not self.adaptive:
return super().get_segments()
f_x = lambdify([self.var], self.expr_x)
f_y = lambdify([self.var], self.expr_y)
list_segments = []
def sample(param_p, param_q, p, q, depth):
""" Samples recursively if three points are almost collinear.
For depth < 6, points are added irrespective of whether they
satisfy the collinearity condition or not. The maximum depth
allowed is 12.
"""
# Randomly sample to avoid aliasing.
np = import_module('numpy')
random = 0.45 + np.random.rand() * 0.1
param_new = param_p + random * (param_q - param_p)
xnew = f_x(param_new)
ynew = f_y(param_new)
new_point = np.array([xnew, ynew])
# Maximum depth
if depth > self.depth:
list_segments.append([p, q])
# Sample irrespective of whether the line is flat till the
# depth of 6. We are not using linspace to avoid aliasing.
elif depth < 6:
sample(param_p, param_new, p, new_point, depth + 1)
sample(param_new, param_q, new_point, q, depth + 1)
# Sample ten points if complex values are encountered
# at both ends. If there is a real value in between, then
# sample those points further.
elif ((p[0] is None and q[1] is None) or
(p[1] is None and q[1] is None)):
param_array = np.linspace(param_p, param_q, 10)
x_array = list(map(f_x, param_array))
y_array = list(map(f_y, param_array))
if any(x is not None and y is not None
for x, y in zip(x_array, y_array)):
for i in range(len(y_array) - 1):
if ((x_array[i] is not None and y_array[i] is not None) or
(x_array[i + 1] is not None and y_array[i + 1] is not None)):
point_a = [x_array[i], y_array[i]]
point_b = [x_array[i + 1], y_array[i + 1]]
sample(param_array[i], param_array[i], point_a,
point_b, depth + 1)
# Sample further if one of the end points in None (i.e. a complex
# value) or the three points are not almost collinear.
elif (p[0] is None or p[1] is None
or q[1] is None or q[0] is None
or not flat(p, new_point, q)):
sample(param_p, param_new, p, new_point, depth + 1)
sample(param_new, param_q, new_point, q, depth + 1)
else:
list_segments.append([p, q])
f_start_x = f_x(self.start)
f_start_y = f_y(self.start)
start = [f_start_x, f_start_y]
f_end_x = f_x(self.end)
f_end_y = f_y(self.end)
end = [f_end_x, f_end_y]
sample(self.start, self.end, start, end, 0)
return list_segments
### 3D lines
class Line3DBaseSeries(Line2DBaseSeries):
"""A base class for 3D lines.
Most of the stuff is derived from Line2DBaseSeries."""
is_2Dline = False
is_3Dline = True
_dim = 3
def __init__(self):
super().__init__()
class Parametric3DLineSeries(Line3DBaseSeries):
"""Representation for a 3D line consisting of two parametric sympy
expressions and a range."""
def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs):
super().__init__()
self.expr_x = sympify(expr_x)
self.expr_y = sympify(expr_y)
self.expr_z = sympify(expr_z)
self.label = kwargs.get('label', None) or \
"(%s, %s)" % (str(self.expr_x), str(self.expr_y))
self.var = sympify(var_start_end[0])
self.start = float(var_start_end[1])
self.end = float(var_start_end[2])
self.nb_of_points = kwargs.get('nb_of_points', 300)
self.line_color = kwargs.get('line_color', None)
def __str__(self):
return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % (
str(self.expr_x), str(self.expr_y), str(self.expr_z),
str(self.var), str((self.start, self.end)))
def get_parameter_points(self):
np = import_module('numpy')
return np.linspace(self.start, self.end, num=self.nb_of_points)
def get_points(self):
np = import_module('numpy')
param = self.get_parameter_points()
fx = vectorized_lambdify([self.var], self.expr_x)
fy = vectorized_lambdify([self.var], self.expr_y)
fz = vectorized_lambdify([self.var], self.expr_z)
list_x = fx(param)
list_y = fy(param)
list_z = fz(param)
list_x = np.array(list_x, dtype=np.float64)
list_y = np.array(list_y, dtype=np.float64)
list_z = np.array(list_z, dtype=np.float64)
list_x = np.ma.masked_invalid(list_x)
list_y = np.ma.masked_invalid(list_y)
list_z = np.ma.masked_invalid(list_z)
self._xlim = (np.amin(list_x), np.amax(list_x))
self._ylim = (np.amin(list_y), np.amax(list_y))
self._zlim = (np.amin(list_z), np.amax(list_z))
return list_x, list_y, list_z
### Surfaces
class SurfaceBaseSeries(BaseSeries):
"""A base class for 3D surfaces."""
is_3Dsurface = True
def __init__(self):
super().__init__()
self.surface_color = None
def get_color_array(self):
np = import_module('numpy')
c = self.surface_color
if isinstance(c, Callable):
f = np.vectorize(c)
nargs = arity(c)
if self.is_parametric:
variables = list(map(centers_of_faces, self.get_parameter_meshes()))
if nargs == 1:
return f(variables[0])
elif nargs == 2:
return f(*variables)
variables = list(map(centers_of_faces, self.get_meshes()))
if nargs == 1:
return f(variables[0])
elif nargs == 2:
return f(*variables[:2])
else:
return f(*variables)
else:
return c*np.ones(self.nb_of_points)
class SurfaceOver2DRangeSeries(SurfaceBaseSeries):
"""Representation for a 3D surface consisting of a sympy expression and 2D
range."""
def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs):
super().__init__()
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
self.start_x = float(var_start_end_x[1])
self.end_x = float(var_start_end_x[2])
self.var_y = sympify(var_start_end_y[0])
self.start_y = float(var_start_end_y[1])
self.end_y = float(var_start_end_y[2])
self.nb_of_points_x = kwargs.get('nb_of_points_x', 50)
self.nb_of_points_y = kwargs.get('nb_of_points_y', 50)
self.surface_color = kwargs.get('surface_color', None)
self._xlim = (self.start_x, self.end_x)
self._ylim = (self.start_y, self.end_y)
def __str__(self):
return ('cartesian surface: %s for'
' %s over %s and %s over %s') % (
str(self.expr),
str(self.var_x),
str((self.start_x, self.end_x)),
str(self.var_y),
str((self.start_y, self.end_y)))
def get_meshes(self):
np = import_module('numpy')
mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
num=self.nb_of_points_x),
np.linspace(self.start_y, self.end_y,
num=self.nb_of_points_y))
f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
mesh_z = f(mesh_x, mesh_y)
mesh_z = np.array(mesh_z, dtype=np.float64)
mesh_z = np.ma.masked_invalid(mesh_z)
self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
return mesh_x, mesh_y, mesh_z
class ParametricSurfaceSeries(SurfaceBaseSeries):
"""Representation for a 3D surface consisting of three parametric sympy
expressions and a range."""
is_parametric = True
def __init__(
self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
**kwargs):
super().__init__()
self.expr_x = sympify(expr_x)
self.expr_y = sympify(expr_y)
self.expr_z = sympify(expr_z)
self.var_u = sympify(var_start_end_u[0])
self.start_u = float(var_start_end_u[1])
self.end_u = float(var_start_end_u[2])
self.var_v = sympify(var_start_end_v[0])
self.start_v = float(var_start_end_v[1])
self.end_v = float(var_start_end_v[2])
self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
self.surface_color = kwargs.get('surface_color', None)
def __str__(self):
return ('parametric cartesian surface: (%s, %s, %s) for'
' %s over %s and %s over %s') % (
str(self.expr_x),
str(self.expr_y),
str(self.expr_z),
str(self.var_u),
str((self.start_u, self.end_u)),
str(self.var_v),
str((self.start_v, self.end_v)))
def get_parameter_meshes(self):
np = import_module('numpy')
return np.meshgrid(np.linspace(self.start_u, self.end_u,
num=self.nb_of_points_u),
np.linspace(self.start_v, self.end_v,
num=self.nb_of_points_v))
def get_meshes(self):
np = import_module('numpy')
mesh_u, mesh_v = self.get_parameter_meshes()
fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x)
fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y)
fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z)
mesh_x = fx(mesh_u, mesh_v)
mesh_y = fy(mesh_u, mesh_v)
mesh_z = fz(mesh_u, mesh_v)
mesh_x = np.array(mesh_x, dtype=np.float64)
mesh_y = np.array(mesh_y, dtype=np.float64)
mesh_z = np.array(mesh_z, dtype=np.float64)
mesh_x = np.ma.masked_invalid(mesh_x)
mesh_y = np.ma.masked_invalid(mesh_y)
mesh_z = np.ma.masked_invalid(mesh_z)
self._xlim = (np.amin(mesh_x), np.amax(mesh_x))
self._ylim = (np.amin(mesh_y), np.amax(mesh_y))
self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
return mesh_x, mesh_y, mesh_z
### Contours
class ContourSeries(BaseSeries):
"""Representation for a contour plot."""
# The code is mostly repetition of SurfaceOver2DRange.
# Presently used in contour_plot function
is_contour = True
def __init__(self, expr, var_start_end_x, var_start_end_y):
super().__init__()
self.nb_of_points_x = 50
self.nb_of_points_y = 50
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
self.start_x = float(var_start_end_x[1])
self.end_x = float(var_start_end_x[2])
self.var_y = sympify(var_start_end_y[0])
self.start_y = float(var_start_end_y[1])
self.end_y = float(var_start_end_y[2])
self.get_points = self.get_meshes
self._xlim = (self.start_x, self.end_x)
self._ylim = (self.start_y, self.end_y)
def __str__(self):
return ('contour: %s for '
'%s over %s and %s over %s') % (
str(self.expr),
str(self.var_x),
str((self.start_x, self.end_x)),
str(self.var_y),
str((self.start_y, self.end_y)))
def get_meshes(self):
np = import_module('numpy')
mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
num=self.nb_of_points_x),
np.linspace(self.start_y, self.end_y,
num=self.nb_of_points_y))
f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
return (mesh_x, mesh_y, f(mesh_x, mesh_y))
##############################################################################
# Backends
##############################################################################
class BaseBackend:
"""Base class for all backends. A backend represents the plotting library,
which implements the necessary functionalities in order to use SymPy
plotting functions.
How the plotting module works:
1. Whenever a plotting function is called, the provided expressions are
processed and a list of instances of the `BaseSeries` class is created,
containing the necessary information to plot the expressions (eg the
expression, ranges, series name, ...). Eventually, these objects will
generate the numerical data to be plotted.
2. A Plot object is instantiated, which stores the list of series and the
main attributes of the plot (eg axis labels, title, ...).
3. When the "show" command is executed, a new backend is instantiated,
which loops through each series object to generate and plot the
numerical data. The backend is also going to set the axis labels, title,
..., according to the values stored in the Plot instance.
The backend should check if it supports the data series that it's given
(eg TextBackend supports only LineOver1DRange).
It's the backend responsibility to know how to use the class of data series
that it's given. Note that the current implementation of the `*Series`
classes is "matplotlib-centric": the numerical data returned by the
`get_points` and `get_meshes` methods is meant to be used directly by
Matplotlib. Therefore, the new backend will have to pre-process the
numerical data to make it compatible with the chosen plotting library.
Keep in mind that future SymPy versions may improve the `*Series` classes in
order to return numerical data "non-matplotlib-centric", hence if you code
a new backend you have the responsibility to check if its working on each
SymPy release.
Please, explore the `MatplotlibBackend` source code to understand how a
backend should be coded.
Methods
=======
In order to be used by SymPy plotting functions, a backend must implement
the following methods:
* `show(self)`: used to loop over the data series, generate the numerical
data, plot it and set the axis labels, title, ...
* save(self, path): used to save the current plot to the specified file
path.
* close(self): used to close the current plot backend (note: some plotting
library doesn't support this functionality. In that case, just raise a
warning).
See also
========
MatplotlibBackend
"""
def __init__(self, parent):
super().__init__()
self.parent = parent
def show(self):
raise NotImplementedError
def save(self, path):
raise NotImplementedError
def close(self):
raise NotImplementedError
# Don't have to check for the success of importing matplotlib in each case;
# we will only be using this backend if we can successfully import matploblib
class MatplotlibBackend(BaseBackend):
""" This class implements the functionalities to use Matplotlib with SymPy
plotting functions.
"""
def __init__(self, parent):
super().__init__(parent)
self.matplotlib = import_module('matplotlib',
import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
min_module_version='1.1.0', catch=(RuntimeError,))
self.plt = self.matplotlib.pyplot
self.cm = self.matplotlib.cm
self.LineCollection = self.matplotlib.collections.LineCollection
aspect = getattr(self.parent, 'aspect_ratio', 'auto')
if aspect != 'auto':
aspect = float(aspect[1]) / aspect[0]
if isinstance(self.parent, Plot):
nrows, ncolumns = 1, 1
series_list = [self.parent._series]
elif isinstance(self.parent, PlotGrid):
nrows, ncolumns = self.parent.nrows, self.parent.ncolumns
series_list = self.parent._series
self.ax = []
self.fig = self.plt.figure(figsize=parent.size)
for i, series in enumerate(series_list):
are_3D = [s.is_3D for s in series]
if any(are_3D) and not all(are_3D):
raise ValueError('The matplotlib backend can not mix 2D and 3D.')
elif all(are_3D):
# mpl_toolkits.mplot3d is necessary for
# projection='3d'
mpl_toolkits = import_module('mpl_toolkits', # noqa
import_kwargs={'fromlist': ['mplot3d']})
self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect))
elif not any(are_3D):
self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect))
self.ax[i].spines['left'].set_position('zero')
self.ax[i].spines['right'].set_color('none')
self.ax[i].spines['bottom'].set_position('zero')
self.ax[i].spines['top'].set_color('none')
self.ax[i].xaxis.set_ticks_position('bottom')
self.ax[i].yaxis.set_ticks_position('left')
def _process_series(self, series, ax, parent):
np = import_module('numpy')
mpl_toolkits = import_module(
'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']})
# XXX Workaround for matplotlib issue
# https://github.com/matplotlib/matplotlib/issues/17130
xlims, ylims, zlims = [], [], []
for s in series:
# Create the collections
if s.is_2Dline:
collection = self.LineCollection(s.get_segments())
ax.add_collection(collection)
elif s.is_contour:
ax.contour(*s.get_meshes())
elif s.is_3Dline:
# TODO too complicated, I blame matplotlib
art3d = mpl_toolkits.mplot3d.art3d
collection = art3d.Line3DCollection(s.get_segments())
ax.add_collection(collection)
x, y, z = s.get_points()
xlims.append(s._xlim)
ylims.append(s._ylim)
zlims.append(s._zlim)
elif s.is_3Dsurface:
x, y, z = s.get_meshes()
collection = ax.plot_surface(x, y, z,
cmap=getattr(self.cm, 'viridis', self.cm.jet),
rstride=1, cstride=1, linewidth=0.1)
xlims.append(s._xlim)
ylims.append(s._ylim)
zlims.append(s._zlim)
elif s.is_implicit:
points = s.get_raster()
if len(points) == 2:
# interval math plotting
x, y = _matplotlib_list(points[0])
ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
else:
# use contourf or contour depending on whether it is
# an inequality or equality.
# XXX: ``contour`` plots multiple lines. Should be fixed.
ListedColormap = self.matplotlib.colors.ListedColormap
colormap = ListedColormap(["white", s.line_color])
xarray, yarray, zarray, plot_type = points
if plot_type == 'contour':
ax.contour(xarray, yarray, zarray, cmap=colormap)
else:
ax.contourf(xarray, yarray, zarray, cmap=colormap)
else:
raise NotImplementedError(
'{} is not supported in the sympy plotting module '
'with matplotlib backend. Please report this issue.'
.format(ax))
# Customise the collections with the corresponding per-series
# options.
if hasattr(s, 'label'):
collection.set_label(s.label)
if s.is_line and s.line_color:
if isinstance(s.line_color, (float, int)) or isinstance(s.line_color, Callable):
color_array = s.get_color_array()
collection.set_array(color_array)
else:
collection.set_color(s.line_color)
if s.is_3Dsurface and s.surface_color:
if self.matplotlib.__version__ < "1.2.0": # TODO in the distant future remove this check
warnings.warn('The version of matplotlib is too old to use surface coloring.')
elif isinstance(s.surface_color, (float, int)) or isinstance(s.surface_color, Callable):
color_array = s.get_color_array()
color_array = color_array.reshape(color_array.size)
collection.set_array(color_array)
else:
collection.set_color(s.surface_color)
Axes3D = mpl_toolkits.mplot3d.Axes3D
if not isinstance(ax, Axes3D):
ax.autoscale_view(
scalex=ax.get_autoscalex_on(),
scaley=ax.get_autoscaley_on())
else:
# XXX Workaround for matplotlib issue
# https://github.com/matplotlib/matplotlib/issues/17130
if xlims:
xlims = np.array(xlims)
xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1]))
ax.set_xlim(xlim)
else:
ax.set_xlim([0, 1])
if ylims:
ylims = np.array(ylims)
ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1]))
ax.set_ylim(ylim)
else:
ax.set_ylim([0, 1])
if zlims:
zlims = np.array(zlims)
zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1]))
ax.set_zlim(zlim)
else:
ax.set_zlim([0, 1])
# Set global options.
# TODO The 3D stuff
# XXX The order of those is important.
if parent.xscale and not isinstance(ax, Axes3D):
ax.set_xscale(parent.xscale)
if parent.yscale and not isinstance(ax, Axes3D):
ax.set_yscale(parent.yscale)
if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check
ax.set_autoscale_on(parent.autoscale)
if parent.axis_center:
val = parent.axis_center
if isinstance(ax, Axes3D):
pass
elif val == 'center':
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
elif val == 'auto':
xl, xh = ax.get_xlim()
yl, yh = ax.get_ylim()
pos_left = ('data', 0) if xl*xh <= 0 else 'center'
pos_bottom = ('data', 0) if yl*yh <= 0 else 'center'
ax.spines['left'].set_position(pos_left)
ax.spines['bottom'].set_position(pos_bottom)
else:
ax.spines['left'].set_position(('data', val[0]))
ax.spines['bottom'].set_position(('data', val[1]))
if not parent.axis:
ax.set_axis_off()
if parent.legend:
if ax.legend():
ax.legend_.set_visible(parent.legend)
if parent.margin:
ax.set_xmargin(parent.margin)
ax.set_ymargin(parent.margin)
if parent.title:
ax.set_title(parent.title)
if parent.xlabel:
ax.set_xlabel(parent.xlabel, position=(1, 0))
if parent.ylabel:
ax.set_ylabel(parent.ylabel, position=(0, 1))
if parent.annotations:
for a in parent.annotations:
ax.annotate(**a)
if parent.markers:
for marker in parent.markers:
# make a copy of the marker dictionary
# so that it doesn't get altered
m = marker.copy()
args = m.pop('args')
ax.plot(*args, **m)
if parent.rectangles:
for r in parent.rectangles:
rect = self.matplotlib.patches.Rectangle(**r)
ax.add_patch(rect)
if parent.fill:
ax.fill_between(**parent.fill)
# xlim and ylim shoulld always be set at last so that plot limits
# doesn't get altered during the process.
if parent.xlim:
ax.set_xlim(parent.xlim)
if parent.ylim:
ax.set_ylim(parent.ylim)
def process_series(self):
"""
Iterates over every ``Plot`` object and further calls
_process_series()
"""
parent = self.parent
if isinstance(parent, Plot):
series_list = [parent._series]
else:
series_list = parent._series
for i, (series, ax) in enumerate(zip(series_list, self.ax)):
if isinstance(self.parent, PlotGrid):
parent = self.parent.args[i]
self._process_series(series, ax, parent)
def show(self):
self.process_series()
#TODO after fixing https://github.com/ipython/ipython/issues/1255
# you can uncomment the next line and remove the pyplot.show() call
#self.fig.show()
if _show:
self.fig.tight_layout()
self.plt.show()
else:
self.close()
def save(self, path):
self.process_series()
self.fig.savefig(path)
def close(self):
self.plt.close(self.fig)
class TextBackend(BaseBackend):
def __init__(self, parent):
super().__init__(parent)
def show(self):
if not _show:
return
if len(self.parent._series) != 1:
raise ValueError(
'The TextBackend supports only one graph per Plot.')
elif not isinstance(self.parent._series[0], LineOver1DRangeSeries):
raise ValueError(
'The TextBackend supports only expressions over a 1D range')
else:
ser = self.parent._series[0]
textplot(ser.expr, ser.start, ser.end)
def close(self):
pass
class DefaultBackend(BaseBackend):
def __new__(cls, parent):
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
return MatplotlibBackend(parent)
else:
return TextBackend(parent)
plot_backends = {
'matplotlib': MatplotlibBackend,
'text': TextBackend,
'default': DefaultBackend
}
##############################################################################
# Finding the centers of line segments or mesh faces
##############################################################################
def centers_of_segments(array):
np = import_module('numpy')
return np.mean(np.vstack((array[:-1], array[1:])), 0)
def centers_of_faces(array):
np = import_module('numpy')
return np.mean(np.dstack((array[:-1, :-1],
array[1:, :-1],
array[:-1, 1:],
array[:-1, :-1],
)), 2)
def flat(x, y, z, eps=1e-3):
"""Checks whether three points are almost collinear"""
np = import_module('numpy')
# Workaround plotting piecewise (#8577):
# workaround for `lambdify` in `.experimental_lambdify` fails
# to return numerical values in some cases. Lower-level fix
# in `lambdify` is possible.
vector_a = (x - y).astype(np.float)
vector_b = (z - y).astype(np.float)
dot_product = np.dot(vector_a, vector_b)
vector_a_norm = np.linalg.norm(vector_a)
vector_b_norm = np.linalg.norm(vector_b)
cos_theta = dot_product / (vector_a_norm * vector_b_norm)
return abs(cos_theta + 1) < eps
def _matplotlib_list(interval_list):
"""
Returns lists for matplotlib ``fill`` command from a list of bounding
rectangular intervals
"""
xlist = []
ylist = []
if len(interval_list):
for intervals in interval_list:
intervalx = intervals[0]
intervaly = intervals[1]
xlist.extend([intervalx.start, intervalx.start,
intervalx.end, intervalx.end, None])
ylist.extend([intervaly.start, intervaly.end,
intervaly.end, intervaly.start, None])
else:
#XXX Ugly hack. Matplotlib does not accept empty lists for ``fill``
xlist.extend([None, None, None, None])
ylist.extend([None, None, None, None])
return xlist, ylist
####New API for plotting module ####
# TODO: Add color arrays for plots.
# TODO: Add more plotting options for 3d plots.
# TODO: Adaptive sampling for 3D plots.
def plot(*args, show=True, **kwargs):
"""Plots a function of a single variable as a curve.
Parameters
==========
args :
The first argument is the expression representing the function
of single variable to be plotted.
The last argument is a 3-tuple denoting the range of the free
variable. e.g. ``(x, 0, 5)``
Typical usage examples are in the followings:
- Plotting a single expression with a single range.
``plot(expr, range, **kwargs)``
- Plotting a single expression with the default range (-10, 10).
``plot(expr, **kwargs)``
- Plotting multiple expressions with a single range.
``plot(expr1, expr2, ..., range, **kwargs)``
- Plotting multiple expressions with multiple ranges.
``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
It is best practice to specify range explicitly because default
range may change in the future if a more advanced default range
detection algorithm is implemented.
show : bool, optional
The default value is set to ``True``. Set show to ``False`` and
the function will not display the plot. The returned instance of
the ``Plot`` class can then be used to save or display the plot
by calling the ``save()`` and ``show()`` methods respectively.
line_color : float, optional
Specifies the color for the plot.
See ``Plot`` to see how to set color for the plots.
If there are multiple plots, then the same series series are
applied to all the plots. If you want to set these options
separately, you can index the ``Plot`` object returned and set
it.
title : str, optional
Title of the plot. It is set to the latex representation of
the expression, if the plot has only one expression.
label : str, optional
The label of the expression in the plot. It will be used when
called with ``legend``. Default is the name of the expression.
e.g. ``sin(x)``
xlabel : str, optional
Label for the x-axis.
ylabel : str, optional
Label for the y-axis.
xscale : 'linear' or 'log', optional
Sets the scaling of the x-axis.
yscale : 'linear' or 'log', optional
Sets the scaling of the y-axis.
axis_center : (float, float), optional
Tuple of two floats denoting the coordinates of the center or
{'center', 'auto'}
xlim : (float, float), optional
Denotes the x-axis limits, ``(min, max)```.
ylim : (float, float), optional
Denotes the y-axis limits, ``(min, max)```.
annotations : list, optional
A list of dictionaries specifying the type of annotation
required. The keys in the dictionary should be equivalent
to the arguments of the matplotlib's annotate() function.
markers : list, optional
A list of dictionaries specifying the type the markers required.
The keys in the dictionary should be equivalent to the arguments
of the matplotlib's plot() function along with the marker
related keyworded arguments.
rectangles : list, optional
A list of dictionaries specifying the dimensions of the
rectangles to be plotted. The keys in the dictionary should be
equivalent to the arguments of the matplotlib's
patches.Rectangle class.
fill : dict, optional
A dictionary specifying the type of color filling required in
the plot. The keys in the dictionary should be equivalent to the
arguments of the matplotlib's fill_between() function.
adaptive : bool, optional
The default value is set to ``True``. Set adaptive to ``False``
and specify ``nb_of_points`` if uniform sampling is required.
The plotting uses an adaptive algorithm which samples
recursively to accurately plot. The adaptive algorithm uses a
random point near the midpoint of two points that has to be
further sampled. Hence the same plots can appear slightly
different.
depth : int, optional
Recursion depth of the adaptive algorithm. A depth of value
``n`` samples a maximum of `2^{n}` points.
If the ``adaptive`` flag is set to ``False``, this will be
ignored.
nb_of_points : int, optional
Used when the ``adaptive`` is set to ``False``. The function
is uniformly sampled at ``nb_of_points`` number of points.
If the ``adaptive`` flag is set to ``True``, this will be
ignored.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot
>>> x = symbols('x')
Single Plot
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x**2, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x**2 for x over (-5.0, 5.0)
Multiple plots with single range.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x, x**2, x**3, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x for x over (-5.0, 5.0)
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
Multiple plots with different ranges.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
No adaptive sampling.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x**2, adaptive=False, nb_of_points=400)
Plot object containing:
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
See Also
========
Plot, LineOver1DRangeSeries
"""
args = list(map(sympify, args))
free = set()
for a in args:
if isinstance(a, Expr):
free |= a.free_symbols
if len(free) > 1:
raise ValueError(
'The same variable should be used in all '
'univariate expressions being plotted.')
x = free.pop() if free else Symbol('x')
kwargs.setdefault('xlabel', x.name)
kwargs.setdefault('ylabel', 'f(%s)' % x.name)
series = []
plot_expr = check_arguments(args, 1, 1)
series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
plots = Plot(*series, **kwargs)
if show:
plots.show()
return plots
def plot_parametric(*args, show=True, **kwargs):
"""
Plots a 2D parametric curve.
Parameters
==========
args
Common specifications are:
- Plotting a single parametric curve with a range
``plot_parametric((expr_x, expr_y), range)``
- Plotting multiple parametric curves with the same range
``plot_parametric((expr_x, expr_y), ..., range)``
- Plotting multiple parametric curves with different ranges
``plot_parametric((expr_x, expr_y, range), ...)``
``expr_x`` is the expression representing $x$ component of the
parametric function.
``expr_y`` is the expression representing $y$ component of the
parametric function.
``range`` is a 3-tuple denoting the parameter symbol, start and
stop. For example, ``(u, 0, 5)``.
If the range is not specified, then a default range of (-10, 10)
is used.
However, if the arguments are specified as
``(expr_x, expr_y, range), ...``, you must specify the ranges
for each expressions manually.
Default range may change in the future if a more advanced
algorithm is implemented.
adaptive : bool, optional
Specifies whether to use the adaptive sampling or not.
The default value is set to ``True``. Set adaptive to ``False``
and specify ``nb_of_points`` if uniform sampling is required.
depth : int, optional
The recursion depth of the adaptive algorithm. A depth of
value $n$ samples a maximum of $2^n$ points.
nb_of_points : int, optional
Used when the ``adaptive`` flag is set to ``False``.
Specifies the number of the points used for the uniform
sampling.
line_color : function
A function which returns a float.
Specifies the color of the plot.
See :class:`Plot` for more details.
label : str, optional
The label of the expression in the plot. It will be used when
called with ``legend``. Default is the name of the expression.
e.g. ``sin(x)``
xlabel : str, optional
Label for the x-axis.
ylabel : str, optional
Label for the y-axis.
xscale : 'linear' or 'log', optional
Sets the scaling of the x-axis.
yscale : 'linear' or 'log', optional
Sets the scaling of the y-axis.
axis_center : (float, float), optional
Tuple of two floats denoting the coordinates of the center or
{'center', 'auto'}
xlim : (float, float), optional
Denotes the x-axis limits, ``(min, max)```.
ylim : (float, float), optional
Denotes the y-axis limits, ``(min, max)```.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot_parametric
>>> u = symbols('u')
A parametric plot with a single expression:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
A parametric plot with multiple expressions with the same range:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
[1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
A parametric plot with multiple expressions with different ranges
for each curve:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
... (cos(u), u, (u, -5, 5)))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
[1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
Notes
=====
The plotting uses an adaptive algorithm which samples recursively to
accurately plot the curve. The adaptive algorithm uses a random point
near the midpoint of two points that has to be further sampled.
Hence, repeating the same plot command can give slightly different
results because of the random sampling.
If there are multiple plots, then the same optional arguments are
applied to all the plots drawn in the same canvas. If you want to
set these options separately, you can index the returned ``Plot``
object and set it.
For example, when you specify ``line_color`` once, it would be
applied simultaneously to both series.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import pi
>>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
>>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
>>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
If you want to specify the line color for the specific series, you
should index each item and apply the property manually.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p[0].line_color = 'red'
>>> p.show()
See Also
========
Plot, Parametric2DLineSeries
"""
args = list(map(sympify, args))
series = []
plot_expr = check_arguments(args, 2, 1)
series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr]
plots = Plot(*series, **kwargs)
if show:
plots.show()
return plots
def plot3d_parametric_line(*args, show=True, **kwargs):
"""
Plots a 3D parametric line plot.
Usage
=====
Single plot:
``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots.
``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
``expr_x`` : Expression representing the function along x.
``expr_y`` : Expression representing the function along y.
``expr_z`` : Expression representing the function along z.
``range``: ``(u, 0, 5)``, A 3-tuple denoting the range of the parameter
variable.
Keyword Arguments
=================
Arguments for ``Parametric3DLineSeries`` class.
``nb_of_points``: The range is uniformly sampled at ``nb_of_points``
number of points.
Aesthetics:
``line_color``: function which returns a float. Specifies the color for the
plot. See ``sympy.plotting.Plot`` for more details.
``label``: str
The label to the plot. It will be used when called with ``legend=True``
to denote the function with the given label in the plot.
If there are multiple plots, then the same series arguments are applied to
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class.
``title`` : str. Title of the plot.
``size`` : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot3d_parametric_line
>>> u = symbols('u')
Single plot.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
Multiple plots.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
... (sin(u), u**2, u, (u, -5, 5)))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
[1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
See Also
========
Plot, Parametric3DLineSeries
"""
args = list(map(sympify, args))
series = []
plot_expr = check_arguments(args, 3, 1)
series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr]
plots = Plot(*series, **kwargs)
if show:
plots.show()
return plots
def plot3d(*args, show=True, **kwargs):
"""
Plots a 3D surface plot.
Usage
=====
Single plot
``plot3d(expr, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plot with the same range.
``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
``expr`` : Expression representing the function along x.
``range_x``: (x, 0, 5), A 3-tuple denoting the range of the x
variable.
``range_y``: (y, 0, 5), A 3-tuple denoting the range of the y
variable.
Keyword Arguments
=================
Arguments for ``SurfaceOver2DRangeSeries`` class:
``nb_of_points_x``: int. The x range is sampled uniformly at
``nb_of_points_x`` of points.
``nb_of_points_y``: int. The y range is sampled uniformly at
``nb_of_points_y`` of points.
Aesthetics:
``surface_color``: Function which returns a float. Specifies the color for
the surface of the plot. See ``sympy.plotting.Plot`` for more details.
If there are multiple plots, then the same series arguments are applied to
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class:
``title`` : str. Title of the plot.
``size`` : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of the
overall figure. The default value is set to ``None``, meaning the size will
be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot3d
>>> x, y = symbols('x y')
Single plot
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with same range
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with different ranges.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
... (x*y, (x, -3, 3), (y, -3, 3)))
Plot object containing:
[0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
See Also
========
Plot, SurfaceOver2DRangeSeries
"""
args = list(map(sympify, args))
series = []
plot_expr = check_arguments(args, 1, 2)
series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr]
plots = Plot(*series, **kwargs)
if show:
plots.show()
return plots
def plot3d_parametric_surface(*args, show=True, **kwargs):
"""
Plots a 3D parametric surface plot.
Explanation
===========
Single plot.
``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
If the ranges is not specified, then a default range of (-10, 10) is used.
Multiple plots.
``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
``expr_x``: Expression representing the function along ``x``.
``expr_y``: Expression representing the function along ``y``.
``expr_z``: Expression representing the function along ``z``.
``range_u``: ``(u, 0, 5)``, A 3-tuple denoting the range of the ``u``
variable.
``range_v``: ``(v, 0, 5)``, A 3-tuple denoting the range of the v
variable.
Keyword Arguments
=================
Arguments for ``ParametricSurfaceSeries`` class:
``nb_of_points_u``: int. The ``u`` range is sampled uniformly at
``nb_of_points_v`` of points
``nb_of_points_y``: int. The ``v`` range is sampled uniformly at
``nb_of_points_y`` of points
Aesthetics:
``surface_color``: Function which returns a float. Specifies the color for
the surface of the plot. See ``sympy.plotting.Plot`` for more details.
If there are multiple plots, then the same series arguments are applied for
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class:
``title`` : str. Title of the plot.
``size`` : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of the
overall figure. The default value is set to ``None``, meaning the size will
be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot3d_parametric_surface
>>> u, v = symbols('u v')
Single plot.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
... (u, -5, 5), (v, -5, 5))
Plot object containing:
[0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
See Also
========
Plot, ParametricSurfaceSeries
"""
args = list(map(sympify, args))
series = []
plot_expr = check_arguments(args, 3, 2)
series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr]
plots = Plot(*series, **kwargs)
if show:
plots.show()
return plots
def plot_contour(*args, show=True, **kwargs):
"""
Draws contour plot of a function
Usage
=====
Single plot
``plot_contour(expr, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plot with the same range.
``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
``expr`` : Expression representing the function along x.
``range_x``: (x, 0, 5), A 3-tuple denoting the range of the x
variable.
``range_y``: (y, 0, 5), A 3-tuple denoting the range of the y
variable.
Keyword Arguments
=================
Arguments for ``ContourSeries`` class:
``nb_of_points_x``: int. The x range is sampled uniformly at
``nb_of_points_x`` of points.
``nb_of_points_y``: int. The y range is sampled uniformly at
``nb_of_points_y`` of points.
Aesthetics:
``surface_color``: Function which returns a float. Specifies the color for
the surface of the plot. See ``sympy.plotting.Plot`` for more details.
If there are multiple plots, then the same series arguments are applied to
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class:
``title`` : str. Title of the plot.
``size`` : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
See Also
========
Plot, ContourSeries
"""
args = list(map(sympify, args))
plot_expr = check_arguments(args, 1, 2)
series = [ContourSeries(*arg) for arg in plot_expr]
plot_contours = Plot(*series, **kwargs)
if len(plot_expr[0].free_symbols) > 2:
raise ValueError('Contour Plot cannot Plot for more than two variables.')
if show:
plot_contours.show()
return plot_contours
def check_arguments(args, expr_len, nb_of_free_symbols):
"""
Checks the arguments and converts into tuples of the
form (exprs, ranges).
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import cos, sin, symbols
>>> from sympy.plotting.plot import check_arguments
>>> x = symbols('x')
>>> check_arguments([cos(x), sin(x)], 2, 1)
[(cos(x), sin(x), (x, -10, 10))]
>>> check_arguments([x, x**2], 1, 1)
[(x, (x, -10, 10)), (x**2, (x, -10, 10))]
"""
if not args:
return []
if expr_len > 1 and isinstance(args[0], Expr):
# Multiple expressions same range.
# The arguments are tuples when the expression length is
# greater than 1.
if len(args) < expr_len:
raise ValueError("len(args) should not be less than expr_len")
for i in range(len(args)):
if isinstance(args[i], Tuple):
break
else:
i = len(args) + 1
exprs = Tuple(*args[:i])
free_symbols = list(set().union(*[e.free_symbols for e in exprs]))
if len(args) == expr_len + nb_of_free_symbols:
#Ranges given
plots = [exprs + Tuple(*args[expr_len:])]
else:
default_range = Tuple(-10, 10)
ranges = []
for symbol in free_symbols:
ranges.append(Tuple(symbol) + default_range)
for i in range(len(free_symbols) - nb_of_free_symbols):
ranges.append(Tuple(Dummy()) + default_range)
plots = [exprs + Tuple(*ranges)]
return plots
if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and
len(args[0]) == expr_len and
expr_len != 3):
# Cannot handle expressions with number of expression = 3. It is
# not possible to differentiate between expressions and ranges.
#Series of plots with same range
for i in range(len(args)):
if isinstance(args[i], Tuple) and len(args[i]) != expr_len:
break
if not isinstance(args[i], Tuple):
args[i] = Tuple(args[i])
else:
i = len(args) + 1
exprs = args[:i]
assert all(isinstance(e, Expr) for expr in exprs for e in expr)
free_symbols = list(set().union(*[e.free_symbols for expr in exprs
for e in expr]))
if len(free_symbols) > nb_of_free_symbols:
raise ValueError("The number of free_symbols in the expression "
"is greater than %d" % nb_of_free_symbols)
if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple):
ranges = Tuple(*[range_expr for range_expr in args[
i:i + nb_of_free_symbols]])
plots = [expr + ranges for expr in exprs]
return plots
else:
# Use default ranges.
default_range = Tuple(-10, 10)
ranges = []
for symbol in free_symbols:
ranges.append(Tuple(symbol) + default_range)
for i in range(nb_of_free_symbols - len(free_symbols)):
ranges.append(Tuple(Dummy()) + default_range)
ranges = Tuple(*ranges)
plots = [expr + ranges for expr in exprs]
return plots
elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols:
# Multiple plots with different ranges.
for arg in args:
for i in range(expr_len):
if not isinstance(arg[i], Expr):
raise ValueError("Expected an expression, given %s" %
str(arg[i]))
for i in range(nb_of_free_symbols):
if not len(arg[i + expr_len]) == 3:
raise ValueError("The ranges should be a tuple of "
"length 3, got %s" % str(arg[i + expr_len]))
return args
|
f163e3abcaa429eb8e040cfad4c3a132ae0dc4430c847a7ca55a0e4f3ce40b80 | """ rewrite of lambdify - This stuff is not stable at all.
It is for internal use in the new plotting module.
It may (will! see the Q'n'A in the source) be rewritten.
It's completely self contained. Especially it does not use lambdarepr.
It does not aim to replace the current lambdify. Most importantly it will never
ever support anything else than sympy expressions (no Matrices, dictionaries
and so on).
"""
import re
from sympy import Symbol, NumberSymbol, I, zoo, oo
from sympy.utilities.iterables import numbered_symbols
# We parse the expression string into a tree that identifies functions. Then
# we translate the names of the functions and we translate also some strings
# that are not names of functions (all this according to translation
# dictionaries).
# If the translation goes to another module (like numpy) the
# module is imported and 'func' is translated to 'module.func'.
# If a function can not be translated, the inner nodes of that part of the
# tree are not translated. So if we have Integral(sqrt(x)), sqrt is not
# translated to np.sqrt and the Integral does not crash.
# A namespace for all this is generated by crawling the (func, args) tree of
# the expression. The creation of this namespace involves many ugly
# workarounds.
# The namespace consists of all the names needed for the sympy expression and
# all the name of modules used for translation. Those modules are imported only
# as a name (import numpy as np) in order to keep the namespace small and
# manageable.
# Please, if there is a bug, do not try to fix it here! Rewrite this by using
# the method proposed in the last Q'n'A below. That way the new function will
# work just as well, be just as simple, but it wont need any new workarounds.
# If you insist on fixing it here, look at the workarounds in the function
# sympy_expression_namespace and in lambdify.
# Q: Why are you not using python abstract syntax tree?
# A: Because it is more complicated and not much more powerful in this case.
# Q: What if I have Symbol('sin') or g=Function('f')?
# A: You will break the algorithm. We should use srepr to defend against this?
# The problem with Symbol('sin') is that it will be printed as 'sin'. The
# parser will distinguish it from the function 'sin' because functions are
# detected thanks to the opening parenthesis, but the lambda expression won't
# understand the difference if we have also the sin function.
# The solution (complicated) is to use srepr and maybe ast.
# The problem with the g=Function('f') is that it will be printed as 'f' but in
# the global namespace we have only 'g'. But as the same printer is used in the
# constructor of the namespace there will be no problem.
# Q: What if some of the printers are not printing as expected?
# A: The algorithm wont work. You must use srepr for those cases. But even
# srepr may not print well. All problems with printers should be considered
# bugs.
# Q: What about _imp_ functions?
# A: Those are taken care for by evalf. A special case treatment will work
# faster but it's not worth the code complexity.
# Q: Will ast fix all possible problems?
# A: No. You will always have to use some printer. Even srepr may not work in
# some cases. But if the printer does not work, that should be considered a
# bug.
# Q: Is there same way to fix all possible problems?
# A: Probably by constructing our strings ourself by traversing the (func,
# args) tree and creating the namespace at the same time. That actually sounds
# good.
from sympy.external import import_module
import warnings
#TODO debugging output
class vectorized_lambdify:
""" Return a sufficiently smart, vectorized and lambdified function.
Returns only reals.
Explanation
===========
This function uses experimental_lambdify to created a lambdified
expression ready to be used with numpy. Many of the functions in sympy
are not implemented in numpy so in some cases we resort to python cmath or
even to evalf.
The following translations are tried:
only numpy complex
- on errors raised by sympy trying to work with ndarray:
only python cmath and then vectorize complex128
When using python cmath there is no need for evalf or float/complex
because python cmath calls those.
This function never tries to mix numpy directly with evalf because numpy
does not understand sympy Float. If this is needed one can use the
float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or
better one can be explicit about the dtypes that numpy works with.
Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what
types of errors to expect.
"""
def __init__(self, args, expr):
self.args = args
self.expr = expr
self.np = import_module('numpy')
self.lambda_func_1 = experimental_lambdify(
args, expr, use_np=True)
self.vector_func_1 = self.lambda_func_1
self.lambda_func_2 = experimental_lambdify(
args, expr, use_python_cmath=True)
self.vector_func_2 = self.np.vectorize(
self.lambda_func_2, otypes=[self.np.complex])
self.vector_func = self.vector_func_1
self.failure = False
def __call__(self, *args):
np = self.np
try:
temp_args = (np.array(a, dtype=np.complex) for a in args)
results = self.vector_func(*temp_args)
results = np.ma.masked_where(
np.abs(results.imag) > 1e-7 * np.abs(results),
results.real, copy=False)
return results
except ValueError:
if self.failure:
raise
self.failure = True
self.vector_func = self.vector_func_2
warnings.warn(
'The evaluation of the expression is problematic. '
'We are trying a failback method that may still work. '
'Please report this as a bug.')
return self.__call__(*args)
class lambdify:
"""Returns the lambdified function.
Explanation
===========
This function uses experimental_lambdify to create a lambdified
expression. It uses cmath to lambdify the expression. If the function
is not implemented in python cmath, python cmath calls evalf on those
functions.
"""
def __init__(self, args, expr):
self.args = args
self.expr = expr
self.lambda_func_1 = experimental_lambdify(
args, expr, use_python_cmath=True, use_evalf=True)
self.lambda_func_2 = experimental_lambdify(
args, expr, use_python_math=True, use_evalf=True)
self.lambda_func_3 = experimental_lambdify(
args, expr, use_evalf=True, complex_wrap_evalf=True)
self.lambda_func = self.lambda_func_1
self.failure = False
def __call__(self, args):
try:
#The result can be sympy.Float. Hence wrap it with complex type.
result = complex(self.lambda_func(args))
if abs(result.imag) > 1e-7 * abs(result):
return None
return result.real
except (ZeroDivisionError, TypeError) as e:
if isinstance(e, ZeroDivisionError):
return None
if self.failure:
raise e
if self.lambda_func == self.lambda_func_1:
self.lambda_func = self.lambda_func_2
return self.__call__(args)
self.failure = True
self.lambda_func = self.lambda_func_3
warnings.warn(
'The evaluation of the expression is problematic. '
'We are trying a failback method that may still work. '
'Please report this as a bug.')
return self.__call__(args)
def experimental_lambdify(*args, **kwargs):
l = Lambdifier(*args, **kwargs)
return l
class Lambdifier:
def __init__(self, args, expr, print_lambda=False, use_evalf=False,
float_wrap_evalf=False, complex_wrap_evalf=False,
use_np=False, use_python_math=False, use_python_cmath=False,
use_interval=False):
self.print_lambda = print_lambda
self.use_evalf = use_evalf
self.float_wrap_evalf = float_wrap_evalf
self.complex_wrap_evalf = complex_wrap_evalf
self.use_np = use_np
self.use_python_math = use_python_math
self.use_python_cmath = use_python_cmath
self.use_interval = use_interval
# Constructing the argument string
# - check
if not all([isinstance(a, Symbol) for a in args]):
raise ValueError('The arguments must be Symbols.')
# - use numbered symbols
syms = numbered_symbols(exclude=expr.free_symbols)
newargs = [next(syms) for _ in args]
expr = expr.xreplace(dict(zip(args, newargs)))
argstr = ', '.join([str(a) for a in newargs])
del syms, newargs, args
# Constructing the translation dictionaries and making the translation
self.dict_str = self.get_dict_str()
self.dict_fun = self.get_dict_fun()
exprstr = str(expr)
newexpr = self.tree2str_translate(self.str2tree(exprstr))
# Constructing the namespaces
namespace = {}
namespace.update(self.sympy_atoms_namespace(expr))
namespace.update(self.sympy_expression_namespace(expr))
# XXX Workaround
# Ugly workaround because Pow(a,Half) prints as sqrt(a)
# and sympy_expression_namespace can not catch it.
from sympy import sqrt
namespace.update({'sqrt': sqrt})
namespace.update({'Eq': lambda x, y: x == y})
namespace.update({'Ne': lambda x, y: x != y})
# End workaround.
if use_python_math:
namespace.update({'math': __import__('math')})
if use_python_cmath:
namespace.update({'cmath': __import__('cmath')})
if use_np:
try:
namespace.update({'np': __import__('numpy')})
except ImportError:
raise ImportError(
'experimental_lambdify failed to import numpy.')
if use_interval:
namespace.update({'imath': __import__(
'sympy.plotting.intervalmath', fromlist=['intervalmath'])})
namespace.update({'math': __import__('math')})
# Construct the lambda
if self.print_lambda:
print(newexpr)
eval_str = 'lambda %s : ( %s )' % (argstr, newexpr)
self.eval_str = eval_str
exec("from __future__ import division; MYNEWLAMBDA = %s" % eval_str, namespace)
self.lambda_func = namespace['MYNEWLAMBDA']
def __call__(self, *args, **kwargs):
return self.lambda_func(*args, **kwargs)
##############################################################################
# Dicts for translating from sympy to other modules
##############################################################################
###
# builtins
###
# Functions with different names in builtins
builtin_functions_different = {
'Min': 'min',
'Max': 'max',
'Abs': 'abs',
}
# Strings that should be translated
builtin_not_functions = {
'I': '1j',
# 'oo': '1e400',
}
###
# numpy
###
# Functions that are the same in numpy
numpy_functions_same = [
'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'exp', 'log',
'sqrt', 'floor', 'conjugate',
]
# Functions with different names in numpy
numpy_functions_different = {
"acos": "arccos",
"acosh": "arccosh",
"arg": "angle",
"asin": "arcsin",
"asinh": "arcsinh",
"atan": "arctan",
"atan2": "arctan2",
"atanh": "arctanh",
"ceiling": "ceil",
"im": "imag",
"ln": "log",
"Max": "amax",
"Min": "amin",
"re": "real",
"Abs": "abs",
}
# Strings that should be translated
numpy_not_functions = {
'pi': 'np.pi',
'oo': 'np.inf',
'E': 'np.e',
}
###
# python math
###
# Functions that are the same in math
math_functions_same = [
'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
'exp', 'log', 'erf', 'sqrt', 'floor', 'factorial', 'gamma',
]
# Functions with different names in math
math_functions_different = {
'ceiling': 'ceil',
'ln': 'log',
'loggamma': 'lgamma'
}
# Strings that should be translated
math_not_functions = {
'pi': 'math.pi',
'E': 'math.e',
}
###
# python cmath
###
# Functions that are the same in cmath
cmath_functions_same = [
'sin', 'cos', 'tan', 'asin', 'acos', 'atan',
'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
'exp', 'log', 'sqrt',
]
# Functions with different names in cmath
cmath_functions_different = {
'ln': 'log',
'arg': 'phase',
}
# Strings that should be translated
cmath_not_functions = {
'pi': 'cmath.pi',
'E': 'cmath.e',
}
###
# intervalmath
###
interval_not_functions = {
'pi': 'math.pi',
'E': 'math.e'
}
interval_functions_same = [
'sin', 'cos', 'exp', 'tan', 'atan', 'log',
'sqrt', 'cosh', 'sinh', 'tanh', 'floor',
'acos', 'asin', 'acosh', 'asinh', 'atanh',
'Abs', 'And', 'Or'
]
interval_functions_different = {
'Min': 'imin',
'Max': 'imax',
'ceiling': 'ceil',
}
###
# mpmath, etc
###
#TODO
###
# Create the final ordered tuples of dictionaries
###
# For strings
def get_dict_str(self):
dict_str = dict(self.builtin_not_functions)
if self.use_np:
dict_str.update(self.numpy_not_functions)
if self.use_python_math:
dict_str.update(self.math_not_functions)
if self.use_python_cmath:
dict_str.update(self.cmath_not_functions)
if self.use_interval:
dict_str.update(self.interval_not_functions)
return dict_str
# For functions
def get_dict_fun(self):
dict_fun = dict(self.builtin_functions_different)
if self.use_np:
for s in self.numpy_functions_same:
dict_fun[s] = 'np.' + s
for k, v in self.numpy_functions_different.items():
dict_fun[k] = 'np.' + v
if self.use_python_math:
for s in self.math_functions_same:
dict_fun[s] = 'math.' + s
for k, v in self.math_functions_different.items():
dict_fun[k] = 'math.' + v
if self.use_python_cmath:
for s in self.cmath_functions_same:
dict_fun[s] = 'cmath.' + s
for k, v in self.cmath_functions_different.items():
dict_fun[k] = 'cmath.' + v
if self.use_interval:
for s in self.interval_functions_same:
dict_fun[s] = 'imath.' + s
for k, v in self.interval_functions_different.items():
dict_fun[k] = 'imath.' + v
return dict_fun
##############################################################################
# The translator functions, tree parsers, etc.
##############################################################################
def str2tree(self, exprstr):
"""Converts an expression string to a tree.
Explanation
===========
Functions are represented by ('func_name(', tree_of_arguments).
Other expressions are (head_string, mid_tree, tail_str).
Expressions that do not contain functions are directly returned.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy import Integral, sin
>>> from sympy.plotting.experimental_lambdify import Lambdifier
>>> str2tree = Lambdifier([x], x).str2tree
>>> str2tree(str(Integral(x, (x, 1, y))))
('', ('Integral(', 'x, (x, 1, y)'), ')')
>>> str2tree(str(x+y))
'x + y'
>>> str2tree(str(x+y*sin(z)+1))
('x + y*', ('sin(', 'z'), ') + 1')
>>> str2tree('sin(y*(y + 1.1) + (sin(y)))')
('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')')
"""
#matches the first 'function_name('
first_par = re.search(r'(\w+\()', exprstr)
if first_par is None:
return exprstr
else:
start = first_par.start()
end = first_par.end()
head = exprstr[:start]
func = exprstr[start:end]
tail = exprstr[end:]
count = 0
for i, c in enumerate(tail):
if c == '(':
count += 1
elif c == ')':
count -= 1
if count == -1:
break
func_tail = self.str2tree(tail[:i])
tail = self.str2tree(tail[i:])
return (head, (func, func_tail), tail)
@classmethod
def tree2str(cls, tree):
"""Converts a tree to string without translations.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy import sin
>>> from sympy.plotting.experimental_lambdify import Lambdifier
>>> str2tree = Lambdifier([x], x).str2tree
>>> tree2str = Lambdifier([x], x).tree2str
>>> tree2str(str2tree(str(x+y*sin(z)+1)))
'x + y*sin(z) + 1'
"""
if isinstance(tree, str):
return tree
else:
return ''.join(map(cls.tree2str, tree))
def tree2str_translate(self, tree):
"""Converts a tree to string with translations.
Explanation
===========
Function names are translated by translate_func.
Other strings are translated by translate_str.
"""
if isinstance(tree, str):
return self.translate_str(tree)
elif isinstance(tree, tuple) and len(tree) == 2:
return self.translate_func(tree[0][:-1], tree[1])
else:
return ''.join([self.tree2str_translate(t) for t in tree])
def translate_str(self, estr):
"""Translate substrings of estr using in order the dictionaries in
dict_tuple_str."""
for pattern, repl in self.dict_str.items():
estr = re.sub(pattern, repl, estr)
return estr
def translate_func(self, func_name, argtree):
"""Translate function names and the tree of arguments.
Explanation
===========
If the function name is not in the dictionaries of dict_tuple_fun then the
function is surrounded by a float((...).evalf()).
The use of float is necessary as np.<function>(sympy.Float(..)) raises an
error."""
if func_name in self.dict_fun:
new_name = self.dict_fun[func_name]
argstr = self.tree2str_translate(argtree)
return new_name + '(' + argstr
elif func_name in ['Eq', 'Ne']:
op = {'Eq': '==', 'Ne': '!='}
return "(lambda x, y: x {} y)({}".format(op[func_name], self.tree2str_translate(argtree))
else:
template = '(%s(%s)).evalf(' if self.use_evalf else '%s(%s'
if self.float_wrap_evalf:
template = 'float(%s)' % template
elif self.complex_wrap_evalf:
template = 'complex(%s)' % template
# Wrapping should only happen on the outermost expression, which
# is the only thing we know will be a number.
float_wrap_evalf = self.float_wrap_evalf
complex_wrap_evalf = self.complex_wrap_evalf
self.float_wrap_evalf = False
self.complex_wrap_evalf = False
ret = template % (func_name, self.tree2str_translate(argtree))
self.float_wrap_evalf = float_wrap_evalf
self.complex_wrap_evalf = complex_wrap_evalf
return ret
##############################################################################
# The namespace constructors
##############################################################################
@classmethod
def sympy_expression_namespace(cls, expr):
"""Traverses the (func, args) tree of an expression and creates a sympy
namespace. All other modules are imported only as a module name. That way
the namespace is not polluted and rests quite small. It probably causes much
more variable lookups and so it takes more time, but there are no tests on
that for the moment."""
if expr is None:
return {}
else:
funcname = str(expr.func)
# XXX Workaround
# Here we add an ugly workaround because str(func(x))
# is not always the same as str(func). Eg
# >>> str(Integral(x))
# "Integral(x)"
# >>> str(Integral)
# "<class 'sympy.integrals.integrals.Integral'>"
# >>> str(sqrt(x))
# "sqrt(x)"
# >>> str(sqrt)
# "<function sqrt at 0x3d92de8>"
# >>> str(sin(x))
# "sin(x)"
# >>> str(sin)
# "sin"
# Either one of those can be used but not all at the same time.
# The code considers the sin example as the right one.
regexlist = [
r'<class \'sympy[\w.]*?.([\w]*)\'>$',
# the example Integral
r'<function ([\w]*) at 0x[\w]*>$', # the example sqrt
]
for r in regexlist:
m = re.match(r, funcname)
if m is not None:
funcname = m.groups()[0]
# End of the workaround
# XXX debug: print funcname
args_dict = {}
for a in expr.args:
if (isinstance(a, Symbol) or
isinstance(a, NumberSymbol) or
a in [I, zoo, oo]):
continue
else:
args_dict.update(cls.sympy_expression_namespace(a))
args_dict.update({funcname: expr.func})
return args_dict
@staticmethod
def sympy_atoms_namespace(expr):
"""For no real reason this function is separated from
sympy_expression_namespace. It can be moved to it."""
atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)
d = {}
for a in atoms:
# XXX debug: print 'atom:' + str(a)
d[str(a)] = a
return d
|
6009fe7258db97893b58861b8cd675b9edc650ce4ce70c2322ddb6e9e003fd01 | from sympy import (S, Symbol, Interval, binomial, nan, exp, Or,
symbols, Eq, cos, And, Tuple, integrate, oo, sin, Sum, Basic, Indexed,
DiracDelta, Lambda, log, pi, FallingFactorial, Rational, Matrix)
from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance,
density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble,
random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric,
DiscreteUniform, Poisson, characteristic_function, moment_generating_function,
BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance)
from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin,
RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol)
from sympy.testing.pytest import raises, skip, XFAIL, ignore_warnings
from sympy.external import import_module
from sympy.core.numbers import comp
from sympy.stats.frv_types import BernoulliDistribution
from sympy.core.symbol import Dummy
from sympy.functions.elementary.piecewise import Piecewise
def test_where():
X, Y = Die('X'), Die('Y')
Z = Normal('Z', 0, 1)
assert where(Z**2 <= 1).set == Interval(-1, 1)
assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol)
assert where(And(X > Y, Y > 4)).as_boolean() == And(
Eq(X.symbol, 6), Eq(Y.symbol, 5))
assert len(where(X < 3).set) == 2
assert 1 in where(X < 3).set
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1)
XX = given(X, And(X**2 <= 1, X >= 0))
assert XX.pspace.domain.set == Interval(0, 1)
assert XX.pspace.domain.as_boolean() == \
And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo)
with raises(TypeError):
XX = given(X, X + 3)
def test_random_symbols():
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
assert set(random_symbols(2*X + 1)) == {X}
assert set(random_symbols(2*X + Y)) == {X, Y}
assert set(random_symbols(2*X + Y.symbol)) == {X}
assert set(random_symbols(2)) == set()
def test_characteristic_function():
# Imports I from sympy
from sympy import I
X = Normal('X',0,1)
Y = DiscreteUniform('Y', [1,2,7])
Z = Poisson('Z', 2)
t = symbols('_t')
P = Lambda(t, exp(-t**2/2))
Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3)
R = Lambda(t, exp(2 * exp(t*I) - 2))
assert characteristic_function(X).dummy_eq(P)
assert characteristic_function(Y).dummy_eq(Q)
assert characteristic_function(Z).dummy_eq(R)
def test_moment_generating_function():
X = Normal('X',0,1)
Y = DiscreteUniform('Y', [1,2,7])
Z = Poisson('Z', 2)
t = symbols('_t')
P = Lambda(t, exp(t**2/2))
Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3))
R = Lambda(t, exp(2 * exp(t) - 2))
assert moment_generating_function(X).dummy_eq(P)
assert moment_generating_function(Y).dummy_eq(Q)
assert moment_generating_function(Z).dummy_eq(R)
def test_sample_iter():
X = Normal('X',0,1)
Y = DiscreteUniform('Y', [1, 2, 7])
Z = Poisson('Z', 2)
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
expr = X**2 + 3
iterator = sample_iter(expr)
expr2 = Y**2 + 5*Y + 4
iterator2 = sample_iter(expr2)
expr3 = Z**3 + 4
iterator3 = sample_iter(expr3)
def is_iterator(obj):
if (
hasattr(obj, '__iter__') and
(hasattr(obj, 'next') or
hasattr(obj, '__next__')) and
callable(obj.__iter__) and
obj.__iter__() is obj
):
return True
else:
return False
assert is_iterator(iterator)
assert is_iterator(iterator2)
assert is_iterator(iterator3)
def test_pspace():
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
x = Symbol('x')
raises(ValueError, lambda: pspace(5 + 3))
raises(ValueError, lambda: pspace(x < 1))
assert pspace(X) == X.pspace
assert pspace(2*X + 1) == X.pspace
assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace)
def test_rs_swap():
X = Normal('x', 0, 1)
Y = Exponential('y', 1)
XX = Normal('x', 0, 2)
YY = Normal('y', 0, 3)
expr = 2*X + Y
assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY
def test_RandomSymbol():
X = Normal('x', 0, 1)
Y = Normal('x', 0, 2)
assert X.symbol == Y.symbol
assert X != Y
assert X.name == X.symbol.name
X = Normal('lambda', 0, 1) # make sure we can use protected terms
X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms
def test_RandomSymbol_diff():
X = Normal('x', 0, 1)
assert (2*X).diff(X)
def test_random_symbol_no_pspace():
x = RandomSymbol(Symbol('x'))
assert x.pspace == PSpace()
def test_overlap():
X = Normal('x', 0, 1)
Y = Normal('x', 0, 2)
raises(ValueError, lambda: P(X > Y))
def test_IndependentProductPSpace():
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 1)
px = X.pspace
py = Y.pspace
assert pspace(X + Y) == IndependentProductPSpace(px, py)
assert pspace(X + Y) == IndependentProductPSpace(py, px)
def test_E():
assert E(5) == 5
def test_H():
X = Normal('X', 0, 1)
D = Die('D', sides = 4)
G = Geometric('G', 0.5)
assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2
assert H(D, D > 2) == log(2)
assert comp(H(G).evalf().round(2), 1.39)
def test_Sample():
X = Die('X', 6)
Y = Normal('Y', 0, 1)
z = Symbol('z', integer=True)
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in [1, 2, 3, 4, 5, 6]
assert isinstance(next(sample(X + Y)), float)
assert P(X + Y > 0, Y < 0, numsamples=10).is_number
assert E(X + Y, numsamples=10).is_number
assert E(X**2 + Y, numsamples=10).is_number
assert E((X + Y)**2, numsamples=10).is_number
assert variance(X + Y, numsamples=10).is_number
raises(TypeError, lambda: P(Y > z, numsamples=5))
assert P(sin(Y) <= 1, numsamples=10) == 1
assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1
assert all(i in range(1, 7) for i in density(X, numsamples=10))
assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10))
@XFAIL
def test_samplingE():
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
Y = Normal('Y', 0, 1)
z = Symbol('z', integer=True)
assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number
def test_given():
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 1)
A = given(X, True)
B = given(X, Y > 2)
assert X == A == B
def test_factorial_moment():
X = Poisson('X', 2)
Y = Binomial('Y', 2, S.Half)
Z = Hypergeometric('Z', 4, 2, 2)
assert factorial_moment(X, 2) == 4
assert factorial_moment(Y, 2) == S.Half
assert factorial_moment(Z, 2) == Rational(1, 3)
x, y, z, l = symbols('x y z l')
Y = Binomial('Y', 2, y)
Z = Hypergeometric('Z', 10, 2, 3)
assert factorial_moment(Y, l) == y**2*FallingFactorial(
2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\
FallingFactorial(0, l)
assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\
15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15
def test_dependence():
X, Y = Die('X'), Die('Y')
assert independent(X, 2*Y)
assert not dependent(X, 2*Y)
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
assert independent(X, Y)
assert dependent(X, 2*X)
# Create a dependency
XX, YY = given(Tuple(X, Y), Eq(X + Y, 3))
assert dependent(XX, YY)
def test_dependent_finite():
X, Y = Die('X'), Die('Y')
# Dependence testing requires symbolic conditions which currently break
# finite random variables
assert dependent(X, Y + X)
XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency
assert dependent(XX, YY)
def test_normality():
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
x = Symbol('x', real=True, finite=True)
z = Symbol('z', real=True, finite=True)
dens = density(X - Y, Eq(X + Y, z))
assert integrate(dens(x), (x, -oo, oo)) == 1
def test_Density():
X = Die('X', 6)
d = Density(X)
assert d.doit() == density(X)
def test_NamedArgsMixin():
class Foo(Basic, NamedArgsMixin):
_argnames = 'foo', 'bar'
a = Foo(1, 2)
assert a.foo == 1
assert a.bar == 2
raises(AttributeError, lambda: a.baz)
class Bar(Basic, NamedArgsMixin):
pass
raises(AttributeError, lambda: Bar(1, 2).foo)
def test_density_constant():
assert density(3)(2) == 0
assert density(3)(3) == DiracDelta(0)
def test_real():
x = Normal('x', 0, 1)
assert x.is_real
def test_issue_10052():
X = Exponential('X', 3)
assert P(X < oo) == 1
assert P(X > oo) == 0
assert P(X < 2, X > oo) == 0
assert P(X < oo, X > oo) == 0
assert P(X < oo, X > 2) == 1
assert P(X < 3, X == 2) == 0
raises(ValueError, lambda: P(1))
raises(ValueError, lambda: P(X < 1, 2))
def test_issue_11934():
density = {0: .5, 1: .5}
X = FiniteRV('X', density)
assert E(X) == 0.5
assert P( X>= 2) == 0
def test_issue_8129():
X = Exponential('X', 4)
assert P(X >= X) == 1
assert P(X > X) == 0
assert P(X > X+1) == 0
def test_issue_12237():
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 1)
U = P(X > 0, X)
V = P(Y < 0, X)
W = P(X + Y > 0, X)
assert W == P(X + Y > 0, X)
assert U == BernoulliDistribution(S.Half, S.Zero, S.One)
assert V == S.Half
def test_is_random():
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 1)
a, b = symbols('a, b')
G = GaussianUnitaryEnsemble('U', 2)
B = BernoulliProcess('B', 0.9)
assert not is_random(a)
assert not is_random(a + b)
assert not is_random(a * b)
assert not is_random(Matrix([a**2, b**2]))
assert is_random(X)
assert is_random(X**2 + Y)
assert is_random(Y + b**2)
assert is_random(Y > 5)
assert is_random(B[3] < 1)
assert is_random(G)
assert is_random(X * Y * B[1])
assert is_random(Matrix([[X, B[2]], [G, Y]]))
assert is_random(Eq(X, 4))
def test_issue_12283():
x = symbols('x')
X = RandomSymbol(x)
Y = RandomSymbol('Y')
Z = RandomMatrixSymbol('Z', 2, 1)
W = RandomMatrixSymbol('W', 2, 1)
RI = RandomIndexedSymbol(Indexed('RI', 3))
assert pspace(Z) == PSpace()
assert pspace(RI) == PSpace()
assert pspace(X) == PSpace()
assert E(X) == Expectation(X)
assert P(Y > 3) == Probability(Y > 3)
assert variance(X) == Variance(X)
assert variance(RI) == Variance(RI)
assert covariance(X, Y) == Covariance(X, Y)
assert covariance(W, Z) == Covariance(W, Z)
def test_issue_6810():
X = Die('X', 6)
Y = Normal('Y', 0, 1)
assert P(Eq(X, 2)) == S(1)/6
assert P(Eq(Y, 0)) == 0
assert P(Or(X > 2, X < 3)) == 1
assert P(And(X > 3, X > 2)) == S(1)/2
def test_issue_20286():
n, p = symbols('n p')
B = Binomial('B', n, p)
k = Dummy('k', integer = True)
eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n))
assert eq.dummy_eq(H(B))
|
312bf40152d0f7810df014b889b3516f392892dacec3c97026675fe7bc6c43bc | from sympy import (FiniteSet, S, Symbol, sqrt, nan, beta, Rational, symbols,
simplify, Eq, cos, And, Tuple, Or, Dict, sympify, binomial,
cancel, exp, I, Piecewise, Sum, Dummy, harmonic, Function)
from sympy.external import import_module
from sympy.matrices import Matrix
from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial, BetaBinomial,
Hypergeometric, Rademacher, IdealSoliton, RobustSoliton, P, E, variance,
covariance, skewness, sample, density, where, FiniteRV, pspace, cdf,
correlation, moment, cmoment, smoment, characteristic_function,
moment_generating_function, quantile, kurtosis, median, coskewness)
from sympy.stats.frv_types import DieDistribution, BinomialDistribution, \
HypergeometricDistribution
from sympy.stats.rv import Density
from sympy.testing.pytest import raises, skip, ignore_warnings
def BayesTest(A, B):
assert P(A, B) == P(And(A, B)) / P(B)
assert P(A, B) == P(B, A) * P(A) / P(B)
def test_discreteuniform():
# Symbolic
a, b, c, t = symbols('a b c t')
X = DiscreteUniform('X', [a, b, c])
assert E(X) == (a + b + c)/3
assert simplify(variance(X)
- ((a**2 + b**2 + c**2)/3 - (a/3 + b/3 + c/3)**2)) == 0
assert P(Eq(X, a)) == P(Eq(X, b)) == P(Eq(X, c)) == S('1/3')
Y = DiscreteUniform('Y', range(-5, 5))
# Numeric
assert E(Y) == S('-1/2')
assert variance(Y) == S('33/4')
assert median(Y) == FiniteSet(-1, 0)
for x in range(-5, 5):
assert P(Eq(Y, x)) == S('1/10')
assert P(Y <= x) == S(x + 6)/10
assert P(Y >= x) == S(5 - x)/10
assert dict(density(Die('D', 6)).items()) == \
dict(density(DiscreteUniform('U', range(1, 7))).items())
assert characteristic_function(X)(t) == exp(I*a*t)/3 + exp(I*b*t)/3 + exp(I*c*t)/3
assert moment_generating_function(X)(t) == exp(a*t)/3 + exp(b*t)/3 + exp(c*t)/3
# issue 18611
raises(ValueError, lambda: DiscreteUniform('Z', [a, a, a, b, b, c]))
def test_dice():
# TODO: Make iid method!
X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6)
a, b, t, p = symbols('a b t p')
assert E(X) == 3 + S.Half
assert variance(X) == Rational(35, 12)
assert E(X + Y) == 7
assert E(X + X) == 7
assert E(a*X + b) == a*E(X) + b
assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2)
assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2)
assert cmoment(X, 0) == 1
assert cmoment(4*X, 3) == 64*cmoment(X, 3)
assert covariance(X, Y) is S.Zero
assert covariance(X, X + Y) == variance(X)
assert density(Eq(cos(X*S.Pi), 1))[True] == S.Half
assert correlation(X, Y) == 0
assert correlation(X, Y) == correlation(Y, X)
assert smoment(X + Y, 3) == skewness(X + Y)
assert smoment(X + Y, 4) == kurtosis(X + Y)
assert smoment(X, 0) == 1
assert P(X > 3) == S.Half
assert P(2*X > 6) == S.Half
assert P(X > Y) == Rational(5, 12)
assert P(Eq(X, Y)) == P(Eq(X, 1))
assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3)
assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3)
assert E(X + Y, Eq(X, Y)) == E(2*X)
assert moment(X, 0) == 1
assert moment(5*X, 2) == 25*moment(X, 2)
assert quantile(X)(p) == Piecewise((nan, (p > 1) | (p < 0)),\
(S.One, p <= Rational(1, 6)), (S(2), p <= Rational(1, 3)), (S(3), p <= S.Half),\
(S(4), p <= Rational(2, 3)), (S(5), p <= Rational(5, 6)), (S(6), p <= 1))
assert P(X > 3, X > 3) is S.One
assert P(X > Y, Eq(Y, 6)) is S.Zero
assert P(Eq(X + Y, 12)) == Rational(1, 36)
assert P(Eq(X + Y, 12), Eq(X, 6)) == Rational(1, 6)
assert density(X + Y) == density(Y + Z) != density(X + X)
d = density(2*X + Y**Z)
assert d[S(22)] == Rational(1, 108) and d[S(4100)] == Rational(1, 216) and S(3130) not in d
assert pspace(X).domain.as_boolean() == Or(
*[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]])
assert where(X > 3).set == FiniteSet(4, 5, 6)
assert characteristic_function(X)(t) == exp(6*I*t)/6 + exp(5*I*t)/6 + exp(4*I*t)/6 + exp(3*I*t)/6 + exp(2*I*t)/6 + exp(I*t)/6
assert moment_generating_function(X)(t) == exp(6*t)/6 + exp(5*t)/6 + exp(4*t)/6 + exp(3*t)/6 + exp(2*t)/6 + exp(t)/6
assert median(X) == FiniteSet(3, 4)
D = Die('D', 7)
assert median(D) == FiniteSet(4)
# Bayes test for die
BayesTest(X > 3, X + Y < 5)
BayesTest(Eq(X - Y, Z), Z > Y)
BayesTest(X > 3, X > 2)
# arg test for die
raises(ValueError, lambda: Die('X', -1)) # issue 8105: negative sides.
raises(ValueError, lambda: Die('X', 0))
raises(ValueError, lambda: Die('X', 1.5)) # issue 8103: non integer sides.
# symbolic test for die
n, k = symbols('n, k', positive=True)
D = Die('D', n)
dens = density(D).dict
assert dens == Density(DieDistribution(n))
assert set(dens.subs(n, 4).doit().keys()) == {1, 2, 3, 4}
assert set(dens.subs(n, 4).doit().values()) == {Rational(1, 4)}
k = Dummy('k', integer=True)
assert E(D).dummy_eq(
Sum(Piecewise((k/n, k <= n), (0, True)), (k, 1, n)))
assert variance(D).subs(n, 6).doit() == Rational(35, 12)
ki = Dummy('ki')
cumuf = cdf(D)(k)
assert cumuf.dummy_eq(
Sum(Piecewise((1/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, k)))
assert cumuf.subs({n: 6, k: 2}).doit() == Rational(1, 3)
t = Dummy('t')
cf = characteristic_function(D)(t)
assert cf.dummy_eq(
Sum(Piecewise((exp(ki*I*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n)))
assert cf.subs(n, 3).doit() == exp(3*I*t)/3 + exp(2*I*t)/3 + exp(I*t)/3
mgf = moment_generating_function(D)(t)
assert mgf.dummy_eq(
Sum(Piecewise((exp(ki*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n)))
assert mgf.subs(n, 3).doit() == exp(3*t)/3 + exp(2*t)/3 + exp(t)/3
def test_given():
X = Die('X', 6)
assert density(X, X > 5) == {S(6): S.One}
assert where(X > 2, X > 5).as_boolean() == Eq(X.symbol, 6)
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X, X > 5)) == 6
def test_domains():
X, Y = Die('x', 6), Die('y', 6)
x, y = X.symbol, Y.symbol
# Domains
d = where(X > Y)
assert d.condition == (x > y)
d = where(And(X > Y, Y > 3))
assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6),
Eq(y, 5)), And(Eq(x, 6), Eq(y, 4)))
assert len(d.elements) == 3
assert len(pspace(X + Y).domain.elements) == 36
Z = Die('x', 4)
raises(ValueError, lambda: P(X > Z)) # Two domains with same internal symbol
assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2
assert where(X > 3).set == FiniteSet(4, 5, 6)
assert X.pspace.domain.dict == FiniteSet(
*[Dict({X.symbol: i}) for i in range(1, 7)])
assert where(X > Y).dict == FiniteSet(*[Dict({X.symbol: i, Y.symbol: j})
for i in range(1, 7) for j in range(1, 7) if i > j])
def test_bernoulli():
p, a, b, t = symbols('p a b t')
X = Bernoulli('B', p, a, b)
assert E(X) == a*p + b*(-p + 1)
assert density(X)[a] == p
assert density(X)[b] == 1 - p
assert characteristic_function(X)(t) == p * exp(I * a * t) + (-p + 1) * exp(I * b * t)
assert moment_generating_function(X)(t) == p * exp(a * t) + (-p + 1) * exp(b * t)
X = Bernoulli('B', p, 1, 0)
z = Symbol("z")
assert E(X) == p
assert simplify(variance(X)) == p*(1 - p)
assert E(a*X + b) == a*E(X) + b
assert simplify(variance(a*X + b)) == simplify(a**2 * variance(X))
assert quantile(X)(z) == Piecewise((nan, (z > 1) | (z < 0)), (0, z <= 1 - p), (1, z <= 1))
Y = Bernoulli('Y', Rational(1, 2))
assert median(Y) == FiniteSet(0, 1)
Z = Bernoulli('Z', Rational(2, 3))
assert median(Z) == FiniteSet(1)
raises(ValueError, lambda: Bernoulli('B', 1.5))
raises(ValueError, lambda: Bernoulli('B', -0.5))
#issue 8248
assert X.pspace.compute_expectation(1) == 1
p = Rational(1, 5)
X = Binomial('X', 5, p)
Y = Binomial('Y', 7, 2*p)
Z = Binomial('Z', 9, 3*p)
assert coskewness(Y + Z, X + Y, X + Z).simplify() == 0
assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y).simplify() == \
sqrt(1529)*Rational(12, 16819)
assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y, X < 2).simplify() \
== -sqrt(357451121)*Rational(2812, 4646864573)
def test_cdf():
D = Die('D', 6)
o = S.One
assert cdf(
D) == sympify({1: o/6, 2: o/3, 3: o/2, 4: 2*o/3, 5: 5*o/6, 6: o})
def test_coins():
C, D = Coin('C'), Coin('D')
H, T = symbols('H, T')
assert P(Eq(C, D)) == S.Half
assert density(Tuple(C, D)) == {(H, H): Rational(1, 4), (H, T): Rational(1, 4),
(T, H): Rational(1, 4), (T, T): Rational(1, 4)}
assert dict(density(C).items()) == {H: S.Half, T: S.Half}
F = Coin('F', Rational(1, 10))
assert P(Eq(F, H)) == Rational(1, 10)
d = pspace(C).domain
assert d.as_boolean() == Or(Eq(C.symbol, H), Eq(C.symbol, T))
raises(ValueError, lambda: P(C > D)) # Can't intelligently compare H to T
def test_binomial_verify_parameters():
raises(ValueError, lambda: Binomial('b', .2, .5))
raises(ValueError, lambda: Binomial('b', 3, 1.5))
def test_binomial_numeric():
nvals = range(5)
pvals = [0, Rational(1, 4), S.Half, Rational(3, 4), 1]
for n in nvals:
for p in pvals:
X = Binomial('X', n, p)
assert E(X) == n*p
assert variance(X) == n*p*(1 - p)
if n > 0 and 0 < p < 1:
assert skewness(X) == (1 - 2*p)/sqrt(n*p*(1 - p))
assert kurtosis(X) == 3 + (1 - 6*p*(1 - p))/(n*p*(1 - p))
for k in range(n + 1):
assert P(Eq(X, k)) == binomial(n, k)*p**k*(1 - p)**(n - k)
def test_binomial_quantile():
X = Binomial('X', 50, S.Half)
assert quantile(X)(0.95) == S(31)
assert median(X) == FiniteSet(25)
X = Binomial('X', 5, S.Half)
p = Symbol("p", positive=True)
assert quantile(X)(p) == Piecewise((nan, p > S.One), (S.Zero, p <= Rational(1, 32)),\
(S.One, p <= Rational(3, 16)), (S(2), p <= S.Half), (S(3), p <= Rational(13, 16)),\
(S(4), p <= Rational(31, 32)), (S(5), p <= S.One))
assert median(X) == FiniteSet(2, 3)
def test_binomial_symbolic():
n = 2
p = symbols('p', positive=True)
X = Binomial('X', n, p)
t = Symbol('t')
assert simplify(E(X)) == n*p == simplify(moment(X, 1))
assert simplify(variance(X)) == n*p*(1 - p) == simplify(cmoment(X, 2))
assert cancel(skewness(X) - (1 - 2*p)/sqrt(n*p*(1 - p))) == 0
assert cancel((kurtosis(X)) - (3 + (1 - 6*p*(1 - p))/(n*p*(1 - p)))) == 0
assert characteristic_function(X)(t) == p ** 2 * exp(2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1) ** 2
assert moment_generating_function(X)(t) == p ** 2 * exp(2 * t) + 2 * p * (-p + 1) * exp(t) + (-p + 1) ** 2
# Test ability to change success/failure winnings
H, T = symbols('H T')
Y = Binomial('Y', n, p, succ=H, fail=T)
assert simplify(E(Y) - (n*(H*p + T*(1 - p)))) == 0
# test symbolic dimensions
n = symbols('n')
B = Binomial('B', n, p)
raises(NotImplementedError, lambda: P(B > 2))
assert density(B).dict == Density(BinomialDistribution(n, p, 1, 0))
assert set(density(B).dict.subs(n, 4).doit().keys()) == \
{S.Zero, S.One, S(2), S(3), S(4)}
assert set(density(B).dict.subs(n, 4).doit().values()) == \
{(1 - p)**4, 4*p*(1 - p)**3, 6*p**2*(1 - p)**2, 4*p**3*(1 - p), p**4}
k = Dummy('k', integer=True)
assert E(B > 2).dummy_eq(
Sum(Piecewise((k*p**k*(1 - p)**(-k + n)*binomial(n, k), (k >= 0)
& (k <= n) & (k > 2)), (0, True)), (k, 0, n)))
def test_beta_binomial():
# verify parameters
raises(ValueError, lambda: BetaBinomial('b', .2, 1, 2))
raises(ValueError, lambda: BetaBinomial('b', 2, -1, 2))
raises(ValueError, lambda: BetaBinomial('b', 2, 1, -2))
assert BetaBinomial('b', 2, 1, 1)
# test numeric values
nvals = range(1,5)
alphavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]
betavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]
for n in nvals:
for a in alphavals:
for b in betavals:
X = BetaBinomial('X', n, a, b)
assert E(X) == moment(X, 1)
assert variance(X) == cmoment(X, 2)
# test symbolic
n, a, b = symbols('a b n')
assert BetaBinomial('x', n, a, b)
n = 2 # Because we're using for loops, can't do symbolic n
a, b = symbols('a b', positive=True)
X = BetaBinomial('X', n, a, b)
t = Symbol('t')
assert E(X).expand() == moment(X, 1).expand()
assert variance(X).expand() == cmoment(X, 2).expand()
assert skewness(X) == smoment(X, 3)
assert characteristic_function(X)(t) == exp(2*I*t)*beta(a + 2, b)/beta(a, b) +\
2*exp(I*t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
assert moment_generating_function(X)(t) == exp(2*t)*beta(a + 2, b)/beta(a, b) +\
2*exp(t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
def test_hypergeometric_numeric():
for N in range(1, 5):
for m in range(0, N + 1):
for n in range(1, N + 1):
X = Hypergeometric('X', N, m, n)
N, m, n = map(sympify, (N, m, n))
assert sum(density(X).values()) == 1
assert E(X) == n * m / N
if N > 1:
assert variance(X) == n*(m/N)*(N - m)/N*(N - n)/(N - 1)
# Only test for skewness when defined
if N > 2 and 0 < m < N and n < N:
assert skewness(X) == simplify((N - 2*m)*sqrt(N - 1)*(N - 2*n)
/ (sqrt(n*m*(N - m)*(N - n))*(N - 2)))
def test_hypergeometric_symbolic():
N, m, n = symbols('N, m, n')
H = Hypergeometric('H', N, m, n)
dens = density(H).dict
expec = E(H > 2)
assert dens == Density(HypergeometricDistribution(N, m, n))
assert dens.subs(N, 5).doit() == Density(HypergeometricDistribution(5, m, n))
assert set(dens.subs({N: 3, m: 2, n: 1}).doit().keys()) == {S.Zero, S.One}
assert set(dens.subs({N: 3, m: 2, n: 1}).doit().values()) == {Rational(1, 3), Rational(2, 3)}
k = Dummy('k', integer=True)
assert expec.dummy_eq(
Sum(Piecewise((k*binomial(m, k)*binomial(N - m, -k + n)
/binomial(N, n), k > 2), (0, True)), (k, 0, n)))
def test_rademacher():
X = Rademacher('X')
t = Symbol('t')
assert E(X) == 0
assert variance(X) == 1
assert density(X)[-1] == S.Half
assert density(X)[1] == S.Half
assert characteristic_function(X)(t) == exp(I*t)/2 + exp(-I*t)/2
assert moment_generating_function(X)(t) == exp(t) / 2 + exp(-t) / 2
def test_ideal_soliton():
raises(ValueError, lambda : IdealSoliton('sol', -12))
raises(ValueError, lambda : IdealSoliton('sol', 13.2))
raises(ValueError, lambda : IdealSoliton('sol', 0))
f = Function('f')
raises(ValueError, lambda : density(IdealSoliton('sol', 10)).pmf(f))
k = Symbol('k', integer=True, positive=True)
x = Symbol('x', integer=True, positive=True)
t = Symbol('t')
sol = IdealSoliton('sol', k)
assert density(sol).low == S.One
assert density(sol).high == k
assert density(sol).dict == Density(density(sol))
assert density(sol).pmf(x) == Piecewise((1/k, Eq(x, 1)), (1/(x*(x - 1)), k >= x), (0, True))
k_vals = [5, 20, 50, 100, 1000]
for i in k_vals:
assert E(sol.subs(k, i)) == harmonic(i) == moment(sol.subs(k, i), 1)
assert variance(sol.subs(k, i)) == (i - 1) + harmonic(i) - harmonic(i)**2 == cmoment(sol.subs(k, i),2)
assert skewness(sol.subs(k, i)) == smoment(sol.subs(k, i), 3)
assert kurtosis(sol.subs(k, i)) == smoment(sol.subs(k, i), 4)
assert exp(I*t)/10 + Sum(exp(I*t*x)/(x*x - x), (x, 2, k)).subs(k, 10).doit() == characteristic_function(sol.subs(k, 10))(t)
assert exp(t)/10 + Sum(exp(t*x)/(x*x - x), (x, 2, k)).subs(k, 10).doit() == moment_generating_function(sol.subs(k, 10))(t)
def test_robust_soliton():
raises(ValueError, lambda : RobustSoliton('robSol', -12, 0.1, 0.02))
raises(ValueError, lambda : RobustSoliton('robSol', 13, 1.89, 0.1))
raises(ValueError, lambda : RobustSoliton('robSol', 15, 0.6, -2.31))
f = Function('f')
raises(ValueError, lambda : density(RobustSoliton('robSol', 15, 0.6, 0.1)).pmf(f))
k = Symbol('k', integer=True, positive=True)
delta = Symbol('delta', positive=True)
c = Symbol('c', positive=True)
robSol = RobustSoliton('robSol', k, delta, c)
assert density(robSol).low == 1
assert density(robSol).high == k
k_vals = [10, 20, 50]
delta_vals = [0.2, 0.4, 0.6]
c_vals = [0.01, 0.03, 0.05]
for x in k_vals:
for y in delta_vals:
for z in c_vals:
assert E(robSol.subs({k: x, delta: y, c: z})) == moment(robSol.subs({k: x, delta: y, c: z}), 1)
assert variance(robSol.subs({k: x, delta: y, c: z})) == cmoment(robSol.subs({k: x, delta: y, c: z}), 2)
assert skewness(robSol.subs({k: x, delta: y, c: z})) == smoment(robSol.subs({k: x, delta: y, c: z}), 3)
assert kurtosis(robSol.subs({k: x, delta: y, c: z})) == smoment(robSol.subs({k: x, delta: y, c: z}), 4)
def test_FiniteRV():
F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}, check=True)
p = Symbol("p", positive=True)
assert dict(density(F).items()) == {S.One: S.Half, S(2): Rational(1, 4), S(3): Rational(1, 4)}
assert P(F >= 2) == S.Half
assert quantile(F)(p) == Piecewise((nan, p > S.One), (S.One, p <= S.Half),\
(S(2), p <= Rational(3, 4)),(S(3), True))
assert pspace(F).domain.as_boolean() == Or(
*[Eq(F.symbol, i) for i in [1, 2, 3]])
assert F.pspace.domain.set == FiniteSet(1, 2, 3)
raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: S.Half, 3: S.Half}, check=True))
raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: Rational(-1, 2), 3: S.One}, check=True))
raises(ValueError, lambda: FiniteRV('F', {1: S.One, 2: Rational(3, 2), 3: S.Zero,\
4: Rational(-1, 2), 5: Rational(-3, 4), 6: Rational(-1, 4)}, check=True))
# purposeful invalid pmf but it should not raise since check=False
# see test_drv_types.test_ContinuousRV for explanation
X = FiniteRV('X', {1: 1, 2: 2})
assert E(X) == 5
assert P(X <= 2) + P(X > 2) != 1
def test_density_call():
from sympy.abc import p
x = Bernoulli('x', p)
d = density(x)
assert d(0) == 1 - p
assert d(S.Zero) == 1 - p
assert d(5) == 0
assert 0 in d
assert 5 not in d
assert d(S.Zero) == d[S.Zero]
def test_DieDistribution():
from sympy.abc import x
X = DieDistribution(6)
assert X.pmf(S.Half) is S.Zero
assert X.pmf(x).subs({x: 1}).doit() == Rational(1, 6)
assert X.pmf(x).subs({x: 7}).doit() == 0
assert X.pmf(x).subs({x: -1}).doit() == 0
assert X.pmf(x).subs({x: Rational(1, 3)}).doit() == 0
raises(ValueError, lambda: X.pmf(Matrix([0, 0])))
raises(ValueError, lambda: X.pmf(x**2 - 1))
def test_FinitePSpace():
X = Die('X', 6)
space = pspace(X)
assert space.density == DieDistribution(6)
def test_symbolic_conditions():
B = Bernoulli('B', Rational(1, 4))
D = Die('D', 4)
b, n = symbols('b, n')
Y = P(Eq(B, b))
Z = E(D > n)
assert Y == \
Piecewise((Rational(1, 4), Eq(b, 1)), (0, True)) + \
Piecewise((Rational(3, 4), Eq(b, 0)), (0, True))
assert Z == \
Piecewise((Rational(1, 4), n < 1), (0, True)) + Piecewise((S.Half, n < 2), (0, True)) + \
Piecewise((Rational(3, 4), n < 3), (0, True)) + Piecewise((S.One, n < 4), (0, True))
def test_sample_numpy():
distribs_numpy = [
Binomial("B", 5, 0.4),
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Die("D"), library='numpy')))
raises(NotImplementedError,
lambda: Die("D").pspace.sample(library='tensorflow'))
def test_sample_scipy():
distribs_scipy = [
FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}),
DiscreteUniform("Y", list(range(5))),
Die("D"),
Bernoulli("Be", 0.3),
Binomial("Bi", 5, 0.4),
BetaBinomial("Bb", 2, 1, 1),
Hypergeometric("H", 1, 1, 1),
Rademacher("R")
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
h_sample = list(sample(Hypergeometric("H", 1, 1, 1), size=size, numsamples=numsamples))
assert len(h_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size))
samps2 = next(sample(X, size=(2, 2)))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Bernoulli('B', 0.2),
Binomial('N', 5, 0.4)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Die("D"), library='pymc3')))
|
3eea14cdef80ef347a4a1df53e04994502fd9e20de5f853b27c7b2523e1af73a | from sympy import (S, symbols, FiniteSet, Eq, Matrix, MatrixSymbol, Float, And,
ImmutableMatrix, Ne, Lt, Le, Gt, Ge, exp, Not, Rational, Lambda, erf,
Piecewise, factorial, Interval, oo, Contains, sqrt, pi, ceiling,
gamma, lowergamma, Sum, Range, Tuple, ImmutableDenseMatrix, Symbol)
from sympy.stats import (DiscreteMarkovChain, P, TransitionMatrixOf, E,
StochasticStateSpaceOf, variance, ContinuousMarkovChain,
BernoulliProcess, PoissonProcess, WienerProcess,
GammaProcess, sample_stochastic_process)
from sympy.stats.joint_rv import JointDistribution
from sympy.stats.joint_rv_types import JointDistributionHandmade
from sympy.stats.rv import RandomIndexedSymbol
from sympy.stats.symbolic_probability import Probability, Expectation
from sympy.testing.pytest import raises, skip, ignore_warnings
from sympy.external import import_module
from sympy.stats.frv_types import BernoulliDistribution
from sympy.stats.drv_types import PoissonDistribution
from sympy.stats.crv_types import NormalDistribution, GammaDistribution
from sympy.core.symbol import Str
def test_DiscreteMarkovChain():
# pass only the name
X = DiscreteMarkovChain("X")
assert isinstance(X.state_space, Range)
assert X.index_set == S.Naturals0
assert isinstance(X.transition_probabilities, MatrixSymbol)
t = symbols('t', positive=True, integer=True)
assert isinstance(X[t], RandomIndexedSymbol)
assert E(X[0]) == Expectation(X[0])
raises(TypeError, lambda: DiscreteMarkovChain(1))
raises(NotImplementedError, lambda: X(t))
raises(NotImplementedError, lambda: X.communication_classes())
raises(NotImplementedError, lambda: X.canonical_form())
raises(NotImplementedError, lambda: X.decompose())
nz = Symbol('n', integer=True)
TZ = MatrixSymbol('M', nz, nz)
SZ = Range(nz)
YZ = DiscreteMarkovChain('Y', SZ, TZ)
assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1]
raises(ValueError, lambda: sample_stochastic_process(t))
raises(ValueError, lambda: next(sample_stochastic_process(X)))
# pass name and state_space
# any hashable object should be a valid state
# states should be valid as a tuple/set/list/Tuple/Range
sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True)
state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain],
Tuple(1, exp(sym), Str('World'), sympify=False), Range(-1, 5, 2),
[rainy, cloudy, sunny]]
chains = [DiscreteMarkovChain("Y", state_space) for state_space in state_spaces]
for i, Y in enumerate(chains):
assert isinstance(Y.transition_probabilities, MatrixSymbol)
assert Y.state_space == state_spaces[i] or Y.state_space == FiniteSet(*state_spaces[i])
assert Y.number_of_states == 3
with ignore_warnings(UserWarning): # TODO: Restore tests once warnings are removed
assert P(Eq(Y[2], 1), Eq(Y[0], 2), evaluate=False) == Probability(Eq(Y[2], 1), Eq(Y[0], 2))
assert E(Y[0]) == Expectation(Y[0])
raises(ValueError, lambda: next(sample_stochastic_process(Y)))
raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1))))
Y = DiscreteMarkovChain("Y", Range(1, t, 2))
assert Y.number_of_states == ceiling((t-1)/2)
# pass name and transition_probabilities
chains = [DiscreteMarkovChain("Y", trans_probs=Matrix([[]])),
DiscreteMarkovChain("Y", trans_probs=Matrix([[0, 1], [1, 0]])),
DiscreteMarkovChain("Y", trans_probs=Matrix([[pi, 1-pi], [sym, 1-sym]]))]
for Z in chains:
assert Z.number_of_states == Z.transition_probabilities.shape[0]
assert isinstance(Z.transition_probabilities, ImmutableDenseMatrix)
# pass name, state_space and transition_probabilities
T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
TS = MatrixSymbol('T', 3, 3)
Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS)
assert Y.joint_distribution(1, Y[2], 3) == JointDistribution(Y[1], Y[2], Y[3])
raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol))
assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2)
assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) -
(TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2])).simplify() == 0
assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1))
assert P(Eq(YS[3], 3), Eq(YS[1], 1)) == TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2]
TO = Matrix([[0.25, 0.75, 0],[0, 0.25, 0.75],[0.75, 0, 0.25]])
assert P(Eq(Y[3], 2), Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(0.375, 3)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert E(Y[3], evaluate=False) == Expectation(Y[3])
assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3)
TSO = MatrixSymbol('T', 4, 4)
raises(ValueError, lambda: str(P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO))))
raises(TypeError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M')))
raises(ValueError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4)))
raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6)))
raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1)))
# extended tests for probability queries
TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]])
assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
Eq(Probability(Eq(Y[0], 0)), Rational(1, 4)) & TransitionMatrixOf(Y, TO1)) == Rational(1, 16)
assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \
Probability(Eq(Y[0], 0))/4
assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) &
StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4)
assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) &
StochasticStateSpaceOf(X, [None, 'None', 1]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4)
assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) &
StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) is S.Zero
assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) &
StochasticStateSpaceOf(X, [None, 'None', 1]) & TransitionMatrixOf(X, TO1)) is S.Zero
assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Y[1], 1)) == 0.1*Probability(Eq(Y[0], 0))
# testing properties of Markov chain
TO2 = Matrix([[S.One, 0, 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]])
TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)], [0, Rational(1, 4), Rational(3, 4)]])
Y2 = DiscreteMarkovChain('Y', trans_probs=TO2)
Y3 = DiscreteMarkovChain('Y', trans_probs=TO3)
assert Y3.fundamental_matrix() == ImmutableMatrix([[176, 81, -132], [36, 141, -52], [-44, -39, 208]])/125
assert Y2.is_absorbing_chain() == True
assert Y3.is_absorbing_chain() == False
assert Y2.canonical_form() == ([0, 1, 2], TO2)
assert Y3.canonical_form() == ([0, 1, 2], TO3)
assert Y2.decompose() == ([0, 1, 2], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3])
assert Y3.decompose() == ([0, 1, 2], TO3, Matrix(0, 3, []), Matrix(0, 0, []))
TO4 = Matrix([[Rational(1, 5), Rational(2, 5), Rational(2, 5)], [Rational(1, 10), S.Half, Rational(2, 5)], [Rational(3, 5), Rational(3, 10), Rational(1, 10)]])
Y4 = DiscreteMarkovChain('Y', trans_probs=TO4)
w = ImmutableMatrix([[Rational(11, 39), Rational(16, 39), Rational(4, 13)]])
assert Y4.limiting_distribution == w
assert Y4.is_regular() == True
assert Y4.is_ergodic() == True
TS1 = MatrixSymbol('T', 3, 3)
Y5 = DiscreteMarkovChain('Y', trans_probs=TS1)
assert Y5.limiting_distribution(w, TO4).doit() == True
assert Y5.stationary_distribution(condition_set=True).subs(TS1, TO4).contains(w).doit() == S.true
TO6 = Matrix([[S.One, 0, 0, 0, 0],[S.Half, 0, S.Half, 0, 0],[0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half], [0, 0, 0, 0, 1]])
Y6 = DiscreteMarkovChain('Y', trans_probs=TO6)
assert Y6.fundamental_matrix() == ImmutableMatrix([[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One], [S.Half, S.One, Rational(3, 2)]])
assert Y6.absorbing_probabilities() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]])
TO7 = Matrix([[Rational(1, 2), Rational(1, 4), Rational(1, 4)], [Rational(1, 2), 0, Rational(1, 2)], [Rational(1, 4), Rational(1, 4), Rational(1, 2)]])
Y7 = DiscreteMarkovChain('Y', trans_probs=TO7)
assert Y7.is_absorbing_chain() == False
assert Y7.fundamental_matrix() == ImmutableDenseMatrix([[Rational(86, 75), Rational(1, 25), Rational(-14, 75)],
[Rational(2, 25), Rational(21, 25), Rational(2, 25)],
[Rational(-14, 75), Rational(1, 25), Rational(86, 75)]])
# test for zero-sized matrix functionality
X = DiscreteMarkovChain('X', trans_probs=Matrix([[]]))
assert X.number_of_states == 0
assert X.stationary_distribution() == Matrix([[]])
assert X.communication_classes() == []
assert X.canonical_form() == ([], Matrix([[]]))
assert X.decompose() == ([], Matrix([[]]), Matrix([[]]), Matrix([[]]))
assert X.is_regular() == False
assert X.is_ergodic() == False
# test communication_class
# see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing
# tutorial 2.pdf
TO7 = Matrix([[0, 5, 5, 0, 0],
[0, 0, 0, 10, 0],
[5, 0, 5, 0, 0],
[0, 10, 0, 0, 0],
[0, 3, 0, 3, 4]])/10
Y7 = DiscreteMarkovChain('Y', trans_probs=TO7)
tuples = Y7.communication_classes()
classes, recurrence, periods = list(zip(*tuples))
assert classes == ([1, 3], [0, 2], [4])
assert recurrence == (True, False, False)
assert periods == (2, 1, 1)
TO8 = Matrix([[0, 0, 0, 10, 0, 0],
[5, 0, 5, 0, 0, 0],
[0, 4, 0, 0, 0, 6],
[10, 0, 0, 0, 0, 0],
[0, 10, 0, 0, 0, 0],
[0, 0, 0, 5, 5, 0]])/10
Y8 = DiscreteMarkovChain('Y', trans_probs=TO8)
tuples = Y8.communication_classes()
classes, recurrence, periods = list(zip(*tuples))
assert classes == ([0, 3], [1, 2, 5, 4])
assert recurrence == (True, False)
assert periods == (2, 2)
TO9 = Matrix([[2, 0, 0, 3, 0, 0, 3, 2, 0, 0],
[0, 10, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 0, 0, 0, 0, 0, 3, 3],
[0, 0, 0, 3, 0, 0, 6, 1, 0, 0],
[0, 0, 0, 0, 5, 5, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 10, 0, 0, 0, 0],
[4, 0, 0, 5, 0, 0, 1, 0, 0, 0],
[2, 0, 0, 4, 0, 0, 2, 2, 0, 0],
[3, 0, 1, 0, 0, 0, 0, 0, 4, 2],
[0, 0, 4, 0, 0, 0, 0, 0, 3, 3]])/10
Y9 = DiscreteMarkovChain('Y', trans_probs=TO9)
tuples = Y9.communication_classes()
classes, recurrence, periods = list(zip(*tuples))
assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4])
assert recurrence == (True, True, False, True, False)
assert periods == (1, 1, 1, 1, 1)
# test canonical form
# see https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
# example 11.13
T = Matrix([[1, 0, 0, 0, 0],
[S(1) / 2, 0, S(1) / 2, 0, 0],
[0, S(1) / 2, 0, S(1) / 2, 0],
[0, 0, S(1) / 2, 0, S(1) / 2],
[0, 0, 0, 0, S(1)]])
DW = DiscreteMarkovChain('DW', [0, 1, 2, 3, 4], T)
states, A, B, C = DW.decompose()
assert states == [0, 4, 1, 2, 3]
assert A == Matrix([[1, 0], [0, 1]])
assert B == Matrix([[S(1)/2, 0], [0, 0], [0, S(1)/2]])
assert C == Matrix([[0, S(1)/2, 0], [S(1)/2, 0, S(1)/2], [0, S(1)/2, 0]])
states, new_matrix = DW.canonical_form()
assert states == [0, 4, 1, 2, 3]
assert new_matrix == Matrix([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[S(1)/2, 0, 0, S(1)/2, 0],
[0, 0, S(1)/2, 0, S(1)/2],
[0, S(1)/2, 0, S(1)/2, 0]])
# test regular and ergodic
# https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
T = Matrix([[0, 4, 0, 0, 0],
[1, 0, 3, 0, 0],
[0, 2, 0, 2, 0],
[0, 0, 3, 0, 1],
[0, 0, 0, 4, 0]])/4
X = DiscreteMarkovChain('X', trans_probs=T)
assert not X.is_regular()
assert X.is_ergodic()
T = Matrix([[0, 1], [1, 0]])
X = DiscreteMarkovChain('X', trans_probs=T)
assert not X.is_regular()
assert X.is_ergodic()
# http://www.math.wisc.edu/~valko/courses/331/MC2.pdf
T = Matrix([[2, 1, 1],
[2, 0, 2],
[1, 1, 2]])/4
X = DiscreteMarkovChain('X', trans_probs=T)
assert X.is_regular()
assert X.is_ergodic()
# https://docs.ufpr.br/~lucambio/CE222/1S2014/Kemeny-Snell1976.pdf
T = Matrix([[1, 1], [1, 1]])/2
X = DiscreteMarkovChain('X', trans_probs=T)
assert X.is_regular()
assert X.is_ergodic()
# test is_absorbing_chain
T = Matrix([[0, 1, 0],
[1, 0, 0],
[0, 0, 1]])
X = DiscreteMarkovChain('X', trans_probs=T)
assert not X.is_absorbing_chain()
# https://en.wikipedia.org/wiki/Absorbing_Markov_chain
T = Matrix([[1, 1, 0, 0],
[0, 1, 1, 0],
[1, 0, 0, 1],
[0, 0, 0, 2]])/2
X = DiscreteMarkovChain('X', trans_probs=T)
assert X.is_absorbing_chain()
T = Matrix([[2, 0, 0, 0, 0],
[1, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 0, 2]])/2
X = DiscreteMarkovChain('X', trans_probs=T)
assert X.is_absorbing_chain()
# test custom state space
Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2)
tuples = Y10.communication_classes()
classes, recurrence, periods = list(zip(*tuples))
assert classes == ([1], [2, 3])
assert recurrence == (True, False)
assert periods == (1, 1)
assert Y10.canonical_form() == ([1, 2, 3], TO2)
assert Y10.decompose() == ([1, 2, 3], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3])
# testing miscellaneous queries
T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)],
[Rational(1, 3), 0, Rational(2, 3)],
[S.Half, S.Half, 0]])
X = DiscreteMarkovChain('X', [0, 1, 2], T)
assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0),
Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12)
assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3)
assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero
assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3)
assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3)
assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9)
raises(ValueError, lambda: E(X[1], Eq(X[2], 1)))
raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T))
# testing miscellaneous queries with different state space
X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T)
assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0),
Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12)
assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3)
assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero
assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3)
a = X.state_space.args[0]
c = X.state_space.args[2]
assert (E(X[1] ** 2, Eq(X[0], 1)) - (a**2/3 + 2*c**2/3)).simplify() == 0
assert (variance(X[1], Eq(X[0], 1)) - (2*(-a/3 + c/3)**2/3 + (2*a/3 - 2*c/3)**2/3)).simplify() == 0
raises(ValueError, lambda: E(X[1], Eq(X[2], 1)))
#testing queries with multiple RandomIndexedSymbols
T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]])
Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
assert P(Eq(Y[7], Y[5]), Eq(Y[2], 0)).round(5) == Float(0.44428, 5)
assert P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) == Float(0.36, 2)
assert P(Le(Y[5], Y[10]), Eq(Y[4], 2)).round(6) == Float(0.583120, 6)
assert Float(P(Eq(Y[10], Y[5]), Eq(Y[4], 1)), 14) == Float(1 - P(Ne(Y[10], Y[5]), Eq(Y[4], 1)), 14)
assert Float(P(Gt(Y[8], Y[9]), Eq(Y[3], 2)), 14) == Float(1 - P(Le(Y[8], Y[9]), Eq(Y[3], 2)), 14)
assert Float(P(Lt(Y[1], Y[4]), Eq(Y[0], 0)), 14) == Float(1 - P(Ge(Y[1], Y[4]), Eq(Y[0], 0)), 14)
assert P(Eq(Y[5], Y[10]), Eq(Y[2], 1)) == P(Eq(Y[10], Y[5]), Eq(Y[2], 1))
assert P(Gt(Y[1], Y[2]), Eq(Y[0], 1)) == P(Lt(Y[2], Y[1]), Eq(Y[0], 1))
assert P(Ge(Y[7], Y[6]), Eq(Y[4], 1)) == P(Le(Y[6], Y[7]), Eq(Y[4], 1))
#test symbolic queries
a, b, c, d = symbols('a b c d')
T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]])
Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
query = P(Eq(Y[a], b), Eq(Y[c], d))
assert query.subs({a:10, b:2, c:5, d:1}).evalf().round(4) == P(Eq(Y[10], 2), Eq(Y[5], 1)).round(4)
assert query.subs({a:15, b:0, c:10, d:1}).evalf().round(4) == P(Eq(Y[15], 0), Eq(Y[10], 1)).round(4)
query_gt = P(Gt(Y[a], b), Eq(Y[c], d))
query_le = P(Le(Y[a], b), Eq(Y[c], d))
assert query_gt.subs({a:5, b:2, c:1, d:0}).evalf() + query_le.subs({a:5, b:2, c:1, d:0}).evalf() == 1
query_ge = P(Ge(Y[a], b), Eq(Y[c], d))
query_lt = P(Lt(Y[a], b), Eq(Y[c], d))
assert query_ge.subs({a:4, b:1, c:0, d:2}).evalf() + query_lt.subs({a:4, b:1, c:0, d:2}).evalf() == 1
def test_sample_stochastic_process():
if not import_module('scipy'):
skip('SciPy Not installed. Skip sampling tests')
import random
random.seed(0)
numpy = import_module('numpy')
if numpy:
numpy.random.seed(0) # scipy uses numpy to sample so to set its seed
T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
for samps in range(10):
assert next(sample_stochastic_process(Y)) in Y.state_space
Z = DiscreteMarkovChain("Z", ['1', 1, 0], T)
for samps in range(10):
assert next(sample_stochastic_process(Z)) in Z.state_space
T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)],
[Rational(1, 3), 0, Rational(2, 3)],
[S.Half, S.Half, 0]])
X = DiscreteMarkovChain('X', [0, 1, 2], T)
for samps in range(10):
assert next(sample_stochastic_process(X)) in X.state_space
W = DiscreteMarkovChain('W', [1, pi, oo], T)
for samps in range(10):
assert next(sample_stochastic_process(W)) in W.state_space
def test_ContinuousMarkovChain():
T1 = Matrix([[S(-2), S(2), S.Zero],
[S.Zero, S.NegativeOne, S.One],
[Rational(3, 2), Rational(3, 2), S(-3)]])
C1 = ContinuousMarkovChain('C', [0, 1, 2], T1)
assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]])
T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]])
C2 = ContinuousMarkovChain('C', [0, 1, 2], T2)
A, t = C2.generator_matrix, symbols('t', positive=True)
assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0],
[S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0],
[S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]])
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1))
assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half
assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1),
Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half)
assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) |
(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)),
Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One
assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half
assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half)
+ (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2))
raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half)))
assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0))
TS1 = MatrixSymbol('G', 3, 3)
CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1)
A = CS1.generator_matrix
assert CS1.transition_probabilities(A)(t) == exp(t*A)
C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2)
assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half
assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half
#test probability queries
G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
assert P(Eq(C(7.385), C(3.19)), Eq(C(0.862), 0)).round(5) == Float(0.35469, 5)
assert P(Gt(C(98.715), C(19.807)), Eq(C(11.314), 2)).round(5) == Float(0.32452, 5)
assert P(Le(C(5.9), C(10.112)), Eq(C(4), 1)).round(6) == Float(0.675214, 6)
assert Float(P(Eq(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) == Float(1 - P(Ne(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14)
assert Float(P(Gt(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) == Float(1 - P(Le(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14)
assert Float(P(Lt(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) == Float(1 - P(Ge(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14)
assert P(Eq(C(5.243), C(10.912)), Eq(C(2.174), 1)) == P(Eq(C(10.912), C(5.243)), Eq(C(2.174), 1))
assert P(Gt(C(2.344), C(9.9)), Eq(C(1.102), 1)) == P(Lt(C(9.9), C(2.344)), Eq(C(1.102), 1))
assert P(Ge(C(7.87), C(1.008)), Eq(C(0.153), 1)) == P(Le(C(1.008), C(7.87)), Eq(C(0.153), 1))
#test symbolic queries
a, b, c, d = symbols('a b c d')
query = P(Eq(C(a), b), Eq(C(c), d))
assert query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10) == P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
query_gt = P(Gt(C(a), b), Eq(C(c), d))
query_le = P(Le(C(a), b), Eq(C(c), d))
assert query_gt.subs({a:13.2, b:0, c:3.29, d:2}).evalf() + query_le.subs({a:13.2, b:0, c:3.29, d:2}).evalf() == 1
query_ge = P(Ge(C(a), b), Eq(C(c), d))
query_lt = P(Lt(C(a), b), Eq(C(c), d))
assert query_ge.subs({a:7.43, b:1, c:1.45, d:0}).evalf() + query_lt.subs({a:7.43, b:1, c:1.45, d:0}).evalf() == 1
def test_BernoulliProcess():
B = BernoulliProcess("B", p=0.6, success=1, failure=0)
assert B.state_space == FiniteSet(0, 1)
assert B.index_set == S.Naturals0
assert B.success == 1
assert B.failure == 0
X = BernoulliProcess("X", p=Rational(1,3), success='H', failure='T')
assert X.state_space == FiniteSet('H', 'T')
H, T = symbols("H,T")
assert E(X[1]+X[2]*X[3]) == H**2/9 + 4*H*T/9 + H/3 + 4*T**2/9 + 2*T/3
t, x = symbols('t, x', positive=True, integer=True)
assert isinstance(B[t], RandomIndexedSymbol)
raises(ValueError, lambda: BernoulliProcess("X", p=1.1, success=1, failure=0))
raises(NotImplementedError, lambda: B(t))
raises(IndexError, lambda: B[-3])
assert B.joint_distribution(B[3], B[9]) == JointDistributionHandmade(Lambda((B[3], B[9]),
Piecewise((0.6, Eq(B[3], 1)), (0.4, Eq(B[3], 0)), (0, True))
*Piecewise((0.6, Eq(B[9], 1)), (0.4, Eq(B[9], 0)), (0, True))))
assert B.joint_distribution(2, B[4]) == JointDistributionHandmade(Lambda((B[2], B[4]),
Piecewise((0.6, Eq(B[2], 1)), (0.4, Eq(B[2], 0)), (0, True))
*Piecewise((0.6, Eq(B[4], 1)), (0.4, Eq(B[4], 0)), (0, True))))
# Test for the sum distribution of Bernoulli Process RVs
Y = B[1] + B[2] + B[3]
assert P(Eq(Y, 0)).round(2) == Float(0.06, 1)
assert P(Eq(Y, 2)).round(2) == Float(0.43, 2)
assert P(Eq(Y, 4)).round(2) == 0
assert P(Gt(Y, 1)).round(2) == Float(0.65, 2)
# Test for independency of each Random Indexed variable
assert P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) == Float(0.06, 1)
assert E(2 * B[1] + B[2]).round(2) == Float(1.80, 3)
assert E(2 * B[1] + B[2] + 5).round(2) == Float(6.80, 3)
assert E(B[2] * B[4] + B[10]).round(2) == Float(0.96, 2)
assert E(B[2] > 0, Eq(B[1],1) & Eq(B[2],1)).round(2) == Float(0.60,2)
assert E(B[1]) == 0.6
assert P(B[1] > 0).round(2) == Float(0.60, 2)
assert P(B[1] < 1).round(2) == Float(0.40, 2)
assert P(B[1] > 0, B[2] <= 1).round(2) == Float(0.60, 2)
assert P(B[12] * B[5] > 0).round(2) == Float(0.36, 2)
assert P(B[12] * B[5] > 0, B[4] < 1).round(2) == Float(0.36, 2)
assert P(Eq(B[2], 1), B[2] > 0) == 1
assert P(Eq(B[5], 3)) == 0
assert P(Eq(B[1], 1), B[1] < 0) == 0
assert P(B[2] > 0, Eq(B[2], 1)) == 1
assert P(B[2] < 0, Eq(B[2], 1)) == 0
assert P(B[2] > 0, B[2]==7) == 0
assert P(B[5] > 0, B[5]) == BernoulliDistribution(0.6, 0, 1)
raises(ValueError, lambda: P(3))
raises(ValueError, lambda: P(B[3] > 0, 3))
# test issue 19456
expr = Sum(B[t], (t, 0, 4))
expr2 = Sum(B[t], (t, 1, 3))
expr3 = Sum(B[t]**2, (t, 1, 3))
assert expr.doit() == B[0] + B[1] + B[2] + B[3] + B[4]
assert expr2.doit() == Y
assert expr3.doit() == B[1]**2 + B[2]**2 + B[3]**2
assert B[2*t].free_symbols == {B[2*t], t}
assert B[4].free_symbols == {B[4]}
assert B[x*t].free_symbols == {B[x*t], x, t}
def test_PoissonProcess():
X = PoissonProcess("X", 3)
assert X.state_space == S.Naturals0
assert X.index_set == Interval(0, oo)
assert X.lamda == 3
t, d, x, y = symbols('t d x y', positive=True)
assert isinstance(X(t), RandomIndexedSymbol)
assert X.distribution(X(t)) == PoissonDistribution(3*t)
raises(ValueError, lambda: PoissonProcess("X", -1))
raises(NotImplementedError, lambda: X[t])
raises(IndexError, lambda: X(-5))
assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(Lambda((X(2), X(3)),
6**X(2)*9**X(3)*exp(-15)/(factorial(X(2))*factorial(X(3)))))
assert X.joint_distribution(4, 6) == JointDistributionHandmade(Lambda((X(4), X(6)),
12**X(4)*18**X(6)*exp(-30)/(factorial(X(4))*factorial(X(6)))))
assert P(X(t) < 1) == exp(-3*t)
assert P(Eq(X(t), 0), Contains(t, Interval.Lopen(3, 5))) == exp(-6) # exp(-2*lamda)
res = P(Eq(X(t), 1), Contains(t, Interval.Lopen(3, 4)))
assert res == 3*exp(-3)
# Equivalent to P(Eq(X(t), 1))**4 because of non-overlapping intervals
assert P(Eq(X(t), 1) & Eq(X(d), 1) & Eq(X(x), 1) & Eq(X(y), 1), Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3))
& Contains(y, Interval.Lopen(3, 4))) == res**4
# Return Probability because of overlapping intervals
assert P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 2))
& Contains(d, Interval.Ropen(2, 4))) == \
Probability(Eq(X(d), 3) & Eq(X(t), 2), Contains(t, Interval.Lopen(0, 2))
& Contains(d, Interval.Ropen(2, 4)))
raises(ValueError, lambda: P(Eq(X(t), 2) & Eq(X(d), 3),
Contains(t, Interval.Lopen(0, 4)) & Contains(d, Interval.Lopen(3, oo)))) # no bound on d
assert P(Eq(X(3), 2)) == 81*exp(-9)/2
assert P(Eq(X(t), 2), Contains(t, Interval.Lopen(0, 5))) == 225*exp(-15)/2
# Check that probability works correctly by adding it to 1
res1 = P(X(t) <= 3, Contains(t, Interval.Lopen(0, 5)))
res2 = P(X(t) > 3, Contains(t, Interval.Lopen(0, 5)))
assert res1 == 691*exp(-15)
assert (res1 + res2).simplify() == 1
# Check Not and Or
assert P(Not(Eq(X(t), 2) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & \
Contains(d, Interval.Lopen(7, 8))).simplify() == -18*exp(-6) + 234*exp(-9) + 1
assert P(Eq(X(t), 2) | Ne(X(t), 4), Contains(t, Interval.Ropen(2, 4))) == 1 - 36*exp(-6)
raises(ValueError, lambda: P(X(t) > 2, X(t) + X(d)))
assert E(X(t)) == 3*t # property of the distribution at a given timestamp
assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == 75
assert E(X(t)**2, Contains(t, Interval.Lopen(0, 1))) == 12
assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Ropen(1, 2))) == \
Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Ropen(1, 2)))
# Value Error because of infinite time bound
raises(ValueError, lambda: E(X(t)**3, Contains(t, Interval.Lopen(1, oo))))
# Equivalent to E(X(t)**2) - E(X(d)**2) == E(X(1)**2) - E(X(1)**2) == 0
assert E((X(t) + X(d))*(X(t) - X(d)), Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Lopen(1, 2))) == 0
assert E(X(2) + x*E(X(5))) == 15*x + 6
assert E(x*X(1) + y) == 3*x + y
assert P(Eq(X(1), 2) & Eq(X(t), 3), Contains(t, Interval.Lopen(1, 2))) == 81*exp(-6)/4
Y = PoissonProcess("Y", 6)
Z = X + Y
assert Z.lamda == X.lamda + Y.lamda == 9
raises(ValueError, lambda: X + 5) # should be added be only PoissonProcess instance
N, M = Z.split(4, 5)
assert N.lamda == 4
assert M.lamda == 5
raises(ValueError, lambda: Z.split(3, 2)) # 2+3 != 9
raises(ValueError, lambda :P(Eq(X(t), 0), Contains(t, Interval.Lopen(1, 3)) & Eq(X(1), 0)))
# check if it handles queries with two random variables in one args
res1 = P(Eq(N(3), N(5)))
assert res1 == P(Eq(N(t), 0), Contains(t, Interval(3, 5)))
res2 = P(N(3) > N(1))
assert res2 == P((N(t) > 0), Contains(t, Interval(1, 3)))
assert P(N(3) < N(1)) == 0 # condition is not possible
res3 = P(N(3) <= N(1)) # holds only for Eq(N(3), N(1))
assert res3 == P(Eq(N(t), 0), Contains(t, Interval(1, 3)))
# tests from https://www.probabilitycourse.com/chapter11/11_1_2_basic_concepts_of_the_poisson_process.php
X = PoissonProcess('X', 10) # 11.1
assert P(Eq(X(S(1)/3), 3) & Eq(X(1), 10)) == exp(-10)*Rational(8000000000, 11160261)
assert P(Eq(X(1), 1), Eq(X(S(1)/3), 3)) == 0
assert P(Eq(X(1), 10), Eq(X(S(1)/3), 3)) == P(Eq(X(S(2)/3), 7))
X = PoissonProcess('X', 2) # 11.2
assert P(X(S(1)/2) < 1) == exp(-1)
assert P(X(3) < 1, Eq(X(1), 0)) == exp(-4)
assert P(Eq(X(4), 3), Eq(X(2), 3)) == exp(-4)
X = PoissonProcess('X', 3)
assert P(Eq(X(2), 5) & Eq(X(1), 2)) == Rational(81, 4)*exp(-6)
# check few properties
assert P(X(2) <= 3, X(1)>=1) == 3*P(Eq(X(1), 0)) + 2*P(Eq(X(1), 1)) + P(Eq(X(1), 2))
assert P(X(2) <= 3, X(1) > 1) == 2*P(Eq(X(1), 0)) + 1*P(Eq(X(1), 1))
assert P(Eq(X(2), 5) & Eq(X(1), 2)) == P(Eq(X(1), 3))*P(Eq(X(1), 2))
assert P(Eq(X(3), 4), Eq(X(1), 3)) == P(Eq(X(2), 1))
def test_WienerProcess():
X = WienerProcess("X")
assert X.state_space == S.Reals
assert X.index_set == Interval(0, oo)
t, d, x, y = symbols('t d x y', positive=True)
assert isinstance(X(t), RandomIndexedSymbol)
assert X.distribution(X(t)) == NormalDistribution(0, sqrt(t))
raises(ValueError, lambda: PoissonProcess("X", -1))
raises(NotImplementedError, lambda: X[t])
raises(IndexError, lambda: X(-2))
assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(
Lambda((X(2), X(3)), sqrt(6)*exp(-X(2)**2/4)*exp(-X(3)**2/6)/(12*pi)))
assert X.joint_distribution(4, 6) == JointDistributionHandmade(
Lambda((X(4), X(6)), sqrt(6)*exp(-X(4)**2/8)*exp(-X(6)**2/12)/(24*pi)))
assert P(X(t) < 3).simplify() == erf(3*sqrt(2)/(2*sqrt(t)))/2 + S(1)/2
assert P(X(t) > 2, Contains(t, Interval.Lopen(3, 7))).simplify() == S(1)/2 -\
erf(sqrt(2)/2)/2
# Equivalent to P(X(1)>1)**4
assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1),
Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2))
& Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() ==\
(1 - erf(sqrt(2)/2))*(1 - erf(sqrt(2)))*(1 - erf(3*sqrt(2)/2))*(1 - erf(2*sqrt(2)))/16
# Contains an overlapping interval so, return Probability
assert P((X(t)< 2) & (X(d)> 3), Contains(t, Interval.Lopen(0, 2))
& Contains(d, Interval.Ropen(2, 4))) == Probability((X(d) > 3) & (X(t) < 2),
Contains(d, Interval.Ropen(2, 4)) & Contains(t, Interval.Lopen(0, 2)))
assert str(P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
Contains(d, Interval.Lopen(7, 8))).simplify()) == \
'-(1 - erf(3*sqrt(2)/2))*(2 - erfc(5/2))/4 + 1'
# Distribution has mean 0 at each timestamp
assert E(X(t)) == 0
assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Ropen(1, 2))) == Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2),
Contains(d, Interval.Ropen(1, 2)) & Contains(t, Interval.Lopen(0, 1)))
assert E(X(t) + x*E(X(3))) == 0
def test_GammaProcess_symbolic():
t, d, x, y, g, l = symbols('t d x y g l', positive=True)
X = GammaProcess("X", l, g)
raises(NotImplementedError, lambda: X[t])
raises(IndexError, lambda: X(-1))
assert isinstance(X(t), RandomIndexedSymbol)
assert X.state_space == Interval(0, oo)
assert X.distribution(X(t)) == GammaDistribution(g*t, 1/l)
assert X.joint_distribution(5, X(3)) == JointDistributionHandmade(Lambda(
(X(5), X(3)), l**(8*g)*exp(-l*X(3))*exp(-l*X(5))*X(3)**(3*g - 1)*X(5)**(5*g
- 1)/(gamma(3*g)*gamma(5*g))))
# property of the gamma process at any given timestamp
assert E(X(t)) == g*t/l
assert variance(X(t)).simplify() == g*t/l**2
# Equivalent to E(2*X(1)) + E(X(1)**2) + E(X(1)**3), where E(X(1)) == g/l
assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1))
& Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == \
2*g/l + (g**2 + g)/l**2 + (g**3 + 3*g**2 + 2*g)/l**3
assert P(X(t) > 3, Contains(t, Interval.Lopen(3, 4))).simplify() == \
1 - lowergamma(g, 3*l)/gamma(g) # equivalent to P(X(1)>3)
def test_GammaProcess_numeric():
t, d, x, y = symbols('t d x y', positive=True)
X = GammaProcess("X", 1, 2)
assert X.state_space == Interval(0, oo)
assert X.index_set == Interval(0, oo)
assert X.lamda == 1
assert X.gamma == 2
raises(ValueError, lambda: GammaProcess("X", -1, 2))
raises(ValueError, lambda: GammaProcess("X", 0, -2))
raises(ValueError, lambda: GammaProcess("X", -1, -2))
# all are independent because of non-overlapping intervals
assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t,
Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x,
Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() == \
120*exp(-10)
# Check working with Not and Or
assert P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
Contains(d, Interval.Lopen(7, 8))).simplify() == -4*exp(-3) + 472*exp(-8)/3 + 1
assert P((X(t) > 2) | (X(t) < 4), Contains(t, Interval.Ropen(1, 4))).simplify() == \
-643*exp(-4)/15 + 109*exp(-2)/15 + 1
assert E(X(t)) == 2*t # E(X(t)) == gamma*t/l
assert E(X(2) + x*E(X(5))) == 10*x + 4
|
d2f5fd4dcf9a31179890403cc1a0e56beb7e88b7e38c0f6399c3e605ca5eed50 | from sympy import (S, Symbol, Sum, I, lambdify, re, im, log, simplify, sqrt,
zeta, pi, besseli, Dummy, oo, Piecewise, Rational, beta,
floor, FiniteSet)
from sympy.core.relational import Eq, Ne
from sympy.functions.elementary.exponential import exp
from sympy.logic.boolalg import Or
from sympy.sets.fancysets import Range
from sympy.stats import (P, E, variance, density, characteristic_function,
where, moment_generating_function, skewness, cdf,
kurtosis, coskewness)
from sympy.stats.drv_types import (PoissonDistribution, GeometricDistribution,
Poisson, Geometric, Hermite, Logarithmic,
NegativeBinomial, Skellam, YuleSimon, Zeta,
DiscreteRV)
from sympy.stats.rv import sample
from sympy.testing.pytest import slow, nocache_fail, raises, skip, ignore_warnings
from sympy.external import import_module
from sympy.stats.symbolic_probability import Expectation
x = Symbol('x')
def test_PoissonDistribution():
l = 3
p = PoissonDistribution(l)
assert abs(p.cdf(10).evalf() - 1) < .001
assert abs(p.cdf(10.4).evalf() - 1) < .001
assert p.expectation(x, x) == l
assert p.expectation(x**2, x) - p.expectation(x, x)**2 == l
def test_Poisson():
l = 3
x = Poisson('x', l)
assert E(x) == l
assert variance(x) == l
assert density(x) == PoissonDistribution(l)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert isinstance(E(x, evaluate=False), Expectation)
assert isinstance(E(2*x, evaluate=False), Expectation)
# issue 8248
assert x.pspace.compute_expectation(1) == 1
@slow
def test_GeometricDistribution():
p = S.One / 5
d = GeometricDistribution(p)
assert d.expectation(x, x) == 1/p
assert d.expectation(x**2, x) - d.expectation(x, x)**2 == (1-p)/p**2
assert abs(d.cdf(20000).evalf() - 1) < .001
assert abs(d.cdf(20000.8).evalf() - 1) < .001
G = Geometric('G', p=S(1)/4)
assert cdf(G)(S(7)/2) == P(G <= S(7)/2)
X = Geometric('X', Rational(1, 5))
Y = Geometric('Y', Rational(3, 10))
assert coskewness(X, X + Y, X + 2*Y).simplify() == sqrt(230)*Rational(81, 1150)
def test_Hermite():
a1 = Symbol("a1", positive=True)
a2 = Symbol("a2", negative=True)
raises(ValueError, lambda: Hermite("H", a1, a2))
a1 = Symbol("a1", negative=True)
a2 = Symbol("a2", positive=True)
raises(ValueError, lambda: Hermite("H", a1, a2))
a1 = Symbol("a1", positive=True)
x = Symbol("x")
H = Hermite("H", a1, a2)
assert moment_generating_function(H)(x) == exp(a1*(exp(x) - 1)
+ a2*(exp(2*x) - 1))
assert characteristic_function(H)(x) == exp(a1*(exp(I*x) - 1)
+ a2*(exp(2*I*x) - 1))
assert E(H) == a1 + 2*a2
H = Hermite("H", a1=5, a2=4)
assert density(H)(2) == 33*exp(-9)/2
assert E(H) == 13
assert variance(H) == 21
assert kurtosis(H) == Rational(464,147)
assert skewness(H) == 37*sqrt(21)/441
def test_Logarithmic():
p = S.Half
x = Logarithmic('x', p)
assert E(x) == -p / ((1 - p) * log(1 - p))
assert variance(x) == -1/log(2)**2 + 2/log(2)
assert E(2*x**2 + 3*x + 4) == 4 + 7 / log(2)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert isinstance(E(x, evaluate=False), Expectation)
@nocache_fail
def test_negative_binomial():
r = 5
p = S.One / 3
x = NegativeBinomial('x', r, p)
assert E(x) == p*r / (1-p)
# This hangs when run with the cache disabled:
assert variance(x) == p*r / (1-p)**2
assert E(x**5 + 2*x + 3) == Rational(9207, 4)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert isinstance(E(x, evaluate=False), Expectation)
def test_skellam():
mu1 = Symbol('mu1')
mu2 = Symbol('mu2')
z = Symbol('z')
X = Skellam('x', mu1, mu2)
assert density(X)(z) == (mu1/mu2)**(z/2) * \
exp(-mu1 - mu2)*besseli(z, 2*sqrt(mu1*mu2))
assert skewness(X).expand() == mu1/(mu1*sqrt(mu1 + mu2) + mu2 *
sqrt(mu1 + mu2)) - mu2/(mu1*sqrt(mu1 + mu2) + mu2*sqrt(mu1 + mu2))
assert variance(X).expand() == mu1 + mu2
assert E(X) == mu1 - mu2
assert characteristic_function(X)(z) == exp(
mu1*exp(I*z) - mu1 - mu2 + mu2*exp(-I*z))
assert moment_generating_function(X)(z) == exp(
mu1*exp(z) - mu1 - mu2 + mu2*exp(-z))
def test_yule_simon():
from sympy import S
rho = S(3)
x = YuleSimon('x', rho)
assert simplify(E(x)) == rho / (rho - 1)
assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2))
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert isinstance(E(x, evaluate=False), Expectation)
# To test the cdf function
assert cdf(x)(x) == Piecewise((-beta(floor(x), 4)*floor(x) + 1, x >= 1), (0, True))
def test_zeta():
s = S(5)
x = Zeta('x', s)
assert E(x) == zeta(s-1) / zeta(s)
assert simplify(variance(x)) == (
zeta(s) * zeta(s-2) - zeta(s-1)**2) / zeta(s)**2
@slow
def test_sample_discrete():
X = Geometric('X', S.Half)
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in X.pspace.domain.set
samps = next(sample(X, size=2)) # This takes long time if ran without scipy
for samp in samps:
assert samp in X.pspace.domain.set
def test_discrete_probability():
X = Geometric('X', Rational(1, 5))
Y = Poisson('Y', 4)
G = Geometric('e', x)
assert P(Eq(X, 3)) == Rational(16, 125)
assert P(X < 3) == Rational(9, 25)
assert P(X > 3) == Rational(64, 125)
assert P(X >= 3) == Rational(16, 25)
assert P(X <= 3) == Rational(61, 125)
assert P(Ne(X, 3)) == Rational(109, 125)
assert P(Eq(Y, 3)) == 32*exp(-4)/3
assert P(Y < 3) == 13*exp(-4)
assert P(Y > 3).equals(32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3)
assert P(Y >= 3).equals(32*(Rational(-39, 32) + 3*exp(4)/32)*exp(-4)/3)
assert P(Y <= 3) == 71*exp(-4)/3
assert P(Ne(Y, 3)).equals(
13*exp(-4) + 32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3)
assert P(X < S.Infinity) is S.One
assert P(X > S.Infinity) is S.Zero
assert P(G < 3) == x*(2-x)
assert P(Eq(G, 3)) == x*(-x + 1)**2
def test_DiscreteRV():
p = S(1)/2
x = Symbol('x', integer=True, positive=True)
pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution
D = DiscreteRV(x, pdf, set=S.Naturals, check=True)
assert E(D) == E(Geometric('G', S(1)/2)) == 2
assert P(D > 3) == S(1)/8
assert D.pspace.domain.set == S.Naturals
raises(ValueError, lambda: DiscreteRV(x, x, FiniteSet(*range(4)), check=True))
# purposeful invalid pmf but it should not raise since check=False
# see test_drv_types.test_ContinuousRV for explanation
X = DiscreteRV(x, 1/x, S.Naturals)
assert P(X < 2) == 1
assert E(X) == oo
def test_precomputed_characteristic_functions():
import mpmath
def test_cf(dist, support_lower_limit, support_upper_limit):
pdf = density(dist)
t = S('t')
x = S('x')
# first function is the hardcoded CF of the distribution
cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath')
# second function is the Fourier transform of the density function
f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath')
cf2 = lambda t: mpmath.nsum(lambda x: f(x, t), [
support_lower_limit, support_upper_limit], maxdegree=10)
# compare the two functions at various points
for test_point in [2, 5, 8, 11]:
n1 = cf1(test_point)
n2 = cf2(test_point)
assert abs(re(n1) - re(n2)) < 1e-12
assert abs(im(n1) - im(n2)) < 1e-12
test_cf(Geometric('g', Rational(1, 3)), 1, mpmath.inf)
test_cf(Logarithmic('l', Rational(1, 5)), 1, mpmath.inf)
test_cf(NegativeBinomial('n', 5, Rational(1, 7)), 0, mpmath.inf)
test_cf(Poisson('p', 5), 0, mpmath.inf)
test_cf(YuleSimon('y', 5), 1, mpmath.inf)
test_cf(Zeta('z', 5), 1, mpmath.inf)
def test_moment_generating_functions():
t = S('t')
geometric_mgf = moment_generating_function(Geometric('g', S.Half))(t)
assert geometric_mgf.diff(t).subs(t, 0) == 2
logarithmic_mgf = moment_generating_function(Logarithmic('l', S.Half))(t)
assert logarithmic_mgf.diff(t).subs(t, 0) == 1/log(2)
negative_binomial_mgf = moment_generating_function(
NegativeBinomial('n', 5, Rational(1, 3)))(t)
assert negative_binomial_mgf.diff(t).subs(t, 0) == Rational(5, 2)
poisson_mgf = moment_generating_function(Poisson('p', 5))(t)
assert poisson_mgf.diff(t).subs(t, 0) == 5
skellam_mgf = moment_generating_function(Skellam('s', 1, 1))(t)
assert skellam_mgf.diff(t).subs(
t, 2) == (-exp(-2) + exp(2))*exp(-2 + exp(-2) + exp(2))
yule_simon_mgf = moment_generating_function(YuleSimon('y', 3))(t)
assert simplify(yule_simon_mgf.diff(t).subs(t, 0)) == Rational(3, 2)
zeta_mgf = moment_generating_function(Zeta('z', 5))(t)
assert zeta_mgf.diff(t).subs(t, 0) == pi**4/(90*zeta(5))
def test_Or():
X = Geometric('X', S.Half)
P(Or(X < 3, X > 4)) == Rational(13, 16)
P(Or(X > 2, X > 1)) == P(X > 1)
P(Or(X >= 3, X < 3)) == 1
def test_where():
X = Geometric('X', Rational(1, 5))
Y = Poisson('Y', 4)
assert where(X**2 > 4).set == Range(3, S.Infinity, 1)
assert where(X**2 >= 4).set == Range(2, S.Infinity, 1)
assert where(Y**2 < 9).set == Range(0, 3, 1)
assert where(Y**2 <= 9).set == Range(0, 4, 1)
def test_conditional():
X = Geometric('X', Rational(2, 3))
Y = Poisson('Y', 3)
assert P(X > 2, X > 3) == 1
assert P(X > 3, X > 2) == Rational(1, 3)
assert P(Y > 2, Y < 2) == 0
assert P(Eq(Y, 3), Y >= 0) == 9*exp(-3)/2
assert P(Eq(Y, 3), Eq(Y, 2)) == 0
assert P(X < 2, Eq(X, 2)) == 0
assert P(X > 2, Eq(X, 3)) == 1
def test_product_spaces():
X1 = Geometric('X1', S.Half)
X2 = Geometric('X2', Rational(1, 3))
#assert str(P(X1 + X2 < 3, evaluate=False)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """\
# + """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, -oo, -1))"""
n = Dummy('n')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert P(X1 + X2 < 3, evaluate=False).rewrite(Sum).dummy_eq(Sum(Piecewise((2**(-n)/4,
n + 2 >= 1), (0, True)), (n, -oo, -1))/3)
#assert str(P(X1 + X2 > 3)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """ +\
# """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, 1, oo))"""
assert P(X1 + X2 > 3).dummy_eq(Sum(Piecewise((2**(X2 - n - 2)*(Rational(2, 3))**(X2 - 1)/6,
-X2 + n + 3 >= 1), (0, True)),
(X2, 1, oo), (n, 1, oo)))
# assert str(P(Eq(X1 + X2, 3))) == """Sum(Piecewise((2**(X2 - 2)*(2/3)**(X2 - 1)/6, """ +\
# """X2 <= 2), (0, True)), (X2, 1, oo))"""
assert P(Eq(X1 + X2, 3)) == Rational(1, 12)
def test_sample_numpy():
distribs_numpy = [
Geometric('G', 0.5),
Poisson('P', 1),
Zeta('Z', 2)
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Skellam('S', 1, 1), library='numpy')))
raises(NotImplementedError,
lambda: Skellam('S', 1, 1).pspace.distribution.sample(library='tensorflow'))
def test_sample_scipy():
p = S(2)/3
x = Symbol('x', integer=True, positive=True)
pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution
distribs_scipy = [
DiscreteRV(x, pdf, set=S.Naturals),
Geometric('G', 0.5),
Logarithmic('L', 0.5),
NegativeBinomial('N', 5, 0.4),
Poisson('P', 1),
Skellam('S', 1, 1),
YuleSimon('Y', 1),
Zeta('Z', 2)
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
z_sample = list(sample(Zeta("G", 7), size=size, numsamples=numsamples))
assert len(z_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size, library='scipy'))
samps2 = next(sample(X, size=(2, 2), library='scipy'))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Geometric('G', 0.5),
Poisson('P', 1),
NegativeBinomial('N', 5, 0.4)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Skellam('S', 1, 1), library='pymc3')))
|
9083ad98b6e8f3d4469aff2b85f482a7d9886569590df66cd1573854f1642618 | from sympy import E as e
from sympy import (Symbol, Abs, exp, expint, S, pi, simplify, Interval, erf, erfc, Ne,
EulerGamma, Eq, log, lowergamma, uppergamma, symbols, sqrt, And,
gamma, beta, Piecewise, Integral, sin, cos, tan, sinh, cosh,
besseli, floor, expand_func, Rational, I, re, Lambda, asin,
im, lambdify, hyper, diff, Or, Mul, sign, Dummy, Sum,
factorial, binomial, erfi, besselj, besselk)
from sympy.external import import_module
from sympy.functions.special.error_functions import erfinv
from sympy.functions.special.hyper import meijerg
from sympy.sets.sets import Intersection, FiniteSet
from sympy.stats import (P, E, where, density, variance, covariance, skewness, kurtosis, median,
given, pspace, cdf, characteristic_function, moment_generating_function,
ContinuousRV, sample, Arcsin, Benini, Beta, BetaNoncentral, BetaPrime,
Cauchy, Chi, ChiSquared, ChiNoncentral, Dagum, Erlang, ExGaussian,
Exponential, ExponentialPower, FDistribution, FisherZ, Frechet, Gamma,
GammaInverse, Gompertz, Gumbel, Kumaraswamy, Laplace, Levy, Logistic,
LogLogistic, LogitNormal, LogNormal, Maxwell, Moyal, Nakagami, Normal, GaussianInverse,
Pareto, PowerFunction, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, ShiftedGompertz, StudentT,
Trapezoidal, Triangular, Uniform, UniformSum, VonMises, Weibull, coskewness,
WignerSemicircle, Wald, correlation, moment, cmoment, smoment, quantile,
Lomax, BoundedPareto)
from sympy.stats.crv_types import NormalDistribution, ExponentialDistribution, ContinuousDistributionHandmade
from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution, MultivariateNormalDistribution
from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDomain
from sympy.stats.compound_rv import CompoundPSpace
from sympy.stats.symbolic_probability import Probability
from sympy.testing.pytest import raises, XFAIL, slow, skip, ignore_warnings
from sympy.testing.randtest import verify_numerically as tn
oo = S.Infinity
x, y, z = map(Symbol, 'xyz')
def test_single_normal():
mu = Symbol('mu', real=True)
sigma = Symbol('sigma', positive=True)
X = Normal('x', 0, 1)
Y = X*sigma + mu
assert E(Y) == mu
assert variance(Y) == sigma**2
pdf = density(Y)
x = Symbol('x', real=True)
assert (pdf(x) ==
2**S.Half*exp(-(x - mu)**2/(2*sigma**2))/(2*pi**S.Half*sigma))
assert P(X**2 < 1) == erf(2**S.Half/2)
assert quantile(Y)(x) == Intersection(S.Reals, FiniteSet(sqrt(2)*sigma*(sqrt(2)*mu/(2*sigma) + erfinv(2*x - 1))))
assert E(X, Eq(X, mu)) == mu
assert median(X) == FiniteSet(0)
# issue 8248
assert X.pspace.compute_expectation(1).doit() == 1
def test_conditional_1d():
X = Normal('x', 0, 1)
Y = given(X, X >= 0)
z = Symbol('z')
assert density(Y)(z) == 2 * density(X)(z)
assert Y.pspace.domain.set == Interval(0, oo)
assert E(Y) == sqrt(2) / sqrt(pi)
assert E(X**2) == E(Y**2)
def test_ContinuousDomain():
X = Normal('x', 0, 1)
assert where(X**2 <= 1).set == Interval(-1, 1)
assert where(X**2 <= 1).symbol == X.symbol
where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1)
raises(ValueError, lambda: where(sin(X) > 1))
Y = given(X, X >= 0)
assert Y.pspace.domain.set == Interval(0, oo)
@slow
def test_multiple_normal():
X, Y = Normal('x', 0, 1), Normal('y', 0, 1)
p = Symbol("p", positive=True)
assert E(X + Y) == 0
assert variance(X + Y) == 2
assert variance(X + X) == 4
assert covariance(X, Y) == 0
assert covariance(2*X + Y, -X) == -2*variance(X)
assert skewness(X) == 0
assert skewness(X + Y) == 0
assert kurtosis(X) == 3
assert kurtosis(X+Y) == 3
assert correlation(X, Y) == 0
assert correlation(X, X + Y) == correlation(X, X - Y)
assert moment(X, 2) == 1
assert cmoment(X, 3) == 0
assert moment(X + Y, 4) == 12
assert cmoment(X, 2) == variance(X)
assert smoment(X*X, 2) == 1
assert smoment(X + Y, 3) == skewness(X + Y)
assert smoment(X + Y, 4) == kurtosis(X + Y)
assert E(X, Eq(X + Y, 0)) == 0
assert variance(X, Eq(X + Y, 0)) == S.Half
assert quantile(X)(p) == sqrt(2)*erfinv(2*p - S.One)
def test_symbolic():
mu1, mu2 = symbols('mu1 mu2', real=True)
s1, s2 = symbols('sigma1 sigma2', positive=True)
rate = Symbol('lambda', positive=True)
X = Normal('x', mu1, s1)
Y = Normal('y', mu2, s2)
Z = Exponential('z', rate)
a, b, c = symbols('a b c', real=True)
assert E(X) == mu1
assert E(X + Y) == mu1 + mu2
assert E(a*X + b) == a*E(X) + b
assert variance(X) == s1**2
assert variance(X + a*Y + b) == variance(X) + a**2*variance(Y)
assert E(Z) == 1/rate
assert E(a*Z + b) == a*E(Z) + b
assert E(X + a*Z + b) == mu1 + a/rate + b
assert median(X) == FiniteSet(mu1)
def test_cdf():
X = Normal('x', 0, 1)
d = cdf(X)
assert P(X < 1) == d(1).rewrite(erfc)
assert d(0) == S.Half
d = cdf(X, X > 0) # given X>0
assert d(0) == 0
Y = Exponential('y', 10)
d = cdf(Y)
assert d(-5) == 0
assert P(Y > 3) == 1 - d(3)
raises(ValueError, lambda: cdf(X + Y))
Z = Exponential('z', 1)
f = cdf(Z)
assert f(z) == Piecewise((1 - exp(-z), z >= 0), (0, True))
def test_characteristic_function():
X = Uniform('x', 0, 1)
cf = characteristic_function(X)
assert cf(1) == -I*(-1 + exp(I))
Y = Normal('y', 1, 1)
cf = characteristic_function(Y)
assert cf(0) == 1
assert cf(1) == exp(I - S.Half)
Z = Exponential('z', 5)
cf = characteristic_function(Z)
assert cf(0) == 1
assert cf(1).expand() == Rational(25, 26) + I*Rational(5, 26)
X = GaussianInverse('x', 1, 1)
cf = characteristic_function(X)
assert cf(0) == 1
assert cf(1) == exp(1 - sqrt(1 - 2*I))
X = ExGaussian('x', 0, 1, 1)
cf = characteristic_function(X)
assert cf(0) == 1
assert cf(1) == (1 + I)*exp(Rational(-1, 2))/2
L = Levy('x', 0, 1)
cf = characteristic_function(L)
assert cf(0) == 1
assert cf(1) == exp(-sqrt(2)*sqrt(-I))
def test_moment_generating_function():
t = symbols('t', positive=True)
# Symbolic tests
a, b, c = symbols('a b c')
mgf = moment_generating_function(Beta('x', a, b))(t)
assert mgf == hyper((a,), (a + b,), t)
mgf = moment_generating_function(Chi('x', a))(t)
assert mgf == sqrt(2)*t*gamma(a/2 + S.Half)*\
hyper((a/2 + S.Half,), (Rational(3, 2),), t**2/2)/gamma(a/2) +\
hyper((a/2,), (S.Half,), t**2/2)
mgf = moment_generating_function(ChiSquared('x', a))(t)
assert mgf == (1 - 2*t)**(-a/2)
mgf = moment_generating_function(Erlang('x', a, b))(t)
assert mgf == (1 - t/b)**(-a)
mgf = moment_generating_function(ExGaussian("x", a, b, c))(t)
assert mgf == exp(a*t + b**2*t**2/2)/(1 - t/c)
mgf = moment_generating_function(Exponential('x', a))(t)
assert mgf == a/(a - t)
mgf = moment_generating_function(Gamma('x', a, b))(t)
assert mgf == (-b*t + 1)**(-a)
mgf = moment_generating_function(Gumbel('x', a, b))(t)
assert mgf == exp(b*t)*gamma(-a*t + 1)
mgf = moment_generating_function(Gompertz('x', a, b))(t)
assert mgf == b*exp(b)*expint(t/a, b)
mgf = moment_generating_function(Laplace('x', a, b))(t)
assert mgf == exp(a*t)/(-b**2*t**2 + 1)
mgf = moment_generating_function(Logistic('x', a, b))(t)
assert mgf == exp(a*t)*beta(-b*t + 1, b*t + 1)
mgf = moment_generating_function(Normal('x', a, b))(t)
assert mgf == exp(a*t + b**2*t**2/2)
mgf = moment_generating_function(Pareto('x', a, b))(t)
assert mgf == b*(-a*t)**b*uppergamma(-b, -a*t)
mgf = moment_generating_function(QuadraticU('x', a, b))(t)
assert str(mgf) == ("(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - "
"3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)")
mgf = moment_generating_function(RaisedCosine('x', a, b))(t)
assert mgf == pi**2*exp(a*t)*sinh(b*t)/(b*t*(b**2*t**2 + pi**2))
mgf = moment_generating_function(Rayleigh('x', a))(t)
assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\
*exp(a**2*t**2/2)/2 + 1
mgf = moment_generating_function(Triangular('x', a, b, c))(t)
assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + "
"2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))")
mgf = moment_generating_function(Uniform('x', a, b))(t)
assert mgf == (-exp(a*t) + exp(b*t))/(t*(-a + b))
mgf = moment_generating_function(UniformSum('x', a))(t)
assert mgf == ((exp(t) - 1)/t)**a
mgf = moment_generating_function(WignerSemicircle('x', a))(t)
assert mgf == 2*besseli(1, a*t)/(a*t)
# Numeric tests
mgf = moment_generating_function(Beta('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 1) == hyper((2,), (3,), 1)/2
mgf = moment_generating_function(Chi('x', 1))(t)
assert mgf.diff(t).subs(t, 1) == sqrt(2)*hyper((1,), (Rational(3, 2),), S.Half
)/sqrt(pi) + hyper((Rational(3, 2),), (Rational(3, 2),), S.Half) + 2*sqrt(2)*hyper((2,),
(Rational(5, 2),), S.Half)/(3*sqrt(pi))
mgf = moment_generating_function(ChiSquared('x', 1))(t)
assert mgf.diff(t).subs(t, 1) == I
mgf = moment_generating_function(Erlang('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == 1
mgf = moment_generating_function(ExGaussian("x", 0, 1, 1))(t)
assert mgf.diff(t).subs(t, 2) == -exp(2)
mgf = moment_generating_function(Exponential('x', 1))(t)
assert mgf.diff(t).subs(t, 0) == 1
mgf = moment_generating_function(Gamma('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == 1
mgf = moment_generating_function(Gumbel('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == EulerGamma + 1
mgf = moment_generating_function(Gompertz('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 1) == -e*meijerg(((), (1, 1)),
((0, 0, 0), ()), 1)
mgf = moment_generating_function(Laplace('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == 1
mgf = moment_generating_function(Logistic('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == beta(1, 1)
mgf = moment_generating_function(Normal('x', 0, 1))(t)
assert mgf.diff(t).subs(t, 1) == exp(S.Half)
mgf = moment_generating_function(Pareto('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 0) == expint(1, 0)
mgf = moment_generating_function(QuadraticU('x', 1, 2))(t)
assert mgf.diff(t).subs(t, 1) == -12*e - 3*exp(2)
mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t)
assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\
(1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2)
mgf = moment_generating_function(Rayleigh('x', 1))(t)
assert mgf.diff(t).subs(t, 0) == sqrt(2)*sqrt(pi)/2
mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t)
assert mgf.diff(t).subs(t, 1) == -e + exp(3)
mgf = moment_generating_function(Uniform('x', 0, 1))(t)
assert mgf.diff(t).subs(t, 1) == 1
mgf = moment_generating_function(UniformSum('x', 1))(t)
assert mgf.diff(t).subs(t, 1) == 1
mgf = moment_generating_function(WignerSemicircle('x', 1))(t)
assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\
besseli(0, 1)
def test_sample_continuous():
Z = ContinuousRV(z, exp(-z), set=Interval(0, oo))
assert density(Z)(-1) == 0
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(Z)) in Z.pspace.domain.set
sym, val = list(Z.pspace.sample().items())[0]
assert sym == Z and val in Interval(0, oo)
def test_ContinuousRV():
pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution
# X and Y should be equivalent
X = ContinuousRV(x, pdf, check=True)
Y = Normal('y', 0, 1)
assert variance(X) == variance(Y)
assert P(X > 0) == P(Y > 0)
Z = ContinuousRV(z, exp(-z), set=Interval(0, oo))
assert Z.pspace.domain.set == Interval(0, oo)
assert E(Z) == 1
assert P(Z > 5) == exp(-5)
raises(ValueError, lambda: ContinuousRV(z, exp(-z), set=Interval(0, 10), check=True))
# the correct pdf for Gamma(k, theta) but the integral in `check`
# integrates to something equivalent to 1 and not to 1 exactly
_x, k, theta = symbols("x k theta", positive=True)
pdf = 1/(gamma(k)*theta**k)*_x**(k-1)*exp(-_x/theta)
X = ContinuousRV(_x, pdf, set=Interval(0, oo))
Y = Gamma('y', k, theta)
assert (E(X) - E(Y)).simplify() == 0
assert (variance(X) - variance(Y)).simplify() == 0
def test_arcsin():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
X = Arcsin('x', a, b)
assert density(X)(x) == 1/(pi*sqrt((-x + b)*(x - a)))
assert cdf(X)(x) == Piecewise((0, a > x),
(2*asin(sqrt((-a + x)/(-a + b)))/pi, b >= x),
(1, True))
assert pspace(X).domain.set == Interval(a, b)
def test_benini():
alpha = Symbol("alpha", positive=True)
beta = Symbol("beta", positive=True)
sigma = Symbol("sigma", positive=True)
X = Benini('x', alpha, beta, sigma)
assert density(X)(x) == ((alpha/x + 2*beta*log(x/sigma)/x)
*exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2))
assert pspace(X).domain.set == Interval(sigma, oo)
raises(NotImplementedError, lambda: moment_generating_function(X))
alpha = Symbol("alpha", nonpositive=True)
raises(ValueError, lambda: Benini('x', alpha, beta, sigma))
beta = Symbol("beta", nonpositive=True)
raises(ValueError, lambda: Benini('x', alpha, beta, sigma))
alpha = Symbol("alpha", positive=True)
raises(ValueError, lambda: Benini('x', alpha, beta, sigma))
beta = Symbol("beta", positive=True)
sigma = Symbol("sigma", nonpositive=True)
raises(ValueError, lambda: Benini('x', alpha, beta, sigma))
def test_beta():
a, b = symbols('alpha beta', positive=True)
B = Beta('x', a, b)
assert pspace(B).domain.set == Interval(0, 1)
assert characteristic_function(B)(x) == hyper((a,), (a + b,), I*x)
assert density(B)(x) == x**(a - 1)*(1 - x)**(b - 1)/beta(a, b)
assert simplify(E(B)) == a / (a + b)
assert simplify(variance(B)) == a*b / (a**3 + 3*a**2*b + a**2 + 3*a*b**2 + 2*a*b + b**3 + b**2)
# Full symbolic solution is too much, test with numeric version
a, b = 1, 2
B = Beta('x', a, b)
assert expand_func(E(B)) == a / S(a + b)
assert expand_func(variance(B)) == (a*b) / S((a + b)**2 * (a + b + 1))
assert median(B) == FiniteSet(1 - 1/sqrt(2))
def test_beta_noncentral():
a, b = symbols('a b', positive=True)
c = Symbol('c', nonnegative=True)
_k = Dummy('k')
X = BetaNoncentral('x', a, b, c)
assert pspace(X).domain.set == Interval(0, 1)
dens = density(X)
z = Symbol('z')
res = Sum( z**(_k + a - 1)*(c/2)**_k*(1 - z)**(b - 1)*exp(-c/2)/
(beta(_k + a, b)*factorial(_k)), (_k, 0, oo))
assert dens(z).dummy_eq(res)
# BetaCentral should not raise if the assumptions
# on the symbols can not be determined
a, b, c = symbols('a b c')
assert BetaNoncentral('x', a, b, c)
a = Symbol('a', positive=False, real=True)
raises(ValueError, lambda: BetaNoncentral('x', a, b, c))
a = Symbol('a', positive=True)
b = Symbol('b', positive=False, real=True)
raises(ValueError, lambda: BetaNoncentral('x', a, b, c))
a = Symbol('a', positive=True)
b = Symbol('b', positive=True)
c = Symbol('c', nonnegative=False, real=True)
raises(ValueError, lambda: BetaNoncentral('x', a, b, c))
def test_betaprime():
alpha = Symbol("alpha", positive=True)
betap = Symbol("beta", positive=True)
X = BetaPrime('x', alpha, betap)
assert density(X)(x) == x**(alpha - 1)*(x + 1)**(-alpha - betap)/beta(alpha, betap)
alpha = Symbol("alpha", nonpositive=True)
raises(ValueError, lambda: BetaPrime('x', alpha, betap))
alpha = Symbol("alpha", positive=True)
betap = Symbol("beta", nonpositive=True)
raises(ValueError, lambda: BetaPrime('x', alpha, betap))
X = BetaPrime('x', 1, 1)
assert median(X) == FiniteSet(1)
def test_BoundedPareto():
L, H = symbols('L, H', negative=True)
raises(ValueError, lambda: BoundedPareto('X', 1, L, H))
L, H = symbols('L, H', real=False)
raises(ValueError, lambda: BoundedPareto('X', 1, L, H))
L, H = symbols('L, H', positive=True)
raises(ValueError, lambda: BoundedPareto('X', -1, L, H))
X = BoundedPareto('X', 2, L, H)
assert X.pspace.domain.set == Interval(L, H)
assert density(X)(x) == 2*L**2/(x**3*(1 - L**2/H**2))
assert cdf(X)(x) == Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) \
+ H**2/(H**2 - L**2), L <= x), (0, True))
assert E(X).simplify() == 2*H*L/(H + L)
X = BoundedPareto('X', 1, 2, 4)
assert E(X).simplify() == log(16)
assert median(X) == FiniteSet(Rational(8, 3))
assert variance(X).simplify() == 8 - 16*log(2)**2
def test_cauchy():
x0 = Symbol("x0", real=True)
gamma = Symbol("gamma", positive=True)
p = Symbol("p", positive=True)
X = Cauchy('x', x0, gamma)
# Tests the characteristic function
assert characteristic_function(X)(x) == exp(-gamma*Abs(x) + I*x*x0)
raises(NotImplementedError, lambda: moment_generating_function(X))
assert density(X)(x) == 1/(pi*gamma*(1 + (x - x0)**2/gamma**2))
assert diff(cdf(X)(x), x) == density(X)(x)
assert quantile(X)(p) == gamma*tan(pi*(p - S.Half)) + x0
x1 = Symbol("x1", real=False)
raises(ValueError, lambda: Cauchy('x', x1, gamma))
gamma = Symbol("gamma", nonpositive=True)
raises(ValueError, lambda: Cauchy('x', x0, gamma))
assert median(X) == FiniteSet(x0)
def test_chi():
from sympy import I
k = Symbol("k", integer=True)
X = Chi('x', k)
assert density(X)(x) == 2**(-k/2 + 1)*x**(k - 1)*exp(-x**2/2)/gamma(k/2)
# Tests the characteristic function
assert characteristic_function(X)(x) == sqrt(2)*I*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,),
(S(3)/2,), -x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), -x**2/2)
# Tests the moment generating function
assert moment_generating_function(X)(x) == sqrt(2)*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,),
(S(3)/2,), x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), x**2/2)
k = Symbol("k", integer=True, positive=False)
raises(ValueError, lambda: Chi('x', k))
k = Symbol("k", integer=False, positive=True)
raises(ValueError, lambda: Chi('x', k))
def test_chi_noncentral():
k = Symbol("k", integer=True)
l = Symbol("l")
X = ChiNoncentral("x", k, l)
assert density(X)(x) == (x**k*l*(x*l)**(-k/2)*
exp(-x**2/2 - l**2/2)*besseli(k/2 - 1, x*l))
k = Symbol("k", integer=True, positive=False)
raises(ValueError, lambda: ChiNoncentral('x', k, l))
k = Symbol("k", integer=True, positive=True)
l = Symbol("l", nonpositive=True)
raises(ValueError, lambda: ChiNoncentral('x', k, l))
k = Symbol("k", integer=False)
l = Symbol("l", positive=True)
raises(ValueError, lambda: ChiNoncentral('x', k, l))
def test_chi_squared():
k = Symbol("k", integer=True)
X = ChiSquared('x', k)
# Tests the characteristic function
assert characteristic_function(X)(x) == ((-2*I*x + 1)**(-k/2))
assert density(X)(x) == 2**(-k/2)*x**(k/2 - 1)*exp(-x/2)/gamma(k/2)
assert cdf(X)(x) == Piecewise((lowergamma(k/2, x/2)/gamma(k/2), x >= 0), (0, True))
assert E(X) == k
assert variance(X) == 2*k
X = ChiSquared('x', 15)
assert cdf(X)(3) == -14873*sqrt(6)*exp(Rational(-3, 2))/(5005*sqrt(pi)) + erf(sqrt(6)/2)
k = Symbol("k", integer=True, positive=False)
raises(ValueError, lambda: ChiSquared('x', k))
k = Symbol("k", integer=False, positive=True)
raises(ValueError, lambda: ChiSquared('x', k))
def test_dagum():
p = Symbol("p", positive=True)
b = Symbol("b", positive=True)
a = Symbol("a", positive=True)
X = Dagum('x', p, a, b)
assert density(X)(x) == a*p*(x/b)**(a*p)*((x/b)**a + 1)**(-p - 1)/x
assert cdf(X)(x) == Piecewise(((1 + (x/b)**(-a))**(-p), x >= 0),
(0, True))
p = Symbol("p", nonpositive=True)
raises(ValueError, lambda: Dagum('x', p, a, b))
p = Symbol("p", positive=True)
b = Symbol("b", nonpositive=True)
raises(ValueError, lambda: Dagum('x', p, a, b))
b = Symbol("b", positive=True)
a = Symbol("a", nonpositive=True)
raises(ValueError, lambda: Dagum('x', p, a, b))
X = Dagum('x', 1 , 1, 1)
assert median(X) == FiniteSet(1)
def test_erlang():
k = Symbol("k", integer=True, positive=True)
l = Symbol("l", positive=True)
X = Erlang("x", k, l)
assert density(X)(x) == x**(k - 1)*l**k*exp(-x*l)/gamma(k)
assert cdf(X)(x) == Piecewise((lowergamma(k, l*x)/gamma(k), x > 0),
(0, True))
def test_exgaussian():
m, z = symbols("m, z")
s, l = symbols("s, l", positive=True)
X = ExGaussian("x", m, s, l)
assert density(X)(z) == l*exp(l*(l*s**2 + 2*m - 2*z)/2) *\
erfc(sqrt(2)*(l*s**2 + m - z)/(2*s))/2
# Note: actual_output simplifies to expected_output.
# Ideally cdf(X)(z) would return expected_output
# expected_output = (erf(sqrt(2)*(l*s**2 + m - z)/(2*s)) - 1)*exp(l*(l*s**2 + 2*m - 2*z)/2)/2 - erf(sqrt(2)*(m - z)/(2*s))/2 + S.Half
u = l*(z - m)
v = l*s
GaussianCDF1 = cdf(Normal('x', 0, v))(u)
GaussianCDF2 = cdf(Normal('x', v**2, v))(u)
actual_output = GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2))
assert cdf(X)(z) == actual_output
# assert simplify(actual_output) == expected_output
assert variance(X).expand() == s**2 + l**(-2)
assert skewness(X).expand() == 2/(l**3*s**2*sqrt(s**2 + l**(-2)) + l *
sqrt(s**2 + l**(-2)))
def test_exponential():
rate = Symbol('lambda', positive=True)
X = Exponential('x', rate)
p = Symbol("p", positive=True, real=True, finite=True)
assert E(X) == 1/rate
assert variance(X) == 1/rate**2
assert skewness(X) == 2
assert skewness(X) == smoment(X, 3)
assert kurtosis(X) == 9
assert kurtosis(X) == smoment(X, 4)
assert smoment(2*X, 4) == smoment(X, 4)
assert moment(X, 3) == 3*2*1/rate**3
assert P(X > 0) is S.One
assert P(X > 1) == exp(-rate)
assert P(X > 10) == exp(-10*rate)
assert quantile(X)(p) == -log(1-p)/rate
assert where(X <= 1).set == Interval(0, 1)
Y = Exponential('y', 1)
assert median(Y) == FiniteSet(log(2))
#Test issue 9970
z = Dummy('z')
assert P(X > z) == exp(-z*rate)
assert P(X < z) == 0
#Test issue 10076 (Distribution with interval(0,oo))
x = Symbol('x')
_z = Dummy('_z')
b = SingleContinuousPSpace(x, ExponentialDistribution(2))
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
expected1 = Integral(2*exp(-2*_z), (_z, 3, oo))
assert b.probability(x > 3, evaluate=False).rewrite(Integral).dummy_eq(expected1)
expected2 = Integral(2*exp(-2*_z), (_z, 0, 4))
assert b.probability(x < 4, evaluate=False).rewrite(Integral).dummy_eq(expected2)
Y = Exponential('y', 2*rate)
assert coskewness(X, X, X) == skewness(X)
assert coskewness(X, Y + rate*X, Y + 2*rate*X) == \
4/(sqrt(1 + 1/(4*rate**2))*sqrt(4 + 1/(4*rate**2)))
assert coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) == \
sqrt(170)*Rational(9, 85)
def test_exponential_power():
mu = Symbol('mu')
z = Symbol('z')
alpha = Symbol('alpha', positive=True)
beta = Symbol('beta', positive=True)
X = ExponentialPower('x', mu, alpha, beta)
assert density(X)(z) == beta*exp(-(Abs(mu - z)/alpha)
** beta)/(2*alpha*gamma(1/beta))
assert cdf(X)(z) == S.Half + lowergamma(1/beta,
(Abs(mu - z)/alpha)**beta)*sign(-mu + z)/\
(2*gamma(1/beta))
def test_f_distribution():
d1 = Symbol("d1", positive=True)
d2 = Symbol("d2", positive=True)
X = FDistribution("x", d1, d2)
assert density(X)(x) == (d2**(d2/2)*sqrt((d1*x)**d1*(d1*x + d2)**(-d1 - d2))
/(x*beta(d1/2, d2/2)))
raises(NotImplementedError, lambda: moment_generating_function(X))
d1 = Symbol("d1", nonpositive=True)
raises(ValueError, lambda: FDistribution('x', d1, d1))
d1 = Symbol("d1", positive=True, integer=False)
raises(ValueError, lambda: FDistribution('x', d1, d1))
d1 = Symbol("d1", positive=True)
d2 = Symbol("d2", nonpositive=True)
raises(ValueError, lambda: FDistribution('x', d1, d2))
d2 = Symbol("d2", positive=True, integer=False)
raises(ValueError, lambda: FDistribution('x', d1, d2))
def test_fisher_z():
d1 = Symbol("d1", positive=True)
d2 = Symbol("d2", positive=True)
X = FisherZ("x", d1, d2)
assert density(X)(x) == (2*d1**(d1/2)*d2**(d2/2)*(d1*exp(2*x) + d2)
**(-d1/2 - d2/2)*exp(d1*x)/beta(d1/2, d2/2))
def test_frechet():
a = Symbol("a", positive=True)
s = Symbol("s", positive=True)
m = Symbol("m", real=True)
X = Frechet("x", a, s=s, m=m)
assert density(X)(x) == a*((x - m)/s)**(-a - 1)*exp(-((x - m)/s)**(-a))/s
assert cdf(X)(x) == Piecewise((exp(-((-m + x)/s)**(-a)), m <= x), (0, True))
@slow
def test_gamma():
k = Symbol("k", positive=True)
theta = Symbol("theta", positive=True)
X = Gamma('x', k, theta)
# Tests characteristic function
assert characteristic_function(X)(x) == ((-I*theta*x + 1)**(-k))
assert density(X)(x) == x**(k - 1)*theta**(-k)*exp(-x/theta)/gamma(k)
assert cdf(X, meijerg=True)(z) == Piecewise(
(-k*lowergamma(k, 0)/gamma(k + 1) +
k*lowergamma(k, z/theta)/gamma(k + 1), z >= 0),
(0, True))
# assert simplify(variance(X)) == k*theta**2 # handled numerically below
assert E(X) == moment(X, 1)
k, theta = symbols('k theta', positive=True)
X = Gamma('x', k, theta)
assert E(X) == k*theta
assert variance(X) == k*theta**2
assert skewness(X).expand() == 2/sqrt(k)
assert kurtosis(X).expand() == 3 + 6/k
Y = Gamma('y', 2*k, 3*theta)
assert coskewness(X, theta*X + Y, k*X + Y).simplify() == \
2*531441**(-k)*sqrt(k)*theta*(3*3**(12*k) - 2*531441**k) \
/(sqrt(k**2 + 18)*sqrt(theta**2 + 18))
def test_gamma_inverse():
a = Symbol("a", positive=True)
b = Symbol("b", positive=True)
X = GammaInverse("x", a, b)
assert density(X)(x) == x**(-a - 1)*b**a*exp(-b/x)/gamma(a)
assert cdf(X)(x) == Piecewise((uppergamma(a, b/x)/gamma(a), x > 0), (0, True))
assert characteristic_function(X)(x) == 2 * (-I*b*x)**(a/2) \
* besselk(a, 2*sqrt(b)*sqrt(-I*x))/gamma(a)
raises(NotImplementedError, lambda: moment_generating_function(X))
def test_sampling_gamma_inverse():
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for sampling of gamma inverse.')
X = GammaInverse("x", 1, 1)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in X.pspace.domain.set
def test_gompertz():
b = Symbol("b", positive=True)
eta = Symbol("eta", positive=True)
X = Gompertz("x", b, eta)
assert density(X)(x) == b*eta*exp(eta)*exp(b*x)*exp(-eta*exp(b*x))
assert cdf(X)(x) == 1 - exp(eta)*exp(-eta*exp(b*x))
assert diff(cdf(X)(x), x) == density(X)(x)
def test_gumbel():
beta = Symbol("beta", positive=True)
mu = Symbol("mu")
x = Symbol("x")
y = Symbol("y")
X = Gumbel("x", beta, mu)
Y = Gumbel("y", beta, mu, minimum=True)
assert density(X)(x).expand() == \
exp(mu/beta)*exp(-x/beta)*exp(-exp(mu/beta)*exp(-x/beta))/beta
assert density(Y)(y).expand() == \
exp(-mu/beta)*exp(y/beta)*exp(-exp(-mu/beta)*exp(y/beta))/beta
assert cdf(X)(x).expand() == \
exp(-exp(mu/beta)*exp(-x/beta))
assert characteristic_function(X)(x) == exp(I*mu*x)*gamma(-I*beta*x + 1)
def test_kumaraswamy():
a = Symbol("a", positive=True)
b = Symbol("b", positive=True)
X = Kumaraswamy("x", a, b)
assert density(X)(x) == x**(a - 1)*a*b*(-x**a + 1)**(b - 1)
assert cdf(X)(x) == Piecewise((0, x < 0),
(-(-x**a + 1)**b + 1, x <= 1),
(1, True))
def test_laplace():
mu = Symbol("mu")
b = Symbol("b", positive=True)
X = Laplace('x', mu, b)
#Tests characteristic_function
assert characteristic_function(X)(x) == (exp(I*mu*x)/(b**2*x**2 + 1))
assert density(X)(x) == exp(-Abs(x - mu)/b)/(2*b)
assert cdf(X)(x) == Piecewise((exp((-mu + x)/b)/2, mu > x),
(-exp((mu - x)/b)/2 + 1, True))
X = Laplace('x', [1, 2], [[1, 0], [0, 1]])
assert isinstance(pspace(X).distribution, MultivariateLaplaceDistribution)
def test_levy():
mu = Symbol("mu", real=True)
c = Symbol("c", positive=True)
X = Levy('x', mu, c)
assert X.pspace.domain.set == Interval(mu, oo)
assert density(X)(x) == sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half))
assert cdf(X)(x) == erfc(sqrt(c/(2*(x - mu))))
raises(NotImplementedError, lambda: moment_generating_function(X))
mu = Symbol("mu", real=False)
raises(ValueError, lambda: Levy('x',mu,c))
c = Symbol("c", nonpositive=True)
raises(ValueError, lambda: Levy('x',mu,c))
mu = Symbol("mu", real=True)
raises(ValueError, lambda: Levy('x',mu,c))
def test_logistic():
mu = Symbol("mu", real=True)
s = Symbol("s", positive=True)
p = Symbol("p", positive=True)
X = Logistic('x', mu, s)
#Tests characteristics_function
assert characteristic_function(X)(x) == \
(Piecewise((pi*s*x*exp(I*mu*x)/sinh(pi*s*x), Ne(x, 0)), (1, True)))
assert density(X)(x) == exp((-x + mu)/s)/(s*(exp((-x + mu)/s) + 1)**2)
assert cdf(X)(x) == 1/(exp((mu - x)/s) + 1)
assert quantile(X)(p) == mu - s*log(-S.One + 1/p)
def test_loglogistic():
a, b = symbols('a b')
assert LogLogistic('x', a, b)
a = Symbol('a', negative=True)
b = Symbol('b', positive=True)
raises(ValueError, lambda: LogLogistic('x', a, b))
a = Symbol('a', positive=True)
b = Symbol('b', negative=True)
raises(ValueError, lambda: LogLogistic('x', a, b))
a, b, z, p = symbols('a b z p', positive=True)
X = LogLogistic('x', a, b)
assert density(X)(z) == b*(z/a)**(b - 1)/(a*((z/a)**b + 1)**2)
assert cdf(X)(z) == 1/(1 + (z/a)**(-b))
assert quantile(X)(p) == a*(p/(1 - p))**(1/b)
# Expectation
assert E(X) == Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True))
b = symbols('b', prime=True) # b > 1
X = LogLogistic('x', a, b)
assert E(X) == pi*a/(b*sin(pi/b))
X = LogLogistic('x', 1, 2)
assert median(X) == FiniteSet(1)
def test_logitnormal():
mu = Symbol('mu', real=True)
s = Symbol('s', positive=True)
X = LogitNormal('x', mu, s)
x = Symbol('x')
assert density(X)(x) == sqrt(2)*exp(-(-mu + log(x/(1 - x)))**2/(2*s**2))/(2*sqrt(pi)*s*x*(1 - x))
assert cdf(X)(x) == erf(sqrt(2)*(-mu + log(x/(1 - x)))/(2*s))/2 + S(1)/2
def test_lognormal():
mean = Symbol('mu', real=True)
std = Symbol('sigma', positive=True)
X = LogNormal('x', mean, std)
# The sympy integrator can't do this too well
#assert E(X) == exp(mean+std**2/2)
#assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2)
# Right now, only density function and sampling works
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for i in range(3):
X = LogNormal('x', i, 1)
assert next(sample(X)) in X.pspace.domain.set
size = 5
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
samps = next(sample(X, size=size))
for samp in samps:
assert samp in X.pspace.domain.set
# The sympy integrator can't do this too well
#assert E(X) ==
raises(NotImplementedError, lambda: moment_generating_function(X))
mu = Symbol("mu", real=True)
sigma = Symbol("sigma", positive=True)
X = LogNormal('x', mu, sigma)
assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2
/(2*sigma**2))/(2*x*sqrt(pi)*sigma))
# Tests cdf
assert cdf(X)(x) == Piecewise(
(erf(sqrt(2)*(-mu + log(x))/(2*sigma))/2
+ S(1)/2, x > 0), (0, True))
X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1
assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi))
def test_Lomax():
a, l = symbols('a, l', negative=True)
raises(ValueError, lambda: Lomax('X', a , l))
a, l = symbols('a, l', real=False)
raises(ValueError, lambda: Lomax('X', a , l))
a, l = symbols('a, l', positive=True)
X = Lomax('X', a, l)
assert X.pspace.domain.set == Interval(0, oo)
assert density(X)(x) == a*(1 + x/l)**(-a - 1)/l
assert cdf(X)(x) == Piecewise((1 - (1 + x/l)**(-a), x >= 0), (0, True))
a = 3
X = Lomax('X', a, l)
assert E(X) == l/2
assert median(X) == FiniteSet(l*(-1 + 2**Rational(1, 3)))
assert variance(X) == 3*l**2/4
def test_maxwell():
a = Symbol("a", positive=True)
X = Maxwell('x', a)
assert density(X)(x) == (sqrt(2)*x**2*exp(-x**2/(2*a**2))/
(sqrt(pi)*a**3))
assert E(X) == 2*sqrt(2)*a/sqrt(pi)
assert variance(X) == -8*a**2/pi + 3*a**2
assert cdf(X)(x) == erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a)
assert diff(cdf(X)(x), x) == density(X)(x)
def test_Moyal():
mu = Symbol('mu',real=False)
sigma = Symbol('sigma', real=True, positive=True)
raises(ValueError, lambda: Moyal('M',mu, sigma))
mu = Symbol('mu', real=True)
sigma = Symbol('sigma', real=True, negative=True)
raises(ValueError, lambda: Moyal('M',mu, sigma))
sigma = Symbol('sigma', real=True, positive=True)
M = Moyal('M', mu, sigma)
assert density(M)(z) == sqrt(2)*exp(-exp((mu - z)/sigma)/2
- (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma)
assert cdf(M)(z).simplify() == 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2)
assert characteristic_function(M)(z) == 2**(-I*sigma*z)*exp(I*mu*z) \
*gamma(-I*sigma*z + Rational(1, 2))/sqrt(pi)
assert E(M) == mu + EulerGamma*sigma + sigma*log(2)
assert moment_generating_function(M)(z) == 2**(-sigma*z)*exp(mu*z) \
*gamma(-sigma*z + Rational(1, 2))/sqrt(pi)
def test_nakagami():
mu = Symbol("mu", positive=True)
omega = Symbol("omega", positive=True)
X = Nakagami('x', mu, omega)
assert density(X)(x) == (2*x**(2*mu - 1)*mu**mu*omega**(-mu)
*exp(-x**2*mu/omega)/gamma(mu))
assert simplify(E(X)) == (sqrt(mu)*sqrt(omega)
*gamma(mu + S.Half)/gamma(mu + 1))
assert simplify(variance(X)) == (
omega - omega*gamma(mu + S.Half)**2/(gamma(mu)*gamma(mu + 1)))
assert cdf(X)(x) == Piecewise(
(lowergamma(mu, mu*x**2/omega)/gamma(mu), x > 0),
(0, True))
X = Nakagami('x',1 ,1)
assert median(X) == FiniteSet(sqrt(log(2)))
def test_gaussian_inverse():
# test for symbolic parameters
a, b = symbols('a b')
assert GaussianInverse('x', a, b)
# Inverse Gaussian distribution is also known as Wald distribution
# `GaussianInverse` can also be referred by the name `Wald`
a, b, z = symbols('a b z')
X = Wald('x', a, b)
assert density(X)(z) == sqrt(2)*sqrt(b/z**3)*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi))
a, b = symbols('a b', positive=True)
z = Symbol('z', positive=True)
X = GaussianInverse('x', a, b)
assert density(X)(z) == sqrt(2)*sqrt(b)*sqrt(z**(-3))*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi))
assert E(X) == a
assert variance(X).expand() == a**3/b
assert cdf(X)(z) == (S.Half - erf(sqrt(2)*sqrt(b)*(1 + z/a)/(2*sqrt(z)))/2)*exp(2*b/a) +\
erf(sqrt(2)*sqrt(b)*(-1 + z/a)/(2*sqrt(z)))/2 + S.Half
a = symbols('a', nonpositive=True)
raises(ValueError, lambda: GaussianInverse('x', a, b))
a = symbols('a', positive=True)
b = symbols('b', nonpositive=True)
raises(ValueError, lambda: GaussianInverse('x', a, b))
def test_sampling_gaussian_inverse():
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for sampling of Gaussian inverse.')
X = GaussianInverse("x", 1, 1)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X, library='scipy')) in X.pspace.domain.set
def test_pareto():
xm, beta = symbols('xm beta', positive=True)
alpha = beta + 5
X = Pareto('x', xm, alpha)
dens = density(X)
#Tests cdf function
assert cdf(X)(x) == \
Piecewise((-x**(-beta - 5)*xm**(beta + 5) + 1, x >= xm), (0, True))
#Tests characteristic_function
assert characteristic_function(X)(x) == \
((-I*x*xm)**(beta + 5)*(beta + 5)*uppergamma(-beta - 5, -I*x*xm))
assert dens(x) == x**(-(alpha + 1))*xm**(alpha)*(alpha)
assert simplify(E(X)) == alpha*xm/(alpha-1)
# computation of taylor series for MGF still too slow
#assert simplify(variance(X)) == xm**2*alpha / ((alpha-1)**2*(alpha-2))
def test_pareto_numeric():
xm, beta = 3, 2
alpha = beta + 5
X = Pareto('x', xm, alpha)
assert E(X) == alpha*xm/S(alpha - 1)
assert variance(X) == xm**2*alpha / S((alpha - 1)**2*(alpha - 2))
assert median(X) == FiniteSet(3*2**Rational(1, 7))
# Skewness tests too slow. Try shortcutting function?
def test_PowerFunction():
alpha = Symbol("alpha", nonpositive=True)
a, b = symbols('a, b', real=True)
raises (ValueError, lambda: PowerFunction('x', alpha, a, b))
a, b = symbols('a, b', real=False)
raises (ValueError, lambda: PowerFunction('x', alpha, a, b))
alpha = Symbol("alpha", positive=True)
a, b = symbols('a, b', real=True)
raises (ValueError, lambda: PowerFunction('x', alpha, 5, 2))
X = PowerFunction('X', 2, a, b)
assert density(X)(z) == (-2*a + 2*z)/(-a + b)**2
assert cdf(X)(z) == Piecewise((a**2/(a**2 - 2*a*b + b**2) -
2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True))
X = PowerFunction('X', 2, 0, 1)
assert density(X)(z) == 2*z
assert cdf(X)(z) == Piecewise((z**2, z >= 0), (0,True))
assert E(X) == Rational(2,3)
assert P(X < 0) == 0
assert P(X < 1) == 1
assert median(X) == FiniteSet(1/sqrt(2))
def test_raised_cosine():
mu = Symbol("mu", real=True)
s = Symbol("s", positive=True)
X = RaisedCosine("x", mu, s)
assert pspace(X).domain.set == Interval(mu - s, mu + s)
#Tests characteristics_function
assert characteristic_function(X)(x) == \
Piecewise((exp(-I*pi*mu/s)/2, Eq(x, -pi/s)), (exp(I*pi*mu/s)/2, Eq(x, pi/s)), (pi**2*exp(I*mu*x)*sin(s*x)/(s*x*(-s**2*x**2 + pi**2)), True))
assert density(X)(x) == (Piecewise(((cos(pi*(x - mu)/s) + 1)/(2*s),
And(x <= mu + s, mu - s <= x)), (0, True)))
def test_rayleigh():
sigma = Symbol("sigma", positive=True)
X = Rayleigh('x', sigma)
#Tests characteristic_function
assert characteristic_function(X)(x) == (-sqrt(2)*sqrt(pi)*sigma*x*(erfi(sqrt(2)*sigma*x/2) - I)*exp(-sigma**2*x**2/2)/2 + 1)
assert density(X)(x) == x*exp(-x**2/(2*sigma**2))/sigma**2
assert E(X) == sqrt(2)*sqrt(pi)*sigma/2
assert variance(X) == -pi*sigma**2/2 + 2*sigma**2
assert cdf(X)(x) == 1 - exp(-x**2/(2*sigma**2))
assert diff(cdf(X)(x), x) == density(X)(x)
def test_reciprocal():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
X = Reciprocal('x', a, b)
assert density(X)(x) == 1/(x*(-log(a) + log(b)))
assert cdf(X)(x) == Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True))
X = Reciprocal('x', 5, 30)
assert E(X) == 25/(log(30) - log(5))
assert P(X < 4) == S.Zero
assert P(X < 20) == log(20) / (log(30) - log(5)) - log(5) / (log(30) - log(5))
assert cdf(X)(10) == log(10) / (log(30) - log(5)) - log(5) / (log(30) - log(5))
a = symbols('a', nonpositive=True)
raises(ValueError, lambda: Reciprocal('x', a, b))
a = symbols('a', positive=True)
b = symbols('b', positive=True)
raises(ValueError, lambda: Reciprocal('x', a + b, a))
def test_shiftedgompertz():
b = Symbol("b", positive=True)
eta = Symbol("eta", positive=True)
X = ShiftedGompertz("x", b, eta)
assert density(X)(x) == b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x))
def test_studentt():
nu = Symbol("nu", positive=True)
X = StudentT('x', nu)
assert density(X)(x) == (1 + x**2/nu)**(-nu/2 - S.Half)/(sqrt(nu)*beta(S.Half, nu/2))
assert cdf(X)(x) == S.Half + x*gamma(nu/2 + S.Half)*hyper((S.Half, nu/2 + S.Half),
(Rational(3, 2),), -x**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2))
raises(NotImplementedError, lambda: moment_generating_function(X))
def test_trapezoidal():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
c = Symbol("c", real=True)
d = Symbol("d", real=True)
X = Trapezoidal('x', a, b, c, d)
assert density(X)(x) == Piecewise(((-2*a + 2*x)/((-a + b)*(-a - b + c + d)), (a <= x) & (x < b)),
(2/(-a - b + c + d), (b <= x) & (x < c)),
((2*d - 2*x)/((-c + d)*(-a - b + c + d)), (c <= x) & (x <= d)),
(0, True))
X = Trapezoidal('x', 0, 1, 2, 3)
assert E(X) == Rational(3, 2)
assert variance(X) == Rational(5, 12)
assert P(X < 2) == Rational(3, 4)
assert median(X) == FiniteSet(Rational(3, 2))
def test_triangular():
a = Symbol("a")
b = Symbol("b")
c = Symbol("c")
X = Triangular('x', a, b, c)
assert pspace(X).domain.set == Interval(a, b)
assert str(density(X)(x)) == ("Piecewise(((-2*a + 2*x)/((-a + b)*(-a + c)), (a <= x) & (c > x)), "
"(2/(-a + b), Eq(c, x)), ((2*b - 2*x)/((-a + b)*(b - c)), (b >= x) & (c < x)), (0, True))")
#Tests moment_generating_function
assert moment_generating_function(X)(x).expand() == \
((-2*(-a + b)*exp(c*x) + 2*(-a + c)*exp(b*x) + 2*(b - c)*exp(a*x))/(x**2*(-a + b)*(-a + c)*(b - c))).expand()
assert str(characteristic_function(X)(x)) == \
'(2*(-a + b)*exp(I*c*x) - 2*(-a + c)*exp(I*b*x) - 2*(b - c)*exp(I*a*x))/(x**2*(-a + b)*(-a + c)*(b - c))'
def test_quadratic_u():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
X = QuadraticU("x", a, b)
Y = QuadraticU("x", 1, 2)
assert pspace(X).domain.set == Interval(a, b)
# Tests _moment_generating_function
assert moment_generating_function(Y)(1) == -15*exp(2) + 27*exp(1)
assert moment_generating_function(Y)(2) == -9*exp(4)/2 + 21*exp(2)/2
assert characteristic_function(Y)(1) == 3*I*(-1 + 4*I)*exp(I*exp(2*I))
assert density(X)(x) == (Piecewise((12*(x - a/2 - b/2)**2/(-a + b)**3,
And(x <= b, a <= x)), (0, True)))
def test_uniform():
l = Symbol('l', real=True)
w = Symbol('w', positive=True)
X = Uniform('x', l, l + w)
assert E(X) == l + w/2
assert variance(X).expand() == w**2/12
# With numbers all is well
X = Uniform('x', 3, 5)
assert P(X < 3) == 0 and P(X > 5) == 0
assert P(X < 4) == P(X > 4) == S.Half
assert median(X) == FiniteSet(4)
z = Symbol('z')
p = density(X)(z)
assert p.subs(z, 3.7) == S.Half
assert p.subs(z, -1) == 0
assert p.subs(z, 6) == 0
c = cdf(X)
assert c(2) == 0 and c(3) == 0
assert c(Rational(7, 2)) == Rational(1, 4)
assert c(5) == 1 and c(6) == 1
@XFAIL
def test_uniform_P():
""" This stopped working because SingleContinuousPSpace.compute_density no
longer calls integrate on a DiracDelta but rather just solves directly.
integrate used to call UniformDistribution.expectation which special-cased
subsed out the Min and Max terms that Uniform produces
I decided to regress on this class for general cleanliness (and I suspect
speed) of the algorithm.
"""
l = Symbol('l', real=True)
w = Symbol('w', positive=True)
X = Uniform('x', l, l + w)
assert P(X < l) == 0 and P(X > l + w) == 0
def test_uniformsum():
n = Symbol("n", integer=True)
_k = Dummy("k")
x = Symbol("x")
X = UniformSum('x', n)
res = Sum((-1)**_k*(-_k + x)**(n - 1)*binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1)
assert density(X)(x).dummy_eq(res)
#Tests set functions
assert X.pspace.domain.set == Interval(0, n)
#Tests the characteristic_function
assert characteristic_function(X)(x) == (-I*(exp(I*x) - 1)/x)**n
#Tests the moment_generating_function
assert moment_generating_function(X)(x) == ((exp(x) - 1)/x)**n
def test_von_mises():
mu = Symbol("mu")
k = Symbol("k", positive=True)
X = VonMises("x", mu, k)
assert density(X)(x) == exp(k*cos(x - mu))/(2*pi*besseli(0, k))
def test_weibull():
a, b = symbols('a b', positive=True)
# FIXME: simplify(E(X)) seems to hang without extended_positive=True
# On a Linux machine this had a rapid memory leak...
# a, b = symbols('a b', positive=True)
X = Weibull('x', a, b)
assert E(X).expand() == a * gamma(1 + 1/b)
assert variance(X).expand() == (a**2 * gamma(1 + 2/b) - E(X)**2).expand()
assert simplify(skewness(X)) == (2*gamma(1 + 1/b)**3 - 3*gamma(1 + 1/b)*gamma(1 + 2/b) + gamma(1 + 3/b))/(-gamma(1 + 1/b)**2 + gamma(1 + 2/b))**Rational(3, 2)
assert simplify(kurtosis(X)) == (-3*gamma(1 + 1/b)**4 +\
6*gamma(1 + 1/b)**2*gamma(1 + 2/b) - 4*gamma(1 + 1/b)*gamma(1 + 3/b) + gamma(1 + 4/b))/(gamma(1 + 1/b)**2 - gamma(1 + 2/b))**2
def test_weibull_numeric():
# Test for integers and rationals
a = 1
bvals = [S.Half, 1, Rational(3, 2), 5]
for b in bvals:
X = Weibull('x', a, b)
assert simplify(E(X)) == expand_func(a * gamma(1 + 1/S(b)))
assert simplify(variance(X)) == simplify(
a**2 * gamma(1 + 2/S(b)) - E(X)**2)
# Not testing Skew... it's slow with int/frac values > 3/2
def test_wignersemicircle():
R = Symbol("R", positive=True)
X = WignerSemicircle('x', R)
assert pspace(X).domain.set == Interval(-R, R)
assert density(X)(x) == 2*sqrt(-x**2 + R**2)/(pi*R**2)
assert E(X) == 0
#Tests ChiNoncentralDistribution
assert characteristic_function(X)(x) == \
Piecewise((2*besselj(1, R*x)/(R*x), Ne(x, 0)), (1, True))
def test_prefab_sampling():
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
N = Normal('X', 0, 1)
L = LogNormal('L', 0, 1)
E = Exponential('Ex', 1)
P = Pareto('P', 1, 3)
W = Weibull('W', 1, 1)
U = Uniform('U', 0, 1)
B = Beta('B', 2, 5)
G = Gamma('G', 1, 3)
variables = [N, L, E, P, W, U, B, G]
niter = 10
size = 5
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for var in variables:
for _ in range(niter):
assert next(sample(var)) in var.pspace.domain.set
samps = next(sample(var, size=size))
for samp in samps:
assert samp in var.pspace.domain.set
def test_input_value_assertions():
a, b = symbols('a b')
p, q = symbols('p q', positive=True)
m, n = symbols('m n', positive=False, real=True)
raises(ValueError, lambda: Normal('x', 3, 0))
raises(ValueError, lambda: Normal('x', m, n))
Normal('X', a, p) # No error raised
raises(ValueError, lambda: Exponential('x', m))
Exponential('Ex', p) # No error raised
for fn in [Pareto, Weibull, Beta, Gamma]:
raises(ValueError, lambda: fn('x', m, p))
raises(ValueError, lambda: fn('x', p, n))
fn('x', p, q) # No error raised
def test_unevaluated():
X = Normal('x', 0, 1)
k = Dummy('k')
expr1 = Integral(sqrt(2)*k*exp(-k**2/2)/(2*sqrt(pi)), (k, -oo, oo))
expr2 = Integral(sqrt(2)*exp(-k**2/2)/(2*sqrt(pi)), (k, 0, oo))
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert E(X, evaluate=False).rewrite(Integral).dummy_eq(expr1)
assert E(X + 1, evaluate=False).rewrite(Integral).dummy_eq(expr1 + 1)
assert P(X > 0, evaluate=False).rewrite(Integral).dummy_eq(expr2)
assert P(X > 0, X**2 < 1) == S.Half
def test_probability_unevaluated():
T = Normal('T', 30, 3)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert type(P(T > 33, evaluate=False)) == Probability
def test_density_unevaluated():
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 2)
assert isinstance(density(X+Y, evaluate=False)(z), Integral)
def test_NormalDistribution():
nd = NormalDistribution(0, 1)
x = Symbol('x')
assert nd.cdf(x) == erf(sqrt(2)*x/2)/2 + S.Half
assert nd.expectation(1, x) == 1
assert nd.expectation(x, x) == 0
assert nd.expectation(x**2, x) == 1
#Test issue 10076
a = SingleContinuousPSpace(x, NormalDistribution(2, 4))
_z = Dummy('_z')
expected1 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, -oo, 1))
assert a.probability(x < 1, evaluate=False).dummy_eq(expected1) is True
expected2 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, 1, oo))
assert a.probability(x > 1, evaluate=False).dummy_eq(expected2) is True
b = SingleContinuousPSpace(x, NormalDistribution(1, 9))
expected3 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, 6, oo))
assert b.probability(x > 6, evaluate=False).dummy_eq(expected3) is True
expected4 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, -oo, 6))
assert b.probability(x < 6, evaluate=False).dummy_eq(expected4) is True
def test_random_parameters():
mu = Normal('mu', 2, 3)
meas = Normal('T', mu, 1)
assert density(meas, evaluate=False)(z)
assert isinstance(pspace(meas), CompoundPSpace)
X = Normal('x', [1, 2], [[1, 0], [0, 1]])
assert isinstance(pspace(X).distribution, MultivariateNormalDistribution)
assert density(meas)(z).simplify() == sqrt(5)*exp(-z**2/20 + z/5 - S(1)/5)/(10*sqrt(pi))
def test_random_parameters_given():
mu = Normal('mu', 2, 3)
meas = Normal('T', mu, 1)
assert given(meas, Eq(mu, 5)) == Normal('T', 5, 1)
def test_conjugate_priors():
mu = Normal('mu', 2, 3)
x = Normal('x', mu, 1)
assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)),
Mul)
def test_difficult_univariate():
""" Since using solve in place of deltaintegrate we're able to perform
substantially more complex density computations on single continuous random
variables """
x = Normal('x', 0, 1)
assert density(x**3)
assert density(exp(x**2))
assert density(log(x))
def test_issue_10003():
X = Exponential('x', 3)
G = Gamma('g', 1, 2)
assert P(X < -1) is S.Zero
assert P(G < -1) is S.Zero
@slow
def test_precomputed_cdf():
x = symbols("x", real=True)
mu = symbols("mu", real=True)
sigma, xm, alpha = symbols("sigma xm alpha", positive=True)
n = symbols("n", integer=True, positive=True)
distribs = [
Normal("X", mu, sigma),
Pareto("P", xm, alpha),
ChiSquared("C", n),
Exponential("E", sigma),
# LogNormal("L", mu, sigma),
]
for X in distribs:
compdiff = cdf(X)(x) - simplify(X.pspace.density.compute_cdf()(x))
compdiff = simplify(compdiff.rewrite(erfc))
assert compdiff == 0
@slow
def test_precomputed_characteristic_functions():
import mpmath
def test_cf(dist, support_lower_limit, support_upper_limit):
pdf = density(dist)
t = Symbol('t')
# first function is the hardcoded CF of the distribution
cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath')
# second function is the Fourier transform of the density function
f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath')
cf2 = lambda t: mpmath.quad(lambda x: f(x, t), [support_lower_limit, support_upper_limit], maxdegree=10)
# compare the two functions at various points
for test_point in [2, 5, 8, 11]:
n1 = cf1(test_point)
n2 = cf2(test_point)
assert abs(re(n1) - re(n2)) < 1e-12
assert abs(im(n1) - im(n2)) < 1e-12
test_cf(Beta('b', 1, 2), 0, 1)
test_cf(Chi('c', 3), 0, mpmath.inf)
test_cf(ChiSquared('c', 2), 0, mpmath.inf)
test_cf(Exponential('e', 6), 0, mpmath.inf)
test_cf(Logistic('l', 1, 2), -mpmath.inf, mpmath.inf)
test_cf(Normal('n', -1, 5), -mpmath.inf, mpmath.inf)
test_cf(RaisedCosine('r', 3, 1), 2, 4)
test_cf(Rayleigh('r', 0.5), 0, mpmath.inf)
test_cf(Uniform('u', -1, 1), -1, 1)
test_cf(WignerSemicircle('w', 3), -3, 3)
def test_long_precomputed_cdf():
x = symbols("x", real=True)
distribs = [
Arcsin("A", -5, 9),
Dagum("D", 4, 10, 3),
Erlang("E", 14, 5),
Frechet("F", 2, 6, -3),
Gamma("G", 2, 7),
GammaInverse("GI", 3, 5),
Kumaraswamy("K", 6, 8),
Laplace("LA", -5, 4),
Logistic("L", -6, 7),
Nakagami("N", 2, 7),
StudentT("S", 4)
]
for distr in distribs:
for _ in range(5):
assert tn(diff(cdf(distr)(x), x), density(distr)(x), x, a=0, b=0, c=1, d=0)
US = UniformSum("US", 5)
pdf01 = density(US)(x).subs(floor(x), 0).doit() # pdf on (0, 1)
cdf01 = cdf(US, evaluate=False)(x).subs(floor(x), 0).doit() # cdf on (0, 1)
assert tn(diff(cdf01, x), pdf01, x, a=0, b=0, c=1, d=0)
def test_issue_13324():
X = Uniform('X', 0, 1)
assert E(X, X > S.Half) == Rational(3, 4)
assert E(X, X > 0) == S.Half
def test_FiniteSet_prob():
E = Exponential('E', 3)
N = Normal('N', 5, 7)
assert P(Eq(E, 1)) is S.Zero
assert P(Eq(N, 2)) is S.Zero
assert P(Eq(N, x)) is S.Zero
def test_prob_neq():
E = Exponential('E', 4)
X = ChiSquared('X', 4)
assert P(Ne(E, 2)) == 1
assert P(Ne(X, 4)) == 1
assert P(Ne(X, 4)) == 1
assert P(Ne(X, 5)) == 1
assert P(Ne(E, x)) == 1
def test_union():
N = Normal('N', 3, 2)
assert simplify(P(N**2 - N > 2)) == \
-erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2)
assert simplify(P(N**2 - 4 > 0)) == \
-erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2)
def test_Or():
N = Normal('N', 0, 1)
assert simplify(P(Or(N > 2, N < 1))) == \
-erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + Rational(3, 2)
assert P(Or(N < 0, N < 1)) == P(N < 1)
assert P(Or(N > 0, N < 0)) == 1
def test_conditional_eq():
E = Exponential('E', 1)
assert P(Eq(E, 1), Eq(E, 1)) == 1
assert P(Eq(E, 1), Eq(E, 2)) == 0
assert P(E > 1, Eq(E, 2)) == 1
assert P(E < 1, Eq(E, 2)) == 0
def test_ContinuousDistributionHandmade():
x = Symbol('x')
z = Dummy('z')
dens = Lambda(x, Piecewise((S.Half, (0<=x)&(x<1)), (0, (x>=1)&(x<2)),
(S.Half, (x>=2)&(x<3)), (0, True)))
dens = ContinuousDistributionHandmade(dens, set=Interval(0, 3))
space = SingleContinuousPSpace(z, dens)
assert dens.pdf == Lambda(x, Piecewise((1/2, (x >= 0) & (x < 1)),
(0, (x >= 1) & (x < 2)), (1/2, (x >= 2) & (x < 3)), (0, True)))
assert median(space.value) == Interval(1, 2)
assert E(space.value) == Rational(3, 2)
assert variance(space.value) == Rational(13, 12)
def test_sample_numpy():
distribs_numpy = [
Beta("B", 1, 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Chi("C", 1), library='numpy')))
raises(NotImplementedError,
lambda: Chi("C", 1).pspace.distribution.sample(library='tensorflow'))
def test_sample_scipy():
distribs_scipy = [
Beta("B", 1, 1),
BetaPrime("BP", 1, 1),
Cauchy("C", 1, 1),
Chi("C", 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
GammaInverse("GI", 1, 1),
GaussianInverse("GUI", 1, 1),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
StudentT("S", 2),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
g_sample = list(sample(Gamma("G", 2, 7), size=size, numsamples=numsamples))
assert len(g_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size, library='scipy'))
samps2 = next(sample(X, size=(2, 2), library='scipy'))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Beta("B", 1, 1),
Cauchy("C", 1, 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
GaussianInverse("GI", 1, 1),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Chi("C", 1), library='pymc3')))
def test_issue_16318():
#test compute_expectation function of the SingleContinuousDomain
N = SingleContinuousDomain(x, Interval(0, 1))
raises (ValueError, lambda: SingleContinuousDomain.compute_expectation(N, x+1, {x, y}))
|
b0fedf7357c767e6521103194bc91f6499911bf285cd5a1787878ff2074ecc51 | from sympy import sin, cos, exp, E, series, oo, S, Derivative, O, Integral, \
Function, PoleError, log, sqrt, N, Symbol, Subs, pi, symbols, atan, LambertW, Rational
from sympy.abc import x, y, n, k
from sympy.testing.pytest import raises
from sympy.series.gruntz import calculate_series
def test_sin():
e1 = sin(x).series(x, 0)
e2 = series(sin(x), x, 0)
assert e1 == e2
def test_cos():
e1 = cos(x).series(x, 0)
e2 = series(cos(x), x, 0)
assert e1 == e2
def test_exp():
e1 = exp(x).series(x, 0)
e2 = series(exp(x), x, 0)
assert e1 == e2
def test_exp2():
e1 = exp(cos(x)).series(x, 0)
e2 = series(exp(cos(x)), x, 0)
assert e1 == e2
def test_issue_5223():
assert series(1, x) == 1
assert next(S.Zero.lseries(x)) == 0
assert cos(x).series() == cos(x).series(x)
raises(ValueError, lambda: cos(x + y).series())
raises(ValueError, lambda: x.series(dir=""))
assert (cos(x).series(x, 1) -
cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0
e = cos(x).series(x, 1, n=None)
assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
e = cos(x).series(x, 1, n=None, dir='-')
assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)]
# the following test is exact so no need for x -> x - 1 replacement
assert abs(x).series(x, 1, dir='-') == x
assert exp(x).series(x, 1, dir='-', n=3).removeO() == \
E - E*(-x + 1) + E*(-x + 1)**2/2
D = Derivative
assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y
assert next(D(cos(x), x).lseries()) == D(1, x)
assert D(
exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3)
assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x
assert (1 + x + O(x**2)).getn() == 2
assert (1 + x).getn() is None
raises(PoleError, lambda: ((1/sin(x))**oo).series())
logx = Symbol('logx')
assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
exp(y*logx) + O(x*exp(y*logx), x)
assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo))
assert abs(x).series(x, oo, n=5, dir='+') == x
assert abs(x).series(x, -oo, n=5, dir='-') == -x
assert abs(-x).series(x, oo, n=5, dir='+') == x
assert abs(-x).series(x, -oo, n=5, dir='-') == -x
assert exp(x*log(x)).series(n=3) == \
1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3)
# XXX is this right? If not, fix "ngot > n" handling in expr.
p = Symbol('p', positive=True)
assert exp(sqrt(p)**3*log(p)).series(n=3) == \
1 + p**S('3/2')*log(p) + O(p**3*log(p)**3)
assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2)
def test_issue_11313():
assert Integral(cos(x), x).series(x) == sin(x).series(x)
assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3)
assert Derivative(x**3, x).as_leading_term(x) == 3*x**2
assert Derivative(x**3, y).as_leading_term(x) == 0
assert Derivative(sin(x), x).as_leading_term(x) == 1
assert Derivative(cos(x), x).as_leading_term(x) == -x
# This result is equivalent to zero, zero is not return because
# `Expr.series` doesn't currently detect an `x` in its `free_symbol`s.
assert Derivative(1, x).as_leading_term(x) == Derivative(1, x)
assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x)
assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x)
assert Derivative(log(x), x).series(x).doit() == (1/x).series(x)
assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO()
def test_series_of_Subs():
from sympy.abc import x, y, z
subs1 = Subs(sin(x), x, y)
subs2 = Subs(sin(x) * cos(z), x, y)
subs3 = Subs(sin(x * z), (x, z), (y, x))
assert subs1.series(x) == subs1
subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) +
Subs(x**5/120, x, y) + O(y**6))
assert subs1.series() == subs1_series
assert subs1.series(y) == subs1_series
assert subs1.series(z) == subs1
assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) +
Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6))
assert subs3.series(x).doit() == subs3.doit().series(x)
assert subs3.series(z).doit() == sin(x*y)
raises(ValueError, lambda: Subs(x + 2*y, y, z).series())
assert Subs(x + y, y, z).series(x).doit() == x + z
def test_issue_3978():
f = Function('f')
assert f(x).series(x, 0, 3, dir='-') == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x).series(x, 0, 3) == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x**2).series(x, 0, 3) == \
f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3)
assert f(x**2+1).series(x, 0, 3) == \
f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3)
class TestF(Function):
pass
assert TestF(x).series(x, 0, 3) == TestF(0) + \
x*Subs(Derivative(TestF(x), x), x, 0) + \
x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3)
from sympy.series.acceleration import richardson, shanks
from sympy import Sum, Integer
def test_acceleration():
e = (1 + 1/n)**n
assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10)
A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n))
assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4)
assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
def test_issue_5852():
assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \
5*x**4/(24*log(x)**4) + O(x**6)
def test_issue_4583():
assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \
x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \
x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5)
def test_issue_6318():
eq = (1/x)**Rational(2, 3)
assert (eq + 1).as_leading_term(x) == eq
def test_x_is_base_detection():
eq = (x**2)**Rational(2, 3)
assert eq.series() == x**Rational(4, 3)
def test_sin_power():
e = sin(x)**1.2
assert calculate_series(e, x) == x**1.2
def test_issue_7203():
assert series(cos(x), x, pi, 3) == \
-1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
def test_exp_product_positive_factors():
a, b = symbols('a, b', positive=True)
x = a * b
assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \
a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \
a**7*b**7/5040 + O(a**8*b**8, a, b)
def test_issue_8805():
assert series(1, n=8) == 1
def test_issue_9549():
y = (x**2 + x + 1) / (x**3 + x**2)
assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo))
def test_issue_10761():
assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6)
def test_issue_12578():
y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8)
assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \
3472*x**14 - 17318*x**16 + O(x**17)
def test_issue_12791():
beta = symbols('beta', real=True, positive=True)
theta, varphi = symbols('theta varphi', real=True)
expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \
beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2
sol = 0.5/(0.5*cos(theta) - 1)**2 - 0.25*cos(theta)/(0.5*cos(theta) - 1)**2 \
+ (beta - 0.5)*(-0.5*varphi*sin(theta)*cos(theta)/((0.5*cos(theta) - 1) \
**2*(0.5*cos(theta) - 1.0)) - 1/(0.5*cos(theta) - 1)**2 + 0.5*cos(theta) \
**2/((0.5*cos(theta) - 1)**2*(0.5*cos(theta) - 1.0)) - 1.0*cos(theta) \
/((0.5*cos(theta) - 1)**2*(0.5*cos(theta) - 1.0))) + 0.25*varphi* \
sin(theta)/(0.5*cos(theta) - 1)**2 + O((beta - 0.5)**2, (beta, 0.5))
assert expr.series(beta, 0.5, 2) == sol
def test_issue_14885():
assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) +
sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 +
x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6))
def test_issue_15539():
assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2
+ O(x**(-6), (x, -oo)))
assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2
+ O(x**(-6), (x, oo)))
def test_issue_7259():
assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6)
assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8)
assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4)
def test_issue_11884():
assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1))
def test_issue_18008():
y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x))
assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \
O(x**(-4), (x, oo))
def test_issue_18842():
f = log(x/(1 - x))
assert f.series(x, 0.491, n=1).removeO().nsimplify() == \
-S(180019443780011)/5000000000000000
def test_issue_19534():
dt = symbols('dt', real=True)
expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \
49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \
dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \
dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \
6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) - \
7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \
0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1
assert N(expr.series(dt, 0, 8), 20) == -0.00092592592592592596126*dt**7 + 0.0027777777777777783175*dt**6 + \
0.016666666666666656027*dt**5 + 0.083333333333333300952*dt**4 + 0.33333333333333337034*dt**3 + \
1.0*dt**2 + 1.0*dt + 1.0
def test_issue_11407():
a, b, c, x = symbols('a b c x')
assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x)
assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x)
def test_issue_14037():
assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x)
def test_issue_20551():
expr = (exp(x)/x).series(x, n=None)
terms = [ next(expr) for i in range(3) ]
assert terms == [1/x, 1, x/2]
|
d8dc9eae153b170363bc7b008ee88c4e935dcb5fe8fc28462596103d6e81c70d | from sympy import (Symbol, Rational, Order, exp, ln, log, nan, oo, O, pi, I,
S, Integral, sin, cos, sqrt, conjugate, expand, transpose, symbols,
Function, Add)
from sympy.core.expr import unchanged
from sympy.testing.pytest import raises
from sympy.abc import w, x, y, z
def test_caching_bug():
#needs to be a first test, so that all caches are clean
#cache it
O(w)
#and test that this won't raise an exception
O(w**(-1/x/log(3)*log(5)), w)
def test_free_symbols():
assert Order(1).free_symbols == set()
assert Order(x).free_symbols == {x}
assert Order(1, x).free_symbols == {x}
assert Order(x*y).free_symbols == {x, y}
assert Order(x, x, y).free_symbols == {x, y}
def test_simple_1():
o = Rational(0)
assert Order(2*x) == Order(x)
assert Order(x)*3 == Order(x)
assert -28*Order(x) == Order(x)
assert Order(Order(x)) == Order(x)
assert Order(Order(x), y) == Order(Order(x), x, y)
assert Order(-23) == Order(1)
assert Order(exp(x)) == Order(1, x)
assert Order(exp(1/x)).expr == exp(1/x)
assert Order(x*exp(1/x)).expr == x*exp(1/x)
assert Order(x**(o/3)).expr == x**(o/3)
assert Order(x**(o*Rational(5, 3))).expr == x**(o*Rational(5, 3))
assert Order(x**2 + x + y, x) == O(1, x)
assert Order(x**2 + x + y, y) == O(1, y)
raises(ValueError, lambda: Order(exp(x), x, x))
raises(TypeError, lambda: Order(x, 2 - x))
def test_simple_2():
assert Order(2*x)*x == Order(x**2)
assert Order(2*x)/x == Order(1, x)
assert Order(2*x)*x*exp(1/x) == Order(x**2*exp(1/x))
assert (Order(2*x)*x*exp(1/x)/ln(x)**3).expr == x**2*exp(1/x)*ln(x)**-3
def test_simple_3():
assert Order(x) + x == Order(x)
assert Order(x) + 2 == 2 + Order(x)
assert Order(x) + x**2 == Order(x)
assert Order(x) + 1/x == 1/x + Order(x)
assert Order(1/x) + 1/x**2 == 1/x**2 + Order(1/x)
assert Order(x) + exp(1/x) == Order(x) + exp(1/x)
def test_simple_4():
assert Order(x)**2 == Order(x**2)
def test_simple_5():
assert Order(x) + Order(x**2) == Order(x)
assert Order(x) + Order(x**-2) == Order(x**-2)
assert Order(x) + Order(1/x) == Order(1/x)
def test_simple_6():
assert Order(x) - Order(x) == Order(x)
assert Order(x) + Order(1) == Order(1)
assert Order(x) + Order(x**2) == Order(x)
assert Order(1/x) + Order(1) == Order(1/x)
assert Order(x) + Order(exp(1/x)) == Order(exp(1/x))
assert Order(x**3) + Order(exp(2/x)) == Order(exp(2/x))
assert Order(x**-3) + Order(exp(2/x)) == Order(exp(2/x))
def test_simple_7():
assert 1 + O(1) == O(1)
assert 2 + O(1) == O(1)
assert x + O(1) == O(1)
assert 1/x + O(1) == 1/x + O(1)
def test_simple_8():
assert O(sqrt(-x)) == O(sqrt(x))
assert O(x**2*sqrt(x)) == O(x**Rational(5, 2))
assert O(x**3*sqrt(-(-x)**3)) == O(x**Rational(9, 2))
assert O(x**Rational(3, 2)*sqrt((-x)**3)) == O(x**3)
assert O(x*(-2*x)**(I/2)) == O(x*(-x)**(I/2))
def test_as_expr_variables():
assert Order(x).as_expr_variables(None) == (x, ((x, 0),))
assert Order(x).as_expr_variables(((x, 0),)) == (x, ((x, 0),))
assert Order(y).as_expr_variables(((x, 0),)) == (y, ((x, 0), (y, 0)))
assert Order(y).as_expr_variables(((x, 0), (y, 0))) == (y, ((x, 0), (y, 0)))
def test_contains_0():
assert Order(1, x).contains(Order(1, x))
assert Order(1, x).contains(Order(1))
assert Order(1).contains(Order(1, x)) is False
def test_contains_1():
assert Order(x).contains(Order(x))
assert Order(x).contains(Order(x**2))
assert not Order(x**2).contains(Order(x))
assert not Order(x).contains(Order(1/x))
assert not Order(1/x).contains(Order(exp(1/x)))
assert not Order(x).contains(Order(exp(1/x)))
assert Order(1/x).contains(Order(x))
assert Order(exp(1/x)).contains(Order(x))
assert Order(exp(1/x)).contains(Order(1/x))
assert Order(exp(1/x)).contains(Order(exp(1/x)))
assert Order(exp(2/x)).contains(Order(exp(1/x)))
assert not Order(exp(1/x)).contains(Order(exp(2/x)))
def test_contains_2():
assert Order(x).contains(Order(y)) is None
assert Order(x).contains(Order(y*x))
assert Order(y*x).contains(Order(x))
assert Order(y).contains(Order(x*y))
assert Order(x).contains(Order(y**2*x))
def test_contains_3():
assert Order(x*y**2).contains(Order(x**2*y)) is None
assert Order(x**2*y).contains(Order(x*y**2)) is None
def test_contains_4():
assert Order(sin(1/x**2)).contains(Order(cos(1/x**2))) is None
assert Order(cos(1/x**2)).contains(Order(sin(1/x**2))) is None
def test_contains():
assert Order(1, x) not in Order(1)
assert Order(1) in Order(1, x)
raises(TypeError, lambda: Order(x*y**2) in Order(x**2*y))
def test_add_1():
assert Order(x + x) == Order(x)
assert Order(3*x - 2*x**2) == Order(x)
assert Order(1 + x) == Order(1, x)
assert Order(1 + 1/x) == Order(1/x)
assert Order(ln(x) + 1/ln(x)) == Order(ln(x))
assert Order(exp(1/x) + x) == Order(exp(1/x))
assert Order(exp(1/x) + 1/x**20) == Order(exp(1/x))
def test_ln_args():
assert O(log(x)) + O(log(2*x)) == O(log(x))
assert O(log(x)) + O(log(x**3)) == O(log(x))
assert O(log(x*y)) + O(log(x) + log(y)) == O(log(x*y))
def test_multivar_0():
assert Order(x*y).expr == x*y
assert Order(x*y**2).expr == x*y**2
assert Order(x*y, x).expr == x
assert Order(x*y**2, y).expr == y**2
assert Order(x*y*z).expr == x*y*z
assert Order(x/y).expr == x/y
assert Order(x*exp(1/y)).expr == x*exp(1/y)
assert Order(exp(x)*exp(1/y)).expr == exp(1/y)
def test_multivar_0a():
assert Order(exp(1/x)*exp(1/y)).expr == exp(1/x + 1/y)
def test_multivar_1():
assert Order(x + y).expr == x + y
assert Order(x + 2*y).expr == x + y
assert (Order(x + y) + x).expr == (x + y)
assert (Order(x + y) + x**2) == Order(x + y)
assert (Order(x + y) + 1/x) == 1/x + Order(x + y)
assert Order(x**2 + y*x).expr == x**2 + y*x
def test_multivar_2():
assert Order(x**2*y + y**2*x, x, y).expr == x**2*y + y**2*x
def test_multivar_mul_1():
assert Order(x + y)*x == Order(x**2 + y*x, x, y)
def test_multivar_3():
assert (Order(x) + Order(y)).args in [
(Order(x), Order(y)),
(Order(y), Order(x))]
assert Order(x) + Order(y) + Order(x + y) == Order(x + y)
assert (Order(x**2*y) + Order(y**2*x)).args in [
(Order(x*y**2), Order(y*x**2)),
(Order(y*x**2), Order(x*y**2))]
assert (Order(x**2*y) + Order(y*x)) == Order(x*y)
def test_issue_3468():
y = Symbol('y', negative=True)
z = Symbol('z', complex=True)
# check that Order does not modify assumptions about symbols
Order(x)
Order(y)
Order(z)
assert x.is_positive is None
assert y.is_positive is False
assert z.is_positive is None
def test_leading_order():
assert (x + 1 + 1/x**5).extract_leading_order(x) == ((1/x**5, O(1/x**5)),)
assert (1 + 1/x).extract_leading_order(x) == ((1/x, O(1/x)),)
assert (1 + x).extract_leading_order(x) == ((1, O(1, x)),)
assert (1 + x**2).extract_leading_order(x) == ((1, O(1, x)),)
assert (2 + x**2).extract_leading_order(x) == ((2, O(1, x)),)
assert (x + x**2).extract_leading_order(x) == ((x, O(x)),)
def test_leading_order2():
assert set((2 + pi + x**2).extract_leading_order(x)) == {(pi, O(1, x)),
(S(2), O(1, x))}
assert set((2*x + pi*x + x**2).extract_leading_order(x)) == {(2*x, O(x)),
(x*pi, O(x))}
def test_order_leadterm():
assert O(x**2)._eval_as_leading_term(x) == O(x**2)
def test_order_symbols():
e = x*y*sin(x)*Integral(x, (x, 1, 2))
assert O(e) == O(x**2*y, x, y)
assert O(e, x) == O(x**2)
def test_nan():
assert O(nan) is nan
assert not O(x).contains(nan)
def test_O1():
assert O(1, x) * x == O(x)
assert O(1, y) * x == O(1, y)
def test_getn():
# other lines are tested incidentally by the suite
assert O(x).getn() == 1
assert O(x/log(x)).getn() == 1
assert O(x**2/log(x)**2).getn() == 2
assert O(x*log(x)).getn() == 1
raises(NotImplementedError, lambda: (O(x) + O(y)).getn())
def test_diff():
assert O(x**2).diff(x) == O(x)
def test_getO():
assert (x).getO() is None
assert (x).removeO() == x
assert (O(x)).getO() == O(x)
assert (O(x)).removeO() == 0
assert (z + O(x) + O(y)).getO() == O(x) + O(y)
assert (z + O(x) + O(y)).removeO() == z
raises(NotImplementedError, lambda: (O(x) + O(y)).getn())
def test_leading_term():
from sympy import digamma
assert O(1/digamma(1/x)) == O(1/log(x))
def test_eval():
assert Order(x).subs(Order(x), 1) == 1
assert Order(x).subs(x, y) == Order(y)
assert Order(x).subs(y, x) == Order(x)
assert Order(x).subs(x, x + y) == Order(x + y, (x, -y))
assert (O(1)**x).is_Pow
def test_issue_4279():
a, b = symbols('a b')
assert O(a, a, b) + O(1, a, b) == O(1, a, b)
assert O(b, a, b) + O(1, a, b) == O(1, a, b)
assert O(a + b, a, b) + O(1, a, b) == O(1, a, b)
assert O(1, a, b) + O(a, a, b) == O(1, a, b)
assert O(1, a, b) + O(b, a, b) == O(1, a, b)
assert O(1, a, b) + O(a + b, a, b) == O(1, a, b)
def test_issue_4855():
assert 1/O(1) != O(1)
assert 1/O(x) != O(1/x)
assert 1/O(x, (x, oo)) != O(1/x, (x, oo))
f = Function('f')
assert 1/O(f(x)) != O(1/x)
def test_order_conjugate_transpose():
x = Symbol('x', real=True)
y = Symbol('y', imaginary=True)
assert conjugate(Order(x)) == Order(conjugate(x))
assert conjugate(Order(y)) == Order(conjugate(y))
assert conjugate(Order(x**2)) == Order(conjugate(x)**2)
assert conjugate(Order(y**2)) == Order(conjugate(y)**2)
assert transpose(Order(x)) == Order(transpose(x))
assert transpose(Order(y)) == Order(transpose(y))
assert transpose(Order(x**2)) == Order(transpose(x)**2)
assert transpose(Order(y**2)) == Order(transpose(y)**2)
def test_order_noncommutative():
A = Symbol('A', commutative=False)
assert Order(A + A*x, x) == Order(1, x)
assert (A + A*x)*Order(x) == Order(x)
assert (A*x)*Order(x) == Order(x**2, x)
assert expand((1 + Order(x))*A*A*x) == A*A*x + Order(x**2, x)
assert expand((A*A + Order(x))*x) == A*A*x + Order(x**2, x)
assert expand((A + Order(x))*A*x) == A*A*x + Order(x**2, x)
def test_issue_6753():
assert (1 + x**2)**10000*O(x) == O(x)
def test_order_at_infinity():
assert Order(1 + x, (x, oo)) == Order(x, (x, oo))
assert Order(3*x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo))*3 == Order(x, (x, oo))
assert -28*Order(x, (x, oo)) == Order(x, (x, oo))
assert Order(Order(x, (x, oo)), (x, oo)) == Order(x, (x, oo))
assert Order(Order(x, (x, oo)), (y, oo)) == Order(x, (x, oo), (y, oo))
assert Order(3, (x, oo)) == Order(1, (x, oo))
assert Order(x**2 + x + y, (x, oo)) == O(x**2, (x, oo))
assert Order(x**2 + x + y, (y, oo)) == O(y, (y, oo))
assert Order(2*x, (x, oo))*x == Order(x**2, (x, oo))
assert Order(2*x, (x, oo))/x == Order(1, (x, oo))
assert Order(2*x, (x, oo))*x*exp(1/x) == Order(x**2*exp(1/x), (x, oo))
assert Order(2*x, (x, oo))*x*exp(1/x)/ln(x)**3 == Order(x**2*exp(1/x)*ln(x)**-3, (x, oo))
assert Order(x, (x, oo)) + 1/x == 1/x + Order(x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + 1 == 1 + Order(x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + x == x + Order(x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + x**2 == x**2 + Order(x, (x, oo))
assert Order(1/x, (x, oo)) + 1/x**2 == 1/x**2 + Order(1/x, (x, oo)) == Order(1/x, (x, oo))
assert Order(x, (x, oo)) + exp(1/x) == exp(1/x) + Order(x, (x, oo))
assert Order(x, (x, oo))**2 == Order(x**2, (x, oo))
assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo))
assert Order(x, (x, oo)) + Order(x**-2, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + Order(1/x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) - Order(x, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + Order(1, (x, oo)) == Order(x, (x, oo))
assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo))
assert Order(1/x, (x, oo)) + Order(1, (x, oo)) == Order(1, (x, oo))
assert Order(x, (x, oo)) + Order(exp(1/x), (x, oo)) == Order(x, (x, oo))
assert Order(x**3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(x**3, (x, oo))
assert Order(x**-3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(exp(2/x), (x, oo))
# issue 7207
assert Order(exp(x), (x, oo)).expr == Order(2*exp(x), (x, oo)).expr == exp(x)
assert Order(y**x, (x, oo)).expr == Order(2*y**x, (x, oo)).expr == exp(log(y)*x)
# issue 19545
assert Order(1/x - 3/(3*x + 2), (x, oo)).expr == x**(-2)
def test_mixing_order_at_zero_and_infinity():
assert (Order(x, (x, 0)) + Order(x, (x, oo))).is_Add
assert Order(x, (x, 0)) + Order(x, (x, oo)) == Order(x, (x, oo)) + Order(x, (x, 0))
assert Order(Order(x, (x, oo))) == Order(x, (x, oo))
# not supported (yet)
raises(NotImplementedError, lambda: Order(x, (x, 0))*Order(x, (x, oo)))
raises(NotImplementedError, lambda: Order(x, (x, oo))*Order(x, (x, 0)))
raises(NotImplementedError, lambda: Order(Order(x, (x, oo)), y))
raises(NotImplementedError, lambda: Order(Order(x), (x, oo)))
def test_order_at_some_point():
assert Order(x, (x, 1)) == Order(1, (x, 1))
assert Order(2*x - 2, (x, 1)) == Order(x - 1, (x, 1))
assert Order(-x + 1, (x, 1)) == Order(x - 1, (x, 1))
assert Order(x - 1, (x, 1))**2 == Order((x - 1)**2, (x, 1))
assert Order(x - 2, (x, 2)) - O(x - 2, (x, 2)) == Order(x - 2, (x, 2))
def test_order_subs_limits():
# issue 3333
assert (1 + Order(x)).subs(x, 1/x) == 1 + Order(1/x, (x, oo))
assert (1 + Order(x)).limit(x, 0) == 1
# issue 5769
assert ((x + Order(x**2))/x).limit(x, 0) == 1
assert Order(x**2).subs(x, y - 1) == Order((y - 1)**2, (y, 1))
assert Order(10*x**2, (x, 2)).subs(x, y - 1) == Order(1, (y, 3))
def test_issue_9351():
assert exp(x).series(x, 10, 1) == exp(10) + Order(x - 10, (x, 10))
def test_issue_9192():
assert O(1)*O(1) == O(1)
assert O(1)**O(1) == O(1)
def test_issue_9910():
assert O(x*log(x) + sin(x), (x, oo)) == O(x*log(x), (x, oo))
def test_performance_of_adding_order():
l = list(x**i for i in range(1000))
l.append(O(x**1001))
assert Add(*l).subs(x,1) == O(1)
def test_issue_14622():
assert (x**(-4) + x**(-3) + x**(-1) + O(x**(-6), (x, oo))).as_numer_denom() == (
x**4 + x**5 + x**7 + O(x**2, (x, oo)), x**8)
assert (x**3 + O(x**2, (x, oo))).is_Add
assert O(x**2, (x, oo)).contains(x**3) is False
assert O(x, (x, oo)).contains(O(x, (x, 0))) is None
assert O(x, (x, 0)).contains(O(x, (x, oo))) is None
raises(NotImplementedError, lambda: O(x**3).contains(x**w))
def test_issue_15539():
assert O(1/x**2 + 1/x**4, (x, -oo)) == O(1/x**2, (x, -oo))
assert O(1/x**4 + exp(x), (x, -oo)) == O(1/x**4, (x, -oo))
assert O(1/x**4 + exp(-x), (x, -oo)) == O(exp(-x), (x, -oo))
assert O(1/x, (x, oo)).subs(x, -x) == O(-1/x, (x, -oo))
def test_issue_18606():
assert unchanged(Order, 0)
|
c592cff8265be1196112572819499c60a19de0fe3670c5a39ccdc39d08f41ea5 | from itertools import product as cartes
from sympy import (
limit, exp, oo, log, sqrt, Limit, sin, floor, cos, ceiling,
atan, Abs, gamma, Symbol, S, pi, Integral, Rational, I,
tan, cot, integrate, Sum, sign, Function, subfactorial, symbols,
binomial, simplify, frac, Float, sec, zoo, fresnelc, fresnels,
acos, erf, erfc, erfi, LambertW, factorial, digamma, uppergamma,
Ei, EulerGamma, asin, atanh, acot, acoth, asec, acsc, cbrt, besselk)
from sympy.calculus.util import AccumBounds
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.series.limits import heuristics
from sympy.series.order import Order
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, y, z, k
n = Symbol('n', integer=True, positive=True)
def test_basic1():
assert limit(x, x, oo) is oo
assert limit(x, x, -oo) is -oo
assert limit(-x, x, oo) is -oo
assert limit(x**2, x, -oo) is oo
assert limit(-x**2, x, oo) is -oo
assert limit(x*log(x), x, 0, dir="+") == 0
assert limit(1/x, x, oo) == 0
assert limit(exp(x), x, oo) is oo
assert limit(-exp(x), x, oo) is -oo
assert limit(exp(x)/x, x, oo) is oo
assert limit(1/x - exp(-x), x, oo) == 0
assert limit(x + 1/x, x, oo) is oo
assert limit(x - x**2, x, oo) is -oo
assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0)
assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-')
assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((x + y + 1)**oo, x, 0, dir='-')
assert limit(y/x/log(x), x, 0) == -oo*sign(y)
assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
assert limit(gamma(1/x + 3), x, oo) == 2
assert limit(S.NaN, x, -oo) is S.NaN
assert limit(Order(2)*x, x, S.NaN) is S.NaN
assert limit(1/(x - 1), x, 1, dir="+") is oo
assert limit(1/(x - 1), x, 1, dir="-") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="-") is oo
assert limit(1/sin(x), x, pi, dir="+") is -oo
assert limit(1/sin(x), x, pi, dir="-") is oo
assert limit(1/cos(x), x, pi/2, dir="+") is -oo
assert limit(1/cos(x), x, pi/2, dir="-") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo
# test bi-directional limits
assert limit(sin(x)/x, x, 0, dir="+-") == 1
assert limit(x**2, x, 0, dir="+-") == 0
assert limit(1/x**2, x, 0, dir="+-") is oo
# test failing bi-directional limits
assert limit(1/x, x, 0, dir="+-") is zoo
# approaching 0
# from dir="+"
assert limit(1 + 1/x, x, 0) is oo
# from dir='-'
# Add
assert limit(1 + 1/x, x, 0, dir='-') is -oo
# Pow
assert limit(x**(-2), x, 0, dir='-') is oo
assert limit(x**(-3), x, 0, dir='-') is -oo
assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
assert limit(x**2, x, 0, dir='-') == 0
assert limit(sqrt(x), x, 0, dir='-') == 0
assert limit(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
def test_basic2():
assert limit(x**x, x, 0, dir="+") == 1
assert limit((exp(x) - 1)/x, x, 0) == 1
assert limit(1 + 1/x, x, oo) == 1
assert limit(-exp(1/x), x, oo) == -1
assert limit(x + exp(-x), x, oo) is oo
assert limit(x + exp(-x**2), x, oo) is oo
assert limit(x + exp(-exp(x)), x, oo) is oo
assert limit(13 + 1/x - exp(-x), x, oo) == 13
def test_basic3():
assert limit(1/x, x, 0, dir="+") is oo
assert limit(1/x, x, 0, dir="-") is -oo
def test_basic4():
assert limit(2*x + y*x, x, 0) == 0
assert limit(2*x + y*x, x, 1) == 2 + y
assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8
assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0
assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9
def test_basic5():
class my(Function):
@classmethod
def eval(cls, arg):
if arg is S.Infinity:
return S.NaN
assert limit(my(x), x, oo) == Limit(my(x), x, oo)
def test_issue_3885():
assert limit(x*y + x*z, z, 2) == x*(y + 2)
def test_Limit():
assert Limit(sin(x)/x, x, 0) != 1
assert Limit(sin(x)/x, x, 0).doit() == 1
assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-'))
def test_floor():
assert limit(floor(x), x, -2, "+") == -2
assert limit(floor(x), x, -2, "-") == -3
assert limit(floor(x), x, -1, "+") == -1
assert limit(floor(x), x, -1, "-") == -2
assert limit(floor(x), x, 0, "+") == 0
assert limit(floor(x), x, 0, "-") == -1
assert limit(floor(x), x, 1, "+") == 1
assert limit(floor(x), x, 1, "-") == 0
assert limit(floor(x), x, 2, "+") == 2
assert limit(floor(x), x, 2, "-") == 1
assert limit(floor(x), x, 248, "+") == 248
assert limit(floor(x), x, 248, "-") == 247
def test_floor_requires_robust_assumptions():
assert limit(floor(sin(x)), x, 0, "+") == 0
assert limit(floor(sin(x)), x, 0, "-") == -1
assert limit(floor(cos(x)), x, 0, "+") == 0
assert limit(floor(cos(x)), x, 0, "-") == 0
assert limit(floor(5 + sin(x)), x, 0, "+") == 5
assert limit(floor(5 + sin(x)), x, 0, "-") == 4
assert limit(floor(5 + cos(x)), x, 0, "+") == 5
assert limit(floor(5 + cos(x)), x, 0, "-") == 5
def test_ceiling():
assert limit(ceiling(x), x, -2, "+") == -1
assert limit(ceiling(x), x, -2, "-") == -2
assert limit(ceiling(x), x, -1, "+") == 0
assert limit(ceiling(x), x, -1, "-") == -1
assert limit(ceiling(x), x, 0, "+") == 1
assert limit(ceiling(x), x, 0, "-") == 0
assert limit(ceiling(x), x, 1, "+") == 2
assert limit(ceiling(x), x, 1, "-") == 1
assert limit(ceiling(x), x, 2, "+") == 3
assert limit(ceiling(x), x, 2, "-") == 2
assert limit(ceiling(x), x, 248, "+") == 249
assert limit(ceiling(x), x, 248, "-") == 248
def test_ceiling_requires_robust_assumptions():
assert limit(ceiling(sin(x)), x, 0, "+") == 1
assert limit(ceiling(sin(x)), x, 0, "-") == 0
assert limit(ceiling(cos(x)), x, 0, "+") == 1
assert limit(ceiling(cos(x)), x, 0, "-") == 1
assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6
assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5
assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6
assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6
def test_atan():
x = Symbol("x", real=True)
assert limit(atan(x)*sin(1/x), x, 0) == 0
assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2
def test_abs():
assert limit(abs(x), x, 0) == 0
assert limit(abs(sin(x)), x, 0) == 0
assert limit(abs(cos(x)), x, 0) == 1
assert limit(abs(sin(x + 1)), x, 0) == sin(1)
def test_heuristic():
x = Symbol("x", real=True)
assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1)
assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2)
def test_issue_3871():
z = Symbol("z", positive=True)
f = -1/z*exp(-z*x)
assert limit(f, x, oo) == 0
assert f.limit(x, oo) == 0
def test_exponential():
n = Symbol('n')
x = Symbol('x', real=True)
assert limit((1 + x/n)**n, n, oo) == exp(x)
assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2)
assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2)
assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2)
assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1
assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3'))
def test_exponential2():
n = Symbol('n')
assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x)
def test_doit():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
assert l.doit() is oo
def test_AccumBounds():
assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2)
assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3)
# not the exact bound
assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2)
# test for issue #9934
t1 = Mul(S.Half, 1/(-1 + cos(1)), Add(AccumBounds(-3, 1), cos(1)))
assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1
t2 = Mul(S.Half, Add(AccumBounds(-2, 2), sin(1)), 1/(-cos(1) + 1))
assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2
assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo)
assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo)
# Possible improvement: AccumBounds(0, 1)
@XFAIL
def test_doit2():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
# limit() breaks on the contained Integral.
assert l.doit(deep=False) == l
def test_issue_2929():
assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0
def test_issue_3792():
assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half)
assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1))
assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1)
def test_issue_4090():
assert limit(1/(x + 3), x, 2) == Rational(1, 5)
assert limit(1/(x + pi), x, 2) == S.One/(2 + pi)
assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7
assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi)
def test_issue_4547():
assert limit(cot(x), x, 0, dir='+') is oo
assert limit(cot(x), x, pi/2, dir='+') == 0
def test_issue_5164():
assert limit(x**0.5, x, oo) == oo**0.5 is oo
assert limit(x**0.5, x, 16) == S(16)**0.5
assert limit(x**0.5, x, 0) == 0
assert limit(x**(-0.5), x, oo) == 0
assert limit(x**(-0.5), x, 4) == S(4)**(-0.5)
def test_issue_14793():
expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \
log(factorial(x)) + S(1)/(12*x))*x**3
assert limit(expr, x, oo) == S(1)/360
def test_issue_5183():
# using list(...) so py.test can recalculate values
tests = list(cartes([x, -x],
[-1, 1],
[2, 3, S.Half, Rational(2, 3)],
['-', '+']))
results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo,
0, 0, 0, 0, 0, 0, 0, 0,
oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3),
0, 0, 0, 0, 0, 0, 0, 0)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
y, s, e, d = args
eq = y**(s*e)
try:
assert limit(eq, x, 0, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, d, limit(eq, x, 0, dir=d))
else:
assert None
def test_issue_5184():
assert limit(sin(x)/x, x, oo) == 0
assert limit(atan(x), x, oo) == pi/2
assert limit(gamma(x), x, oo) is oo
assert limit(cos(x)/x, x, oo) == 0
assert limit(gamma(x), x, S.Half) == sqrt(pi)
r = Symbol('r', real=True)
assert limit(r*sin(1/r), r, 0) == 0
def test_issue_5229():
assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0
def test_issue_4546():
# using list(...) so py.test can recalculate values
tests = list(cartes([cot, tan],
[-pi/2, 0, pi/2, pi, pi*Rational(3, 2)],
['-', '+']))
results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0,
oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
f, l, d = args
eq = f(x)
try:
assert limit(eq, x, l, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, l, d, limit(eq, x, l, dir=d))
else:
assert None
def test_issue_3934():
assert limit((1 + x**log(3))**(1/x), x, 0) == 1
assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5
def test_calculate_series():
# needs gruntz calculate_series to go to n = 32
assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1
# needs gruntz calculate_series to go to n = 128
assert limit(x**101.1/(1 + x**101.1), x, oo) == 1
def test_issue_5955():
assert limit((x**16)/(1 + x**16), x, oo) == 1
assert limit((x**100)/(1 + x**100), x, oo) == 1
assert limit((x**1885)/(1 + x**1885), x, oo) == 1
assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1
def test_newissue():
assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1
def test_extended_real_line():
assert limit(x - oo, x, oo) is -oo
assert limit(oo - x, x, -oo) is oo
assert limit(x**2/(x - 5) - oo, x, oo) is -oo
assert limit(1/(x + sin(x)) - oo, x, 0) is -oo
assert limit(oo/x, x, oo) is oo
assert limit(x - oo + 1/x, x, oo) is -oo
assert limit(x - oo + 1/x, x, 0) is -oo
@XFAIL
def test_order_oo():
x = Symbol('x', positive=True)
assert Order(x)*oo != Order(1, x)
assert limit(oo/(x**2 - 4), x, oo) is oo
def test_issue_5436():
raises(NotImplementedError, lambda: limit(exp(x*y), x, oo))
raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo))
def test_Limit_dir():
raises(TypeError, lambda: Limit(x, x, 0, dir=0))
raises(ValueError, lambda: Limit(x, x, 0, dir='0'))
def test_polynomial():
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1
def test_rational():
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z)
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z)
def test_issue_5740():
assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z)
def test_issue_6366():
n = Symbol('n', integer=True, positive=True)
r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
assert limit(r, x, 1) == n/2
def test_factorial():
from sympy import factorial, E
f = factorial(x)
assert limit(f, x, oo) is oo
assert limit(x/f, x, oo) == 0
# see Stirling's approximation:
# https://en.wikipedia.org/wiki/Stirling's_approximation
assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1
assert limit(f, x, -oo) == factorial(-oo)
assert limit(f, x, x**2) == factorial(x**2)
assert limit(f, x, -x**2) == factorial(-x**2)
def test_issue_6560():
e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) +
35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1)))
assert limit(e, y, oo) == (5*x**3 + 3*x**2 - 3*x - 1)/4
@XFAIL
def test_issue_5172():
n = Symbol('n')
r = Symbol('r', positive=True)
c = Symbol('c')
p = Symbol('p', positive=True)
m = Symbol('m', negative=True)
expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c +
(r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
expr = expr.subs(c, c + 1)
raises(NotImplementedError, lambda: limit(expr, n, oo))
assert limit(expr.subs(c, m), n, oo) == 1
assert limit(expr.subs(c, p), n, oo).simplify() == \
(2**(p + 1) + r - 1)/(r + 1)**(p + 1)
def test_issue_7088():
a = Symbol('a')
assert limit(sqrt(x/(x + a)), x, oo) == 1
def test_branch_cuts():
assert limit(asin(I*x + 2), x, 0) == pi - asin(2)
assert limit(asin(I*x + 2), x, 0, '-') == asin(2)
assert limit(asin(I*x - 2), x, 0) == -asin(2)
assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2)
assert limit(acos(I*x + 2), x, 0) == -acos(2)
assert limit(acos(I*x + 2), x, 0, '-') == acos(2)
assert limit(acos(I*x - 2), x, 0) == acos(-2)
assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2)
assert limit(atan(x + 2*I), x, 0) == I*atanh(2)
assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2)
assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2)
assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2)
assert limit(atan(1/x), x, 0) == pi/2
assert limit(atan(1/x), x, 0, '-') == -pi/2
assert limit(atan(x), x, oo) == pi/2
assert limit(atan(x), x, -oo) == -pi/2
assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2)
assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2)
assert limit(acot(x), x, 0) == pi/2
assert limit(acot(x), x, 0, '-') == -pi/2
assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2)
assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2)
assert limit(log(I*x - 1), x, 0) == I*pi
assert limit(log(I*x - 1), x, 0, '-') == -I*pi
assert limit(log(-I*x - 1), x, 0) == -I*pi
assert limit(log(-I*x - 1), x, 0, '-') == I*pi
assert limit(sqrt(I*x - 1), x, 0) == I
assert limit(sqrt(I*x - 1), x, 0, '-') == -I
assert limit(sqrt(-I*x - 1), x, 0) == -I
assert limit(sqrt(-I*x - 1), x, 0, '-') == I
assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3)
assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3)
def test_issue_6364():
a = Symbol('a')
e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2)
assert limit(e, z, 0).simplify() == 2/cos(2*a)
def test_issue_4099():
a = Symbol('a')
assert limit(a/x, x, 0) == oo*sign(a)
assert limit(-a/x, x, 0) == -oo*sign(a)
assert limit(-a*x, x, oo) == -oo*sign(a)
assert limit(a*x, x, oo) == oo*sign(a)
def test_issue_4503():
dx = Symbol('dx')
assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \
exp(x)/(2*sqrt(exp(x) + 1))
def test_issue_8208():
assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0
def test_issue_8229():
assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0
def test_issue_8433():
d, t = symbols('d t', positive=True)
assert limit(erf(1 - t/d), t, oo) == -1
def test_issue_8481():
k = Symbol('k', integer=True, nonnegative=True)
lamda = Symbol('lamda', real=True, positive=True)
limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0
def test_issue_8730():
assert limit(subfactorial(x), x, oo) is oo
def test_issue_9558():
assert limit(sin(x)**15, x, 0, '-') == 0
def test_issue_10801():
# make sure limits work with binomial
assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi
def test_issue_10976():
s, x = symbols('s x', real=True)
assert limit(erf(s*x)/erf(s), s, 0) == x
def test_issue_9041():
assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1
def test_issue_9205():
x, y, a = symbols('x, y, a')
assert Limit(x, x, a).free_symbols == {a}
assert Limit(x, x, a, '-').free_symbols == {a}
assert Limit(x + y, x + y, a).free_symbols == {a}
assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a}
def test_issue_9471():
assert limit(((27**(log(n,3)))/n**3),n,oo) == 1
assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27
def test_issue_11496():
assert limit(erfc(log(1/x)), x, oo) == 2
def test_issue_11879():
assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1)
def test_limit_with_Float():
k = symbols("k")
assert limit(1.0 ** k, k, oo) == 1
assert limit(0.3*1.0**k, k, oo) == Float(0.3)
def test_issue_10610():
assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3)
def test_issue_6599():
assert limit((n + cos(n))/n, n, oo) == 1
def test_issue_12398():
assert limit(Abs(log(x)/x**3), x, oo) == 0
assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3
def test_issue_12555():
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo
def test_issue_12769():
r, z, x = symbols('r z x', real=True)
a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True)
fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \
F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \
2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \
2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \
2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1)
assert fx.subs(K, F0).cancel().together() == limit(fx, K, F0).together()
def test_issue_13332():
assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) *
(6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36)
def test_issue_12564():
assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo
assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, oo) is oo
assert limit(((x + sin(x))**2).expand(), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, -oo) is oo
assert limit(((x + sin(x))**2).expand(), x, -oo) is oo
def test_issue_14456():
raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit())
raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit())
def test_issue_14411():
assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo
def test_issue_13382():
assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2
def test_issue_13403():
assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x ,oo) == 1
def test_issue_13416():
assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x ,oo) == 1
def test_issue_13462():
assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x*(x - 2)*(x - 1)/24
def test_issue_13750():
a = Symbol('a')
assert limit(erf(a - x), x, oo) == -1
assert limit(erf(sqrt(x) - x), x, oo) == -1
def test_issue_14514():
assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1
def test_issue_14574():
assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0
def test_issue_10102():
assert limit(fresnels(x), x, oo) == S.Half
assert limit(3 + fresnels(x), x, oo) == 3 + S.Half
assert limit(5*fresnels(x), x, oo) == Rational(5, 2)
assert limit(fresnelc(x), x, oo) == S.Half
assert limit(fresnels(x), x, -oo) == Rational(-1, 2)
assert limit(4*fresnelc(x), x, -oo) == -2
def test_issue_14377():
raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo))
def test_issue_15146():
e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \
2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3)
assert limit(e, x, oo) == S(1)/3
def test_issue_15202():
e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1)
assert limit(e, x, oo) == exp(1)
e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x)
assert limit(e, x, oo) == 10
def test_issue_15282():
assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000
def test_issue_15984():
assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-').doit() == 0
def test_issue_13571():
assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1
def test_issue_13575():
assert limit(acos(erfi(x)), x, 1).cancel() == acos(-I*erf(I))
def test_issue_17325():
assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1
assert Limit(x**2, x, 0, dir="+-").doit() == 0
assert Limit(1/x**2, x, 0, dir="+-").doit() is oo
assert Limit(1/x, x, 0, dir="+-").doit() is zoo
def test_issue_10978():
assert LambertW(x).limit(x, 0) == 0
@XFAIL
def test_issue_14313_comment():
assert limit(floor(n/2), n, oo) is oo
@XFAIL
def test_issue_15323():
d = ((1 - 1/x)**x).diff(x)
assert limit(d, x, 1, dir='+') == 1
def test_issue_12571():
assert limit(-LambertW(-log(x))/log(x), x, 1) == 1
def test_issue_14590():
assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1)
def test_issue_14393():
a, b = symbols('a b')
assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a)*y**b/a
def test_issue_14556():
assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1)
def test_issue_14811():
assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo
def test_issue_14874():
assert limit(besselk(0, x), x, oo) == 0
def test_issue_16222():
assert limit(exp(x), x, 1000000000) == exp(1000000000)
def test_issue_16714():
assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1))
def test_issue_16722():
z = symbols('z', positive=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
z = symbols('z', positive=True, integer=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
def test_issue_17431():
assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) *
(n + 2) * factorial(n) / (n + 1), n, oo) == 0
assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1))
, n, oo) == 0
assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0
def test_issue_17671():
assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma
def test_issue_17751():
a, b, c, x = symbols('a b c x', positive=True)
assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2)
def test_issue_17792():
assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi)
def test_issue_18306():
assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1
def test_issue_18378():
assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3
def test_issue_18399():
assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo
assert limit((-x)**x, x, oo) is zoo
def test_issue_18442():
assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-')
def test_issue_18452():
assert limit(abs(log(x))**x, x, 0) == 1
assert limit(abs(log(x))**x, x, 0, "-") == 1
def test_issue_18482():
assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1)
def test_issue_18501():
assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
def test_issue_18508():
assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2)
def test_issue_18969():
a, b = symbols('a b', positive=True)
assert limit(LambertW(a), a, b) == LambertW(b)
assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b))
def test_issue_18992():
assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1)
def test_issue_18997():
assert limit(Abs(log(x)), x, 0) == oo
assert limit(Abs(log(Abs(x))), x, 0) == oo
def test_issue_19026():
x = Symbol('x', positive=True)
assert limit(Abs(log(x) + 1)/log(x), x, oo) == 1
def test_issue_19067():
x = Symbol('x')
assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1
def test_issue_19586():
assert limit(x**(2**x*3**(-x)), x, oo) == 1
def test_issue_13715():
n = Symbol('n')
p = Symbol('p', zero=True)
assert limit(n + p, n, 0) == p
def test_issue_15055():
assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1
def test_issue_16708():
m, vi = symbols('m vi', positive=True)
B, ti, d = symbols('B ti d')
assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi
def test_issue_19739():
assert limit((-S(1)/4)**x, x, oo) == 0
def test_issue_19766():
assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2
def test_issue_19770():
m = Symbol('m')
# the result is not 0 for non-real m
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', real=True)
# can be improved to give the correct result 0
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', nonzero=True)
assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1)
assert limit(cos(m*x)/x, x, oo) == 0
def test_issue_7535():
assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-')
assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1)
assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo)
|
531c49b89639760ab143869d580257a4ea57e7170c679bf847cbfabe847d0f63 | from sympy import (
Add, Mul, S, Symbol, cos, cot, pi, I, sin, sqrt, tan, root, csc, sec,
powsimp, symbols, sinh, cosh, tanh, coth, sech, csch, Dummy, Rational)
from sympy.simplify.fu import (
L, TR1, TR10, TR10i, TR11, _TR11, TR12, TR12i, TR13, TR14, TR15, TR16,
TR111, TR2, TR2i, TR3, TR5, TR6, TR7, TR8, TR9, TRmorrie, _TR56 as T,
TRpower, hyper_as_trig, fu, process_common_addends, trig_split,
as_f_sign_1)
from sympy.testing.randtest import verify_numerically
from sympy.abc import a, b, c, x, y, z
def test_TR1():
assert TR1(2*csc(x) + sec(x)) == 1/cos(x) + 2/sin(x)
def test_TR2():
assert TR2(tan(x)) == sin(x)/cos(x)
assert TR2(cot(x)) == cos(x)/sin(x)
assert TR2(tan(tan(x) - sin(x)/cos(x))) == 0
def test_TR2i():
# just a reminder that ratios of powers only simplify if both
# numerator and denominator satisfy the condition that each
# has a positive base or an integer exponent; e.g. the following,
# at y=-1, x=1/2 gives sqrt(2)*I != -sqrt(2)*I
assert powsimp(2**x/y**x) != (2/y)**x
assert TR2i(sin(x)/cos(x)) == tan(x)
assert TR2i(sin(x)*sin(y)/cos(x)) == tan(x)*sin(y)
assert TR2i(1/(sin(x)/cos(x))) == 1/tan(x)
assert TR2i(1/(sin(x)*sin(y)/cos(x))) == 1/tan(x)/sin(y)
assert TR2i(sin(x)/2/(cos(x) + 1)) == sin(x)/(cos(x) + 1)/2
assert TR2i(sin(x)/2/(cos(x) + 1), half=True) == tan(x/2)/2
assert TR2i(sin(1)/(cos(1) + 1), half=True) == tan(S.Half)
assert TR2i(sin(2)/(cos(2) + 1), half=True) == tan(1)
assert TR2i(sin(4)/(cos(4) + 1), half=True) == tan(2)
assert TR2i(sin(5)/(cos(5) + 1), half=True) == tan(5*S.Half)
assert TR2i((cos(1) + 1)/sin(1), half=True) == 1/tan(S.Half)
assert TR2i((cos(2) + 1)/sin(2), half=True) == 1/tan(1)
assert TR2i((cos(4) + 1)/sin(4), half=True) == 1/tan(2)
assert TR2i((cos(5) + 1)/sin(5), half=True) == 1/tan(5*S.Half)
assert TR2i((cos(1) + 1)**(-a)*sin(1)**a, half=True) == tan(S.Half)**a
assert TR2i((cos(2) + 1)**(-a)*sin(2)**a, half=True) == tan(1)**a
assert TR2i((cos(4) + 1)**(-a)*sin(4)**a, half=True) == (cos(4) + 1)**(-a)*sin(4)**a
assert TR2i((cos(5) + 1)**(-a)*sin(5)**a, half=True) == (cos(5) + 1)**(-a)*sin(5)**a
assert TR2i((cos(1) + 1)**a*sin(1)**(-a), half=True) == tan(S.Half)**(-a)
assert TR2i((cos(2) + 1)**a*sin(2)**(-a), half=True) == tan(1)**(-a)
assert TR2i((cos(4) + 1)**a*sin(4)**(-a), half=True) == (cos(4) + 1)**a*sin(4)**(-a)
assert TR2i((cos(5) + 1)**a*sin(5)**(-a), half=True) == (cos(5) + 1)**a*sin(5)**(-a)
i = symbols('i', integer=True)
assert TR2i(((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**(-i)
assert TR2i(1/((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**i
def test_TR3():
assert TR3(cos(y - x*(y - x))) == cos(x*(x - y) + y)
assert cos(pi/2 + x) == -sin(x)
assert cos(30*pi/2 + x) == -cos(x)
for f in (cos, sin, tan, cot, csc, sec):
i = f(pi*Rational(3, 7))
j = TR3(i)
assert verify_numerically(i, j) and i.func != j.func
def test__TR56():
h = lambda x: 1 - x
assert T(sin(x)**3, sin, cos, h, 4, False) == sin(x)**3
assert T(sin(x)**10, sin, cos, h, 4, False) == sin(x)**10
assert T(sin(x)**6, sin, cos, h, 6, False) == (-cos(x)**2 + 1)**3
assert T(sin(x)**6, sin, cos, h, 6, True) == sin(x)**6
assert T(sin(x)**8, sin, cos, h, 10, True) == (-cos(x)**2 + 1)**4
# issue 17137
assert T(sin(x)**I, sin, cos, h, 4, True) == sin(x)**I
assert T(sin(x)**(2*I + 1), sin, cos, h, 4, True) == sin(x)**(2*I + 1)
def test_TR5():
assert TR5(sin(x)**2) == -cos(x)**2 + 1
assert TR5(sin(x)**-2) == sin(x)**(-2)
assert TR5(sin(x)**4) == (-cos(x)**2 + 1)**2
def test_TR6():
assert TR6(cos(x)**2) == -sin(x)**2 + 1
assert TR6(cos(x)**-2) == cos(x)**(-2)
assert TR6(cos(x)**4) == (-sin(x)**2 + 1)**2
def test_TR7():
assert TR7(cos(x)**2) == cos(2*x)/2 + S.Half
assert TR7(cos(x)**2 + 1) == cos(2*x)/2 + Rational(3, 2)
def test_TR8():
assert TR8(cos(2)*cos(3)) == cos(5)/2 + cos(1)/2
assert TR8(cos(2)*sin(3)) == sin(5)/2 + sin(1)/2
assert TR8(sin(2)*sin(3)) == -cos(5)/2 + cos(1)/2
assert TR8(sin(1)*sin(2)*sin(3)) == sin(4)/4 - sin(6)/4 + sin(2)/4
assert TR8(cos(2)*cos(3)*cos(4)*cos(5)) == \
cos(4)/4 + cos(10)/8 + cos(2)/8 + cos(8)/8 + cos(14)/8 + \
cos(6)/8 + Rational(1, 8)
assert TR8(cos(2)*cos(3)*cos(4)*cos(5)*cos(6)) == \
cos(10)/8 + cos(4)/8 + 3*cos(2)/16 + cos(16)/16 + cos(8)/8 + \
cos(14)/16 + cos(20)/16 + cos(12)/16 + Rational(1, 16) + cos(6)/8
assert TR8(sin(pi*Rational(3, 7))**2*cos(pi*Rational(3, 7))**2/(16*sin(pi/7)**2)) == Rational(1, 64)
def test_TR9():
a = S.Half
b = 3*a
assert TR9(a) == a
assert TR9(cos(1) + cos(2)) == 2*cos(a)*cos(b)
assert TR9(cos(1) - cos(2)) == 2*sin(a)*sin(b)
assert TR9(sin(1) - sin(2)) == -2*sin(a)*cos(b)
assert TR9(sin(1) + sin(2)) == 2*sin(b)*cos(a)
assert TR9(cos(1) + 2*sin(1) + 2*sin(2)) == cos(1) + 4*sin(b)*cos(a)
assert TR9(cos(4) + cos(2) + 2*cos(1)*cos(3)) == 4*cos(1)*cos(3)
assert TR9((cos(4) + cos(2))/cos(3)/2 + cos(3)) == 2*cos(1)*cos(2)
assert TR9(cos(3) + cos(4) + cos(5) + cos(6)) == \
4*cos(S.Half)*cos(1)*cos(Rational(9, 2))
assert TR9(cos(3) + cos(3)*cos(2)) == cos(3) + cos(2)*cos(3)
assert TR9(-cos(y) + cos(x*y)) == -2*sin(x*y/2 - y/2)*sin(x*y/2 + y/2)
assert TR9(-sin(y) + sin(x*y)) == 2*sin(x*y/2 - y/2)*cos(x*y/2 + y/2)
c = cos(x)
s = sin(x)
for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
for a in ((c, s), (s, c), (cos(x), cos(x*y)), (sin(x), sin(x*y))):
args = zip(si, a)
ex = Add(*[Mul(*ai) for ai in args])
t = TR9(ex)
assert not (a[0].func == a[1].func and (
not verify_numerically(ex, t.expand(trig=True)) or t.is_Add)
or a[1].func != a[0].func and ex != t)
def test_TR10():
assert TR10(cos(a + b)) == -sin(a)*sin(b) + cos(a)*cos(b)
assert TR10(sin(a + b)) == sin(a)*cos(b) + sin(b)*cos(a)
assert 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)
assert TR10(cos(a + b + c)) == \
(-sin(a)*sin(b) + cos(a)*cos(b))*cos(c) - \
(sin(a)*cos(b) + sin(b)*cos(a))*sin(c)
def test_TR10i():
assert TR10i(cos(1)*cos(3) + sin(1)*sin(3)) == cos(2)
assert TR10i(cos(1)*cos(3) - sin(1)*sin(3)) == cos(4)
assert TR10i(cos(1)*sin(3) - sin(1)*cos(3)) == sin(2)
assert TR10i(cos(1)*sin(3) + sin(1)*cos(3)) == sin(4)
assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + 7) == sin(4) + 7
assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3)) == cos(3) + sin(4)
assert TR10i(2*cos(1)*sin(3) + 2*sin(1)*cos(3) + cos(3)) == \
2*sin(4) + cos(3)
assert TR10i(cos(2)*cos(3) + sin(2)*(cos(1)*sin(2) + cos(2)*sin(1))) == \
cos(1)
eq = (cos(2)*cos(3) + sin(2)*(
cos(1)*sin(2) + cos(2)*sin(1)))*cos(5) + sin(1)*sin(5)
assert TR10i(eq) == TR10i(eq.expand()) == cos(4)
assert TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x) == \
2*sqrt(2)*x*sin(x + pi/6)
assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) +
cos(x)/sqrt(6)/3 + sin(x)/sqrt(2)/3) == 4*sqrt(6)*sin(x + pi/6)/9
assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) +
cos(y)/sqrt(6)/3 + sin(y)/sqrt(2)/3) == \
sqrt(6)*sin(x + pi/6)/3 + sqrt(6)*sin(y + pi/6)/9
assert TR10i(cos(x) + sqrt(3)*sin(x) + 2*sqrt(3)*cos(x + pi/6)) == 4*cos(x)
assert TR10i(cos(x) + sqrt(3)*sin(x) +
2*sqrt(3)*cos(x + pi/6) + 4*sin(x)) == 4*sqrt(2)*sin(x + pi/4)
assert TR10i(cos(2)*sin(3) + sin(2)*cos(4)) == \
sin(2)*cos(4) + sin(3)*cos(2)
A = Symbol('A', commutative=False)
assert TR10i(sqrt(2)*cos(x)*A + sqrt(6)*sin(x)*A) == \
2*sqrt(2)*sin(x + pi/6)*A
c = cos(x)
s = sin(x)
h = sin(y)
r = cos(y)
for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
for argsi in ((c*r, s*h), (c*h, s*r)): # explicit 2-args
args = zip(si, argsi)
ex = Add(*[Mul(*ai) for ai in args])
t = TR10i(ex)
assert not (ex - t.expand(trig=True) or t.is_Add)
c = cos(x)
s = sin(x)
h = sin(pi/6)
r = cos(pi/6)
for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
for argsi in ((c*r, s*h), (c*h, s*r)): # induced
args = zip(si, argsi)
ex = Add(*[Mul(*ai) for ai in args])
t = TR10i(ex)
assert not (ex - t.expand(trig=True) or t.is_Add)
def test_TR11():
assert TR11(sin(2*x)) == 2*sin(x)*cos(x)
assert TR11(sin(4*x)) == 4*((-sin(x)**2 + cos(x)**2)*sin(x)*cos(x))
assert TR11(sin(x*Rational(4, 3))) == \
4*((-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3))
assert TR11(cos(2*x)) == -sin(x)**2 + cos(x)**2
assert TR11(cos(4*x)) == \
(-sin(x)**2 + cos(x)**2)**2 - 4*sin(x)**2*cos(x)**2
assert TR11(cos(2)) == cos(2)
assert TR11(cos(pi*Rational(3, 7)), pi*Rational(2, 7)) == -cos(pi*Rational(2, 7))**2 + sin(pi*Rational(2, 7))**2
assert TR11(cos(4), 2) == -sin(2)**2 + cos(2)**2
assert TR11(cos(6), 2) == cos(6)
assert TR11(sin(x)/cos(x/2), x/2) == 2*sin(x/2)
def test__TR11():
assert _TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8))) == \
4*sin(x/8)*sin(x/6)*sin(2*x),_TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8)))
assert _TR11(sin(x/3)/cos(x/6)) == 2*sin(x/6)
assert _TR11(cos(x/6)/sin(x/3)) == 1/(2*sin(x/6))
assert _TR11(sin(2*x)*cos(x/8)/sin(x/4)) == sin(2*x)/(2*sin(x/8)), _TR11(sin(2*x)*cos(x/8)/sin(x/4))
assert _TR11(sin(x)/sin(x/2)) == 2*cos(x/2)
def test_TR12():
assert TR12(tan(x + y)) == (tan(x) + tan(y))/(-tan(x)*tan(y) + 1)
assert TR12(tan(x + y + z)) ==\
(tan(z) + (tan(x) + tan(y))/(-tan(x)*tan(y) + 1))/(
1 - (tan(x) + tan(y))*tan(z)/(-tan(x)*tan(y) + 1))
assert TR12(tan(x*y)) == tan(x*y)
def test_TR13():
assert TR13(tan(3)*tan(2)) == -tan(2)/tan(5) - tan(3)/tan(5) + 1
assert TR13(cot(3)*cot(2)) == 1 + cot(3)*cot(5) + cot(2)*cot(5)
assert TR13(tan(1)*tan(2)*tan(3)) == \
(-tan(2)/tan(5) - tan(3)/tan(5) + 1)*tan(1)
assert TR13(tan(1)*tan(2)*cot(3)) == \
(-tan(2)/tan(3) + 1 - tan(1)/tan(3))*cot(3)
def test_L():
assert L(cos(x) + sin(x)) == 2
def test_fu():
assert fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) == Rational(3, 2)
assert fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) == 2*sqrt(2)*sin(x + pi/3)
eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2
assert fu(eq) == cos(x)**4 - 2*cos(y)**2 + 2
assert fu(S.Half - cos(2*x)/2) == sin(x)**2
assert fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b))) == \
sqrt(2)*sin(a + b + pi/4)
assert fu(sqrt(3)*cos(x)/2 + sin(x)/2) == sin(x + pi/3)
assert fu(1 - sin(2*x)**2/4 - sin(y)**2 - cos(x)**4) == \
-cos(x)**2 + cos(y)**2
assert fu(cos(pi*Rational(4, 9))) == sin(pi/18)
assert fu(cos(pi/9)*cos(pi*Rational(2, 9))*cos(pi*Rational(3, 9))*cos(pi*Rational(4, 9))) == Rational(1, 16)
assert fu(
tan(pi*Rational(7, 18)) + tan(pi*Rational(5, 18)) - sqrt(3)*tan(pi*Rational(5, 18))*tan(pi*Rational(7, 18))) == \
-sqrt(3)
assert fu(tan(1)*tan(2)) == tan(1)*tan(2)
expr = Mul(*[cos(2**i) for i in range(10)])
assert fu(expr) == sin(1024)/(1024*sin(1))
# issue #18059:
assert fu(cos(x) + sqrt(sin(x)**2)) == cos(x) + sqrt(sin(x)**2)
def test_objective():
assert fu(sin(x)/cos(x), measure=lambda x: x.count_ops()) == \
tan(x)
assert fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) == \
sin(x)/cos(x)
def test_process_common_addends():
# this tests that the args are not evaluated as they are given to do
# and that key2 works when key1 is False
do = lambda x: Add(*[i**(i%2) for i in x.args])
process_common_addends(Add(*[1, 2, 3, 4], evaluate=False), do,
key2=lambda x: x%2, key1=False) == 1**1 + 3**1 + 2**0 + 4**0
def test_trig_split():
assert trig_split(cos(x), cos(y)) == (1, 1, 1, x, y, True)
assert trig_split(2*cos(x), -2*cos(y)) == (2, 1, -1, x, y, True)
assert trig_split(cos(x)*sin(y), cos(y)*sin(y)) == \
(sin(y), 1, 1, x, y, True)
assert trig_split(cos(x), -sqrt(3)*sin(x), two=True) == \
(2, 1, -1, x, pi/6, False)
assert trig_split(cos(x), sin(x), two=True) == \
(sqrt(2), 1, 1, x, pi/4, False)
assert trig_split(cos(x), -sin(x), two=True) == \
(sqrt(2), 1, -1, x, pi/4, False)
assert trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) == \
(2*sqrt(2), 1, -1, x, pi/6, False)
assert trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) == \
(-2*sqrt(2), 1, 1, x, pi/3, False)
assert trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) == \
(sqrt(6)/3, 1, 1, x, pi/6, False)
assert 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)
assert trig_split(cos(x), sin(x)) is None
assert trig_split(cos(x), sin(z)) is None
assert trig_split(2*cos(x), -sin(x)) is None
assert trig_split(cos(x), -sqrt(3)*sin(x)) is None
assert trig_split(cos(x)*cos(y), sin(x)*sin(z)) is None
assert trig_split(cos(x)*cos(y), sin(x)*sin(y)) is None
assert trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) is \
None
assert trig_split(sqrt(3)*sqrt(x), cos(3), two=True) is None
assert trig_split(sqrt(3)*root(x, 3), sin(3)*cos(2), two=True) is None
assert trig_split(cos(5)*cos(6), cos(7)*sin(5), two=True) is None
def test_TRmorrie():
assert TRmorrie(7*Mul(*[cos(i) for i in range(10)])) == \
7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3))
assert TRmorrie(x) == x
assert TRmorrie(2*x) == 2*x
e = cos(pi/7)*cos(pi*Rational(2, 7))*cos(pi*Rational(4, 7))
assert TR8(TRmorrie(e)) == Rational(-1, 8)
e = Mul(*[cos(2**i*pi/17) for i in range(1, 17)])
assert TR8(TR3(TRmorrie(e))) == Rational(1, 65536)
# issue 17063
eq = cos(x)/cos(x/2)
assert TRmorrie(eq) == eq
# issue #20430
eq = cos(x/2)*sin(x/2)*cos(x)**3
assert TRmorrie(eq) == sin(2*x)*cos(x)**2/4
def test_TRpower():
assert TRpower(1/sin(x)**2) == 1/sin(x)**2
assert TRpower(cos(x)**3*sin(x/2)**4) == \
(3*cos(x)/4 + cos(3*x)/4)*(-cos(x)/2 + cos(2*x)/8 + Rational(3, 8))
for k in range(2, 8):
assert verify_numerically(sin(x)**k, TRpower(sin(x)**k))
assert verify_numerically(cos(x)**k, TRpower(cos(x)**k))
def test_hyper_as_trig():
from sympy.simplify.fu import _osborne as o, _osbornei as i, TR12
eq = sinh(x)**2 + cosh(x)**2
t, f = hyper_as_trig(eq)
assert f(fu(t)) == cosh(2*x)
e, f = hyper_as_trig(tanh(x + y))
assert f(TR12(e)) == (tanh(x) + tanh(y))/(tanh(x)*tanh(y) + 1)
d = Dummy()
assert o(sinh(x), d) == I*sin(x*d)
assert o(tanh(x), d) == I*tan(x*d)
assert o(coth(x), d) == cot(x*d)/I
assert o(cosh(x), d) == cos(x*d)
assert o(sech(x), d) == sec(x*d)
assert o(csch(x), d) == csc(x*d)/I
for func in (sinh, cosh, tanh, coth, sech, csch):
h = func(pi)
assert i(o(h, d), d) == h
# /!\ the _osborne functions are not meant to work
# in the o(i(trig, d), d) direction so we just check
# that they work as they are supposed to work
assert i(cos(x*y + z), y) == cosh(x + z*I)
assert i(sin(x*y + z), y) == sinh(x + z*I)/I
assert i(tan(x*y + z), y) == tanh(x + z*I)/I
assert i(cot(x*y + z), y) == coth(x + z*I)*I
assert i(sec(x*y + z), y) == sech(x + z*I)
assert i(csc(x*y + z), y) == csch(x + z*I)*I
def test_TR12i():
ta, tb, tc = [tan(i) for i in (a, b, c)]
assert TR12i((ta + tb)/(-ta*tb + 1)) == tan(a + b)
assert TR12i((ta + tb)/(ta*tb - 1)) == -tan(a + b)
assert TR12i((-ta - tb)/(ta*tb - 1)) == tan(a + b)
eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1))
assert TR12i(eq.expand()) == \
-3*tan(a + b)*tan(a + c)/(tan(a) + tan(b) - 1)/2
assert TR12i(tan(x)/sin(x)) == tan(x)/sin(x)
eq = (ta + cos(2))/(-ta*tb + 1)
assert TR12i(eq) == eq
eq = (ta + tb + 2)**2/(-ta*tb + 1)
assert TR12i(eq) == eq
eq = ta/(-ta*tb + 1)
assert TR12i(eq) == eq
eq = (((ta + tb)*(a + 1)).expand())**2/(ta*tb - 1)
assert TR12i(eq) == -(a + 1)**2*tan(a + b)
def test_TR14():
eq = (cos(x) - 1)*(cos(x) + 1)
ans = -sin(x)**2
assert TR14(eq) == ans
assert TR14(1/eq) == 1/ans
assert TR14((cos(x) - 1)**2*(cos(x) + 1)**2) == ans**2
assert TR14((cos(x) - 1)**2*(cos(x) + 1)**3) == ans**2*(cos(x) + 1)
assert TR14((cos(x) - 1)**3*(cos(x) + 1)**2) == ans**2*(cos(x) - 1)
eq = (cos(x) - 1)**y*(cos(x) + 1)**y
assert TR14(eq) == eq
eq = (cos(x) - 2)**y*(cos(x) + 1)
assert TR14(eq) == eq
eq = (tan(x) - 2)**2*(cos(x) + 1)
assert TR14(eq) == eq
i = symbols('i', integer=True)
assert TR14((cos(x) - 1)**i*(cos(x) + 1)**i) == ans**i
assert TR14((sin(x) - 1)**i*(sin(x) + 1)**i) == (-cos(x)**2)**i
# could use extraction in this case
eq = (cos(x) - 1)**(i + 1)*(cos(x) + 1)**i
assert TR14(eq) in [(cos(x) - 1)*ans**i, eq]
assert 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))
assert TR14(p1*p2*p3*(x - 1)) == -18*((x - 1)*sin(x)**2*sin(y)**4)
def test_TR15_16_17():
assert TR15(1 - 1/sin(x)**2) == -cot(x)**2
assert TR16(1 - 1/cos(x)**2) == -tan(x)**2
assert TR111(1 - 1/tan(x)**2) == 1 - cot(x)**2
def test_as_f_sign_1():
assert as_f_sign_1(x + 1) == (1, x, 1)
assert as_f_sign_1(x - 1) == (1, x, -1)
assert as_f_sign_1(-x + 1) == (-1, x, -1)
assert as_f_sign_1(-x - 1) == (-1, x, 1)
assert as_f_sign_1(2*x + 2) == (2, x, 1)
assert as_f_sign_1(x*y - y) == (y, x, -1)
assert as_f_sign_1(-x*y + y) == (-y, x, -1)
|
5084e3319a53e2bc509b0046456bf57cdc3bc06aaab6a671643e7b5e79bce86d | from sympy import (
Abs, acos, Add, asin, atan, Basic, binomial, besselsimp,
cos, cosh, count_ops, csch, diff, E,
Eq, erf, exp, exp_polar, expand, expand_multinomial, factor,
factorial, Float, Function, gamma, GoldenRatio, hyper,
hypersimp, I, Integral, integrate, KroneckerDelta, log, logcombine, Lt,
Matrix, MatrixSymbol, Mul, nsimplify, oo, pi, Piecewise, Poly, posify, rad,
Rational, S, separatevars, signsimp, simplify, sign, sin,
sinc, sinh, solve, sqrt, Sum, Symbol, symbols, sympify, tan,
zoo)
from sympy.core.mul import _keep_coeff
from sympy.core.expr import unchanged
from sympy.simplify.simplify import nthroot, inversecombine
from sympy.testing.pytest import XFAIL, slow
from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i
def test_issue_7263():
assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \
673.447451402970) < 1e-12
def test_factorial_simplify():
# There are more tests in test_factorials.py.
x = Symbol('x')
assert simplify(factorial(x)/x) == gamma(x)
assert simplify(factorial(factorial(x))) == factorial(factorial(x))
def test_simplify_expr():
x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A')
f = Function('f')
assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I])
e = 1/x + 1/y
assert e != (x + y)/(x*y)
assert simplify(e) == (x + y)/(x*y)
e = A**2*s**4/(4*pi*k*m**3)
assert simplify(e) == e
e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x)
assert simplify(e) == 0
e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2
assert simplify(e) == -2*y
e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2
assert simplify(e) == -2*y
e = (x + x*y)/x
assert simplify(e) == 1 + y
e = (f(x) + y*f(x))/f(x)
assert simplify(e) == 1 + y
e = (2 * (1/n - cos(n * pi)/n))/pi
assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2
e = integrate(1/(x**3 + 1), x).diff(x)
assert simplify(e) == 1/(x**3 + 1)
e = integrate(x/(x**2 + 3*x + 1), x).diff(x)
assert simplify(e) == x/(x**2 + 3*x + 1)
f = Symbol('f')
A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv()
assert simplify((A*Matrix([0, f]))[1] -
(-f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)))) == 0
f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t)
assert simplify(f) == (y + a*z)/(z + t)
# issue 10347
expr = -x*(y**2 - 1)*(2*y**2*(x**2 - 1)/(a*(x**2 - y**2)**2) + (x**2 - 1)
/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2
+ y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 +
y**2 - 1)*sin(z)/(a*(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*
(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(x**2 - 1) + sqrt(
(-x**2 + 1)*(y**2 - 1))*(x*(-x*y**2 + x)/sqrt(-x**2*y**2 + x**2 + y**2 -
1) + sqrt(-x**2*y**2 + x**2 + y**2 - 1))*sin(z))/(a*sqrt((-x**2 + 1)*(
y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*
(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*
(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*
(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2
*y**2 + x**2 + y**2 - 1)*cos(z)/(x**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 -
1))*(-x*y**2 + x)*cos(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt((-x**2
+ 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z))/(a*sqrt((-x**2
+ 1)*(y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(
z)/(a*(x**2 - y**2)) - y*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y*sqrt(-x**2*
y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt(
-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) + (x*y*sqrt((
-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(y**2 -
1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*sin(z)/sqrt(-x**2*y**2
+ x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sin(
z)/(a*(x**2 - y**2)) + y*(x**2 - 1)*(-2*x*y*(x**2 - 1)/(a*(x**2 - y**2)
**2) + 2*x*y/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + y*(x**2 - 1)*(y**2 -
1)*(-x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)*(y**2
- 1)) + 2*x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)
**2) + (x*y*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 -
1)*cos(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*cos(
z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1)
)*(x**2 - y**2)))*cos(z)/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)
) - x*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(
z)**2/(a**2*(x**2 - 1)*(x**2 - y**2)*(y**2 - 1)) - x*sqrt((-x**2 + 1)*(
y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)**2/(a**2*(x**2 - 1)*(
x**2 - y**2)*(y**2 - 1))
assert simplify(expr) == 2*x/(a**2*(x**2 - y**2))
#issue 17631
assert simplify('((-1/2)*Boole(True)*Boole(False)-1)*Boole(True)') == \
Mul(sympify('(2 + Boole(True)*Boole(False))'), sympify('-Boole(True)/2'))
A, B = symbols('A,B', commutative=False)
assert simplify(A*B - B*A) == A*B - B*A
assert simplify(A/(1 + y/x)) == x*A/(x + y)
assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y)
assert simplify(log(2) + log(3)) == log(6)
assert simplify(log(2*x) - log(2)) == log(x)
assert simplify(hyper([], [], x)) == exp(x)
def test_issue_3557():
f_1 = x*a + y*b + z*c - 1
f_2 = x*d + y*e + z*f - 1
f_3 = x*g + y*h + z*i - 1
solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False)
assert simplify(solutions[y]) == \
(a*i + c*d + f*g - a*f - c*g - d*i)/ \
(a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g)
def test_simplify_other():
assert simplify(sin(x)**2 + cos(x)**2) == 1
assert simplify(gamma(x + 1)/gamma(x)) == x
assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x
assert simplify(
Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(x, 1)
nc = symbols('nc', commutative=False)
assert simplify(x + x*nc) == x*(1 + nc)
# issue 6123
# f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2)
# ans = integrate(f, (k, -oo, oo), conds='none')
ans = I*(-pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))*erf(x*exp(I*pi*Rational(-3, 4))/
(2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))/
(2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * \
(-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t))
assert simplify(ans) == -(-1)**Rational(3, 4)*sqrt(pi)/sqrt(t)
# issue 6370
assert simplify(2**(2 + x)/4) == 2**x
def test_simplify_complex():
cosAsExp = cos(x)._eval_rewrite_as_exp(x)
tanAsExp = tan(x)._eval_rewrite_as_exp(x)
assert simplify(cosAsExp*tanAsExp) == sin(x) # issue 4341
# issue 10124
assert simplify(exp(Matrix([[0, -1], [1, 0]]))) == Matrix([[cos(1),
-sin(1)], [sin(1), cos(1)]])
def test_simplify_ratio():
# roots of x**3-3*x+5
roots = ['(1/2 - sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3) + 1/((1/2 - '
'sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3))',
'1/((1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)) + '
'(1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)',
'-(sqrt(21)/2 + 5/2)**(1/3) - 1/(sqrt(21)/2 + 5/2)**(1/3)']
for r in roots:
r = S(r)
assert count_ops(simplify(r, ratio=1)) <= count_ops(r)
# If ratio=oo, simplify() is always applied:
assert simplify(r, ratio=oo) is not r
def test_simplify_measure():
measure1 = lambda expr: len(str(expr))
measure2 = lambda expr: -count_ops(expr)
# Return the most complicated result
expr = (x + 1)/(x + sin(x)**2 + cos(x)**2)
assert measure1(simplify(expr, measure=measure1)) <= measure1(expr)
assert measure2(simplify(expr, measure=measure2)) <= measure2(expr)
expr2 = Eq(sin(x)**2 + cos(x)**2, 1)
assert measure1(simplify(expr2, measure=measure1)) <= measure1(expr2)
assert measure2(simplify(expr2, measure=measure2)) <= measure2(expr2)
def test_simplify_rational():
expr = 2**x*2.**y
assert simplify(expr, rational = True) == 2**(x+y)
assert simplify(expr, rational = None) == 2.0**(x+y)
assert simplify(expr, rational = False) == expr
def test_simplify_issue_1308():
assert simplify(exp(Rational(-1, 2)) + exp(Rational(-3, 2))) == \
(1 + E)*exp(Rational(-3, 2))
def test_issue_5652():
assert simplify(E + exp(-E)) == exp(-E) + E
n = symbols('n', commutative=False)
assert simplify(n + n**(-n)) == n + n**(-n)
def test_simplify_fail1():
x = Symbol('x')
y = Symbol('y')
e = (x + y)**2/(-4*x*y**2 - 2*y**3 - 2*x**2*y)
assert simplify(e) == 1 / (-2*y)
def test_nthroot():
assert nthroot(90 + 34*sqrt(7), 3) == sqrt(7) + 3
q = 1 + sqrt(2) - 2*sqrt(3) + sqrt(6) + sqrt(7)
assert nthroot(expand_multinomial(q**3), 3) == q
assert nthroot(41 + 29*sqrt(2), 5) == 1 + sqrt(2)
assert nthroot(-41 - 29*sqrt(2), 5) == -1 - sqrt(2)
expr = 1320*sqrt(10) + 4216 + 2576*sqrt(6) + 1640*sqrt(15)
assert nthroot(expr, 5) == 1 + sqrt(6) + sqrt(15)
q = 1 + sqrt(2) + sqrt(3) + sqrt(5)
assert expand_multinomial(nthroot(expand_multinomial(q**5), 5)) == q
q = 1 + sqrt(2) + 7*sqrt(6) + 2*sqrt(10)
assert nthroot(expand_multinomial(q**5), 5, 8) == q
q = 1 + sqrt(2) - 2*sqrt(3) + 1171*sqrt(6)
assert nthroot(expand_multinomial(q**3), 3) == q
assert nthroot(expand_multinomial(q**6), 6) == q
def test_nthroot1():
q = 1 + sqrt(2) + sqrt(3) + S.One/10**20
p = expand_multinomial(q**5)
assert nthroot(p, 5) == q
q = 1 + sqrt(2) + sqrt(3) + S.One/10**30
p = expand_multinomial(q**5)
assert nthroot(p, 5) == q
def test_separatevars():
x, y, z, n = symbols('x,y,z,n')
assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y)
assert separatevars(x*z + x*y*z) == x*z*(1 + y)
assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y)
assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \
x*(sin(y) + y**2)*sin(x)
assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x)
assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z
assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1)
assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \
y*exp(x/cos(n))*exp(-z/cos(n))/pi
assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2
# issue 4858
p = Symbol('p', positive=True)
assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x)
assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x))
assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \
p*sqrt(y)*sqrt(1 + x)
# issue 4865
assert separatevars(sqrt(x*y)).is_Pow
assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y)
# issue 4957
# any type sequence for symbols is fine
assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \
{'coeff': 1, x: 2*x + 2, y: y}
# separable
assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \
{'coeff': y, x: 2*x + 2}
assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \
{'coeff': 1, x: 2*x + 2, y: y}
assert separatevars(((2*x + 2)*y), dict=True) == \
{'coeff': 1, x: 2*x + 2, y: y}
assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \
{'coeff': y*(2*x + 2)}
# not separable
assert separatevars(3, dict=True) is None
assert separatevars(2*x + y, dict=True, symbols=()) is None
assert separatevars(2*x + y, dict=True) is None
assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y}
# issue 4808
n, m = symbols('n,m', commutative=False)
assert separatevars(m + n*m) == (1 + n)*m
assert separatevars(x + x*n) == x*(1 + n)
# issue 4910
f = Function('f')
assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x)
# a noncommutable object present
eq = x*(1 + hyper((), (), y*z))
assert separatevars(eq) == eq
s = separatevars(abs(x*y))
assert s == abs(x)*abs(y) and s.is_Mul
z = cos(1)**2 + sin(1)**2 - 1
a = abs(x*z)
s = separatevars(a)
assert not a.is_Mul and s.is_Mul and s == abs(x)*abs(z)
s = separatevars(abs(x*y*z))
assert s == abs(x)*abs(y)*abs(z)
# abs(x+y)/abs(z) would be better but we test this here to
# see that it doesn't raise
assert separatevars(abs((x+y)/z)) == abs((x+y)/z)
def test_separatevars_advanced_factor():
x, y, z = symbols('x,y,z')
assert separatevars(1 + log(x)*log(y) + log(x) + log(y)) == \
(log(x) + 1)*(log(y) + 1)
assert separatevars(1 + x - log(z) - x*log(z) - exp(y)*log(z) -
x*exp(y)*log(z) + x*exp(y) + exp(y)) == \
-((x + 1)*(log(z) - 1)*(exp(y) + 1))
x, y = symbols('x,y', positive=True)
assert separatevars(1 + log(x**log(y)) + log(x*y)) == \
(log(x) + 1)*(log(y) + 1)
def test_hypersimp():
n, k = symbols('n,k', integer=True)
assert hypersimp(factorial(k), k) == k + 1
assert hypersimp(factorial(k**2), k) is None
assert hypersimp(1/factorial(k), k) == 1/(k + 1)
assert hypersimp(2**k/factorial(k)**2, k) == 2/(k + 1)**2
assert hypersimp(binomial(n, k), k) == (n - k)/(k + 1)
assert hypersimp(binomial(n + 1, k), k) == (n - k + 1)/(k + 1)
term = (4*k + 1)*factorial(k)/factorial(2*k + 1)
assert hypersimp(term, k) == S.Half*((4*k + 5)/(3 + 14*k + 8*k**2))
term = 1/((2*k - 1)*factorial(2*k + 1))
assert hypersimp(term, k) == (k - S.Half)/((k + 1)*(2*k + 1)*(2*k + 3))
term = binomial(n, k)*(-1)**k/factorial(k)
assert hypersimp(term, k) == (k - n)/(k + 1)**2
def test_nsimplify():
x = Symbol("x")
assert nsimplify(0) == 0
assert nsimplify(-1) == -1
assert nsimplify(1) == 1
assert nsimplify(1 + x) == 1 + x
assert nsimplify(2.7) == Rational(27, 10)
assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
assert nsimplify(exp(pi*I*Rational(5, 3), evaluate=False)) == \
sympify('1/2 - sqrt(3)*I/2')
assert nsimplify(sin(pi*Rational(3, 5), evaluate=False)) == \
sympify('sqrt(sqrt(5)/8 + 5/8)')
assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
sqrt(pi) + sqrt(pi)/2*I
assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
2**Rational(1, 3)
assert nsimplify(x + .5, rational=True) == S.Half + x
assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
assert nsimplify(log(3).n(), rational=True) == \
sympify('109861228866811/100000000000000')
assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8
assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
-pi/4 - log(2) + Rational(7, 4)
assert nsimplify(x/7.0) == x/7
assert nsimplify(pi/1e2) == pi/100
assert nsimplify(pi/1e2, rational=False) == pi/100.0
assert nsimplify(pi/1e-7) == 10000000*pi
assert not nsimplify(
factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)
e = x**0.0
assert e.is_Pow and nsimplify(x**0.0) == 1
assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3)
assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3)
assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
assert nsimplify(-203.1) == Rational(-2031, 10)
assert nsimplify(.2, tolerance=0) == Rational(1, 5)
assert nsimplify(-.2, tolerance=0) == Rational(-1, 5)
assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000)
assert nsimplify(-.2222, tolerance=0) == Rational(-1111, 5000)
# issue 7211, PR 4112
assert nsimplify(S(2e-8)) == Rational(1, 50000000)
# issue 7322 direct test
assert nsimplify(1e-42, rational=True) != 0
# issue 10336
inf = Float('inf')
infs = (-oo, oo, inf, -inf)
for zi in infs:
ans = sign(zi)*oo
assert nsimplify(zi) == ans
assert nsimplify(zi + x) == x + ans
assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333)
# Make sure nsimplify on expressions uses full precision
assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x
def test_issue_9448():
tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))")
assert nsimplify(tmp) == S.Half
def test_extract_minus_sign():
x = Symbol("x")
y = Symbol("y")
a = Symbol("a")
b = Symbol("b")
assert simplify(-x/-y) == x/y
assert simplify(-x/y) == -x/y
assert simplify(x/y) == x/y
assert simplify(x/-y) == -x/y
assert simplify(-x/0) == zoo*x
assert simplify(Rational(-5, 0)) is zoo
assert simplify(-a*x/(-y - b)) == a*x/(b + y)
def test_diff():
x = Symbol("x")
y = Symbol("y")
f = Function("f")
g = Function("g")
assert simplify(g(x).diff(x)*f(x).diff(x) - f(x).diff(x)*g(x).diff(x)) == 0
assert simplify(2*f(x)*f(x).diff(x) - diff(f(x)**2, x)) == 0
assert simplify(diff(1/f(x), x) + f(x).diff(x)/f(x)**2) == 0
assert simplify(f(x).diff(x, y) - f(x).diff(y, x)) == 0
def test_logcombine_1():
x, y = symbols("x,y")
a = Symbol("a")
z, w = symbols("z,w", positive=True)
b = Symbol("b", real=True)
assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y)
assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2)
assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z)
assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x)
assert logcombine(b*log(z) - log(w)) == log(z**b/w)
assert logcombine(log(x)*log(z)) == log(x)*log(z)
assert logcombine(log(w)*log(x)) == log(w)*log(x)
assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)),
cos(log(z**2/w**b))]
assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \
log(log(x/y)/z)
assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x)
assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \
(x**2 + log(x/y))/(x*y)
# the following could also give log(z*x**log(y**2)), what we
# are testing is that a canonical result is obtained
assert logcombine(log(x)*2*log(y) + log(z), force=True) == \
log(z*y**log(x**2))
assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)*
sqrt(y)**3), force=True) == (
x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**Rational(2, 3)*y**Rational(3, 2))
assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \
acos(-log(x/y))*gamma(-log(x/y))
assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \
log(z**log(w**2))*log(x) + log(w*z)
assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3)
assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6)
assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3)
# a single unknown can combine
assert logcombine(log(x) + log(2)) == log(2*x)
eq = log(abs(x)) + log(abs(y))
assert logcombine(eq) == eq
reps = {x: 0, y: 0}
assert log(abs(x)*abs(y)).subs(reps) != eq.subs(reps)
def test_logcombine_complex_coeff():
i = Integral((sin(x**2) + cos(x**3))/x, x)
assert logcombine(i, force=True) == i
assert logcombine(i + 2*log(x), force=True) == \
i + log(x**2)
def test_issue_5950():
x, y = symbols("x,y", positive=True)
assert logcombine(log(3) - log(2)) == log(Rational(3,2), evaluate=False)
assert logcombine(log(x) - log(y)) == log(x/y)
assert logcombine(log(Rational(3,2), evaluate=False) - log(2)) == \
log(Rational(3,4), evaluate=False)
def test_posify():
from sympy.abc import x
assert str(posify(
x +
Symbol('p', positive=True) +
Symbol('n', negative=True))) == '(_x + n + p, {_x: x})'
eq, rep = posify(1/x)
assert log(eq).expand().subs(rep) == -log(x)
assert str(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})'
x = symbols('x')
p = symbols('p', positive=True)
n = symbols('n', negative=True)
orig = [x, n, p]
modified, reps = posify(orig)
assert str(modified) == '[_x, n, p]'
assert [w.subs(reps) for w in modified] == orig
assert str(Integral(posify(1/x + y)[0], (y, 1, 3)).expand()) == \
'Integral(1/_x, (y, 1, 3)) + Integral(_y, (y, 1, 3))'
assert str(Sum(posify(1/x**n)[0], (n,1,3)).expand()) == \
'Sum(_x**(-n), (n, 1, 3))'
# issue 16438
k = Symbol('k', finite=True)
eq, rep = posify(k)
assert eq.assumptions0 == {'positive': True, 'zero': False, 'imaginary': False,
'nonpositive': False, 'commutative': True, 'hermitian': True, 'real': True, 'nonzero': True,
'nonnegative': True, 'negative': False, 'complex': True, 'finite': True,
'infinite': False, 'extended_real':True, 'extended_negative': False,
'extended_nonnegative': True, 'extended_nonpositive': False,
'extended_nonzero': True, 'extended_positive': True}
def test_issue_4194():
# simplify should call cancel
from sympy.abc import x, y
f = Function('f')
assert simplify((4*x + 6*f(y))/(2*x + 3*f(y))) == 2
@XFAIL
def test_simplify_float_vs_integer():
# Test for issue 4473:
# https://github.com/sympy/sympy/issues/4473
assert simplify(x**2.0 - x**2) == 0
assert simplify(x**2 - x**2.0) == 0
def test_as_content_primitive():
assert (x/2 + y).as_content_primitive() == (S.Half, x + 2*y)
assert (x/2 + y).as_content_primitive(clear=False) == (S.One, x/2 + y)
assert (y*(x/2 + y)).as_content_primitive() == (S.Half, y*(x + 2*y))
assert (y*(x/2 + y)).as_content_primitive(clear=False) == (S.One, y*(x/2 + y))
# although the _as_content_primitive methods do not alter the underlying structure,
# the as_content_primitive function will touch up the expression and join
# bases that would otherwise have not been joined.
assert (x*(2 + 2*x)*(3*x + 3)**2).as_content_primitive() == \
(18, x*(x + 1)**3)
assert (2 + 2*x + 2*y*(3 + 3*y)).as_content_primitive() == \
(2, x + 3*y*(y + 1) + 1)
assert ((2 + 6*x)**2).as_content_primitive() == \
(4, (3*x + 1)**2)
assert ((2 + 6*x)**(2*y)).as_content_primitive() == \
(1, (_keep_coeff(S(2), (3*x + 1)))**(2*y))
assert (5 + 10*x + 2*y*(3 + 3*y)).as_content_primitive() == \
(1, 10*x + 6*y*(y + 1) + 5)
assert (5*(x*(1 + y)) + 2*x*(3 + 3*y)).as_content_primitive() == \
(11, x*(y + 1))
assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() == \
(121, x**2*(y + 1)**2)
assert (y**2).as_content_primitive() == \
(1, y**2)
assert (S.Infinity).as_content_primitive() == (1, oo)
eq = x**(2 + y)
assert (eq).as_content_primitive() == (1, eq)
assert (S.Half**(2 + x)).as_content_primitive() == (Rational(1, 4), 2**-x)
assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \
(Rational(1, 4), (Rational(-1, 2))**x)
assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \
(Rational(1, 4), Rational(-1, 2)**x)
assert (4**((1 + y)/2)).as_content_primitive() == (2, 4**(y/2))
assert (3**((1 + y)/2)).as_content_primitive() == \
(1, 3**(Mul(S.Half, 1 + y, evaluate=False)))
assert (5**Rational(3, 4)).as_content_primitive() == (1, 5**Rational(3, 4))
assert (5**Rational(7, 4)).as_content_primitive() == (5, 5**Rational(3, 4))
assert Add(z*Rational(5, 7), 0.5*x, y*Rational(3, 2), evaluate=False).as_content_primitive() == \
(Rational(1, 14), 7.0*x + 21*y + 10*z)
assert (2**Rational(3, 4) + 2**Rational(1, 4)*sqrt(3)).as_content_primitive(radical=True) == \
(1, 2**Rational(1, 4)*(sqrt(2) + sqrt(3)))
def test_signsimp():
e = x*(-x + 1) + x*(x - 1)
assert signsimp(Eq(e, 0)) is S.true
assert Abs(x - 1) == Abs(1 - x)
assert signsimp(y - x) == y - x
assert signsimp(y - x, evaluate=False) == Mul(-1, x - y, evaluate=False)
def test_besselsimp():
from sympy import besselj, besseli, cosh, cosine_transform, bessely
assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \
besselj(y, z)
assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \
besselj(a, 2*sqrt(x))
assert besselsimp(sqrt(2)*sqrt(pi)*x**Rational(1, 4)*exp(I*pi/4)*exp(-I*pi*a/2) *
besseli(Rational(-1, 2), sqrt(x)*exp_polar(I*pi/2)) *
besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \
besselj(a, sqrt(x)) * cos(sqrt(x))
assert besselsimp(besseli(Rational(-1, 2), z)) == \
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \
exp(-I*pi*a/2)*besselj(a, z)
assert cosine_transform(1/t*sin(a/t), t, y) == \
sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2
assert besselsimp(x**2*(a*(-2*besselj(5*I, x) + besselj(-2 + 5*I, x) +
besselj(2 + 5*I, x)) + b*(-2*bessely(5*I, x) + bessely(-2 + 5*I, x) +
bessely(2 + 5*I, x)))/4 + x*(a*(besselj(-1 + 5*I, x)/2 - besselj(1 + 5*I, x)/2)
+ b*(bessely(-1 + 5*I, x)/2 - bessely(1 + 5*I, x)/2)) + (x**2 + 25)*(a*besselj(5*I, x)
+ b*bessely(5*I, x))) == 0
assert besselsimp(81*x**2*(a*(besselj(Rational(-5, 3), 9*x) - 2*besselj(Rational(1, 3), 9*x) + besselj(Rational(7, 3), 9*x))
+ b*(bessely(Rational(-5, 3), 9*x) - 2*bessely(Rational(1, 3), 9*x) + bessely(Rational(7, 3), 9*x)))/4 + x*(a*(9*besselj(Rational(-2, 3), 9*x)/2
- 9*besselj(Rational(4, 3), 9*x)/2) + b*(9*bessely(Rational(-2, 3), 9*x)/2 - 9*bessely(Rational(4, 3), 9*x)/2)) +
(81*x**2 - Rational(1, 9))*(a*besselj(Rational(1, 3), 9*x) + b*bessely(Rational(1, 3), 9*x))) == 0
assert besselsimp(besselj(a-1,x) + besselj(a+1, x) - 2*a*besselj(a, x)/x) == 0
assert besselsimp(besselj(a-1,x) + besselj(a+1, x) + besselj(a, x)) == (2*a + x)*besselj(a, x)/x
assert besselsimp(x**2* besselj(a,x) + x**3*besselj(a+1, x) + besselj(a+2, x)) == \
2*a*x*besselj(a + 1, x) + x**3*besselj(a + 1, x) - x**2*besselj(a + 2, x) + 2*x*besselj(a + 1, x) + besselj(a + 2, x)
def test_Piecewise():
e1 = x*(x + y) - y*(x + y)
e2 = sin(x)**2 + cos(x)**2
e3 = expand((x + y)*y/x)
s1 = simplify(e1)
s2 = simplify(e2)
s3 = simplify(e3)
assert simplify(Piecewise((e1, x < e2), (e3, True))) == \
Piecewise((s1, x < s2), (s3, True))
def test_polymorphism():
class A(Basic):
def _eval_simplify(x, **kwargs):
return S.One
a = A(5, 2)
assert simplify(a) == 1
def test_issue_from_PR1599():
n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True)
assert simplify(I*sqrt(n1)) == -sqrt(-n1)
def test_issue_6811():
eq = (x + 2*y)*(2*x + 2)
assert simplify(eq) == (x + 1)*(x + 2*y)*2
# reject the 2-arg Mul -- these are a headache for test writing
assert simplify(eq.expand()) == \
2*x**2 + 4*x*y + 2*x + 4*y
def test_issue_6920():
e = [cos(x) + I*sin(x), cos(x) - I*sin(x),
cosh(x) - sinh(x), cosh(x) + sinh(x)]
ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)]
# wrap in f to show that the change happens wherever ei occurs
f = Function('f')
assert [simplify(f(ei)).args[0] for ei in e] == ok
def test_issue_7001():
from sympy.abc import r, R
assert simplify(-(r*Piecewise((pi*Rational(4, 3), r <= R),
(-8*pi*R**3/(3*r**3), True)) + 2*Piecewise((pi*r*Rational(4, 3), r <= R),
(4*pi*R**3/(3*r**2), True)))/(4*pi*r)) == \
Piecewise((-1, r <= R), (0, True))
def test_inequality_no_auto_simplify():
# no simplify on creation but can be simplified
lhs = cos(x)**2 + sin(x)**2
rhs = 2
e = Lt(lhs, rhs, evaluate=False)
assert e is not S.true
assert simplify(e)
def test_issue_9398():
from sympy import Number, cancel
assert cancel(1e-14) != 0
assert cancel(1e-14*I) != 0
assert simplify(1e-14) != 0
assert simplify(1e-14*I) != 0
assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0
assert cancel(1e-20) != 0
assert cancel(1e-20*I) != 0
assert simplify(1e-20) != 0
assert simplify(1e-20*I) != 0
assert cancel(1e-100) != 0
assert cancel(1e-100*I) != 0
assert simplify(1e-100) != 0
assert simplify(1e-100*I) != 0
f = Float("1e-1000")
assert cancel(f) != 0
assert cancel(f*I) != 0
assert simplify(f) != 0
assert simplify(f*I) != 0
def test_issue_9324_simplify():
M = MatrixSymbol('M', 10, 10)
e = M[0, 0] + M[5, 4] + 1304
assert simplify(e) == e
def test_issue_13474():
x = Symbol('x')
assert simplify(x + csch(sinc(1))) == x + csch(sinc(1))
def test_simplify_function_inverse():
# "inverse" attribute does not guarantee that f(g(x)) is x
# so this simplification should not happen automatically.
# See issue #12140
x, y = symbols('x, y')
g = Function('g')
class f(Function):
def inverse(self, argindex=1):
return g
assert simplify(f(g(x))) == f(g(x))
assert inversecombine(f(g(x))) == x
assert simplify(f(g(x)), inverse=True) == x
assert simplify(f(g(sin(x)**2 + cos(x)**2)), inverse=True) == 1
assert simplify(f(g(x, y)), inverse=True) == f(g(x, y))
assert unchanged(asin, sin(x))
assert simplify(asin(sin(x))) == asin(sin(x))
assert simplify(2*asin(sin(3*x)), inverse=True) == 6*x
assert simplify(log(exp(x))) == log(exp(x))
assert simplify(log(exp(x)), inverse=True) == x
assert simplify(log(exp(x), 2), inverse=True) == x/log(2)
assert simplify(log(exp(x), 2, evaluate=False), inverse=True) == x/log(2)
def test_clear_coefficients():
from sympy.simplify.simplify import clear_coefficients
assert clear_coefficients(4*y*(6*x + 3)) == (y*(2*x + 1), 0)
assert clear_coefficients(4*y*(6*x + 3) - 2) == (y*(2*x + 1), Rational(1, 6))
assert clear_coefficients(4*y*(6*x + 3) - 2, x) == (y*(2*x + 1), x/12 + Rational(1, 6))
assert clear_coefficients(sqrt(2) - 2) == (sqrt(2), 2)
assert clear_coefficients(4*sqrt(2) - 2) == (sqrt(2), S.Half)
assert clear_coefficients(S(3), x) == (0, x - 3)
assert clear_coefficients(S.Infinity, x) == (S.Infinity, x)
assert clear_coefficients(-S.Pi, x) == (S.Pi, -x)
assert clear_coefficients(2 - S.Pi/3, x) == (pi, -3*x + 6)
def test_nc_simplify():
from sympy.simplify.simplify import nc_simplify
from sympy.matrices.expressions import MatPow, Identity
from sympy.core import Pow
from functools import reduce
a, b, c, d = symbols('a b c d', commutative = False)
x = Symbol('x')
A = MatrixSymbol("A", x, x)
B = MatrixSymbol("B", x, x)
C = MatrixSymbol("C", x, x)
D = MatrixSymbol("D", x, x)
subst = {a: A, b: B, c: C, d:D}
funcs = {Add: lambda x,y: x+y, Mul: lambda x,y: x*y }
def _to_matrix(expr):
if expr in subst:
return subst[expr]
if isinstance(expr, Pow):
return MatPow(_to_matrix(expr.args[0]), expr.args[1])
elif isinstance(expr, (Add, Mul)):
return reduce(funcs[expr.func],[_to_matrix(a) for a in expr.args])
else:
return expr*Identity(x)
def _check(expr, simplified, deep=True, matrix=True):
assert nc_simplify(expr, deep=deep) == simplified
assert expand(expr) == expand(simplified)
if matrix:
m_simp = _to_matrix(simplified).doit(inv_expand=False)
assert nc_simplify(_to_matrix(expr), deep=deep) == m_simp
_check(a*b*a*b*a*b*c*(a*b)**3*c, ((a*b)**3*c)**2)
_check(a*b*(a*b)**-2*a*b, 1)
_check(a**2*b*a*b*a*b*(a*b)**-1, a*(a*b)**2, matrix=False)
_check(b*a*b**2*a*b**2*a*b**2, b*(a*b**2)**3)
_check(a*b*a**2*b*a**2*b*a**3, (a*b*a)**3*a**2)
_check(a**2*b*a**4*b*a**4*b*a**2, (a**2*b*a**2)**3)
_check(a**3*b*a**4*b*a**4*b*a, a**3*(b*a**4)**3*a**-3)
_check(a*b*a*b + a*b*c*x*a*b*c, (a*b)**2 + x*(a*b*c)**2)
_check(a*b*a*b*c*a*b*a*b*c, ((a*b)**2*c)**2)
_check(b**-1*a**-1*(a*b)**2, a*b)
_check(a**-1*b*c**-1, (c*b**-1*a)**-1)
expr = a**3*b*a**4*b*a**4*b*a**2*b*a**2*(b*a**2)**2*b*a**2*b*a**2
for _ in range(10):
expr *= a*b
_check(expr, a**3*(b*a**4)**2*(b*a**2)**6*(a*b)**10)
_check((a*b*a*b)**2, (a*b*a*b)**2, deep=False)
_check(a*b*(c*d)**2, a*b*(c*d)**2)
expr = b**-1*(a**-1*b**-1 - a**-1*c*b**-1)**-1*a**-1
assert nc_simplify(expr) == (1-c)**-1
# commutative expressions should be returned without an error
assert nc_simplify(2*x**2) == 2*x**2
def test_issue_15965():
A = Sum(z*x**y, (x, 1, a))
anew = z*Sum(x**y, (x, 1, a))
B = Integral(x*y, x)
bdo = x**2*y/2
assert simplify(A + B) == anew + bdo
assert simplify(A) == anew
assert simplify(B) == bdo
assert simplify(B, doit=False) == y*Integral(x, x)
def test_issue_17137():
assert simplify(cos(x)**I) == cos(x)**I
assert simplify(cos(x)**(2 + 3*I)) == cos(x)**(2 + 3*I)
def test_issue_7971():
z = Integral(x, (x, 1, 1))
assert z != 0
assert simplify(z) is S.Zero
@slow
def test_issue_17141_slow():
# Should not give RecursionError
assert simplify((2**acos(I+1)**2).rewrite('log')) == 2**((pi + 2*I*log(-1 +
sqrt(1 - 2*I) + I))**2/4)
def test_issue_17141():
# Check that there is no RecursionError
assert simplify(x**(1 / acos(I))) == x**(2/(pi - 2*I*log(1 + sqrt(2))))
assert simplify(acos(-I)**2*acos(I)**2) == \
log(1 + sqrt(2))**4 + pi**2*log(1 + sqrt(2))**2/2 + pi**4/16
assert simplify(2**acos(I)**2) == 2**((pi - 2*I*log(1 + sqrt(2)))**2/4)
p = 2**acos(I+1)**2
assert simplify(p) == p
def test_simplify_kroneckerdelta():
i, j = symbols("i j")
K = KroneckerDelta
assert simplify(K(i, j)) == K(i, j)
assert simplify(K(0, j)) == K(0, j)
assert simplify(K(i, 0)) == K(i, 0)
assert simplify(K(0, j).rewrite(Piecewise) * K(1, j)) == 0
assert simplify(K(1, i) + Piecewise((1, Eq(j, 2)), (0, True))) == K(1, i) + K(2, j)
# issue 17214
assert simplify(K(0, j) * K(1, j)) == 0
n = Symbol('n', integer=True)
assert simplify(K(0, n) * K(1, n)) == 0
M = Matrix(4, 4, lambda i, j: K(j - i, n) if i <= j else 0)
assert simplify(M**2) == Matrix([[K(0, n), 0, K(1, n), 0],
[0, K(0, n), 0, K(1, n)],
[0, 0, K(0, n), 0],
[0, 0, 0, K(0, n)]])
def test_issue_17292():
assert simplify(abs(x)/abs(x**2)) == 1/abs(x)
# this is bigger than the issue: check that deep processing works
assert simplify(5*abs((x**2 - 1)/(x - 1))) == 5*Abs(x + 1)
def test_issue_19484():
assert simplify(sign(x) * Abs(x)) == x
e = x + sign(x + x**3)
assert simplify(Abs(x + x**3)*e) == x**3 + x*Abs(x**3 + x) + x
e = x**2 + sign(x**3 + 1)
assert simplify(Abs(x**3 + 1) * e) == x**3 + x**2*Abs(x**3 + 1) + 1
f = Function('f')
e = x + sign(x + f(x)**3)
assert simplify(Abs(x + f(x)**3) * e) == x*Abs(x + f(x)**3) + x + f(x)**3
def test_issue_19161():
polynomial = Poly('x**2').simplify()
assert (polynomial-x**2).simplify() == 0
|
23dff82909ea8cb1257fda7c6a887632c907a4f013b391d23c9569e148d82c49 | from sympy import symbols, IndexedBase, Identity, cos, Inverse, tensorcontraction, permutedims, tensorproduct
from sympy.codegen.array_utils import (CodegenArrayContraction,
CodegenArrayTensorProduct, CodegenArrayDiagonal,
CodegenArrayPermuteDims, CodegenArrayElementwiseAdd,
_codegen_array_parse, _recognize_matrix_expression, _RecognizeMatOp,
_RecognizeMatMulLines, _unfold_recognized_expr,
parse_indexed_expression, recognize_matrix_expression,
parse_matrix_expression, nest_permutation)
from sympy import MatrixSymbol, Sum
from sympy.combinatorics import Permutation
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices import Trace, MatAdd, MatMul, Transpose
from sympy.testing.pytest import raises
import random
A, B = symbols("A B", cls=IndexedBase)
i, j, k, l, m, n = symbols("i j k l m n")
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
def test_codegen_array_contraction_construction():
cg = CodegenArrayContraction(A)
assert cg == A
s = Sum(A[i]*B[i], (i, 0, 3))
cg = parse_indexed_expression(s)
assert cg == CodegenArrayContraction(CodegenArrayTensorProduct(A, B), (0, 1))
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, B), (1, 0))
assert cg == CodegenArrayContraction(CodegenArrayTensorProduct(A, B), (0, 1))
expr = M*N
result = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2))
assert parse_matrix_expression(expr) == result
elem = expr[i, j]
assert parse_indexed_expression(elem) == result
expr = M*N*M
result = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, M), (1, 2), (3, 4))
assert parse_matrix_expression(expr) == result
elem = expr[i, j]
result = CodegenArrayContraction(CodegenArrayTensorProduct(M, M, N), (1, 4), (2, 5))
cg = parse_indexed_expression(elem)
cg = cg.sort_args_by_name()
assert cg == result
def test_codegen_array_contraction_indices_types():
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (0, 1))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (0, 1)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)]
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 1), (1, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)]
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, M, N), (1, 4), (2, 5))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)]
def test_codegen_array_recognize_matrix_mul_lines():
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M), (0, 1))
assert recognize_matrix_expression(cg) == Trace(M)
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (0, 1), (2, 3))
assert recognize_matrix_expression(cg) == Trace(M)*Trace(N)
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (0, 3), (1, 2))
assert recognize_matrix_expression(cg) == Trace(M*N)
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (0, 2), (1, 3))
assert recognize_matrix_expression(cg) == Trace(M*N.T)
cg = parse_indexed_expression((M*N*P)[i,j])
assert recognize_matrix_expression(cg) == M*N*P
cg = parse_matrix_expression(M*N*P)
assert recognize_matrix_expression(cg) == M*N*P
cg = parse_indexed_expression((M*N.T*P)[i,j])
assert recognize_matrix_expression(cg) == M*N.T*P
cg = parse_matrix_expression(M*N.T*P)
assert recognize_matrix_expression(cg) == M*N.T*P
cg = CodegenArrayContraction(CodegenArrayTensorProduct(M,N,P,Q), (1, 2), (5, 6))
assert recognize_matrix_expression(cg) == [M*N, P*Q]
expr = -2*M*N
elem = expr[i, j]
cg = parse_indexed_expression(elem)
assert recognize_matrix_expression(cg) == -2*M*N
def test_codegen_array_flatten():
# Flatten nested CodegenArrayTensorProduct objects:
expr1 = CodegenArrayTensorProduct(M, N)
expr2 = CodegenArrayTensorProduct(P, Q)
expr = CodegenArrayTensorProduct(expr1, expr2)
assert expr == CodegenArrayTensorProduct(M, N, P, Q)
assert expr.args == (M, N, P, Q)
# Flatten mixed CodegenArrayTensorProduct and CodegenArrayContraction objects:
cg1 = CodegenArrayContraction(expr1, (1, 2))
cg2 = CodegenArrayContraction(expr2, (0, 3))
expr = CodegenArrayTensorProduct(cg1, cg2)
assert expr == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (1, 2), (4, 7))
expr = CodegenArrayTensorProduct(M, cg1)
assert expr == CodegenArrayContraction(CodegenArrayTensorProduct(M, M, N), (3, 4))
# Flatten nested CodegenArrayContraction objects:
cgnested = CodegenArrayContraction(cg1, (0, 1))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (0, 3), (1, 2))
cgnested = CodegenArrayContraction(CodegenArrayTensorProduct(cg1, cg2), (0, 3))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 6), (1, 2), (4, 7))
cg3 = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4))
cgnested = CodegenArrayContraction(cg3, (0, 1))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 5), (1, 3), (2, 4))
cgnested = CodegenArrayContraction(cg3, (0, 3), (1, 2))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6))
cg4 = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7))
cgnested = CodegenArrayContraction(cg4, (0, 1))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7))
cgnested = CodegenArrayContraction(cg4, (0, 1), (2, 3))
assert cgnested == CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6))
cg = CodegenArrayDiagonal(cg4)
assert cg == cg4
assert isinstance(cg, type(cg4))
# Flatten nested CodegenArrayDiagonal objects:
cg1 = CodegenArrayDiagonal(expr1, (1, 2))
cg2 = CodegenArrayDiagonal(expr2, (0, 3))
cg3 = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4))
cg4 = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7))
cgnested = CodegenArrayDiagonal(cg1, (0, 1))
assert cgnested == CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2), (0, 3))
cgnested = CodegenArrayDiagonal(cg3, (1, 2))
assert cgnested == CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4), (5, 6))
cgnested = CodegenArrayDiagonal(cg4, (1, 2))
assert cgnested == CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7), (2, 4))
def test_codegen_array_parse():
expr = M[i, j]
assert _codegen_array_parse(expr) == (M, (i, j))
expr = M[i, j]*N[k, l]
assert _codegen_array_parse(expr) == (CodegenArrayTensorProduct(M, N), (i, j, k, l))
expr = M[i, j]*N[j, k]
assert _codegen_array_parse(expr) == (CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2)), (i, k, j))
expr = Sum(M[i, j]*N[j, k], (j, 0, k-1))
assert _codegen_array_parse(expr) == (CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2)), (i, k))
expr = M[i, j] + N[i, j]
assert _codegen_array_parse(expr) == (CodegenArrayElementwiseAdd(M, N), (i, j))
expr = M[i, j] + N[j, i]
assert _codegen_array_parse(expr) == (CodegenArrayElementwiseAdd(M, CodegenArrayPermuteDims(N, Permutation([1,0]))), (i, j))
expr = M[i, j] + M[j, i]
assert _codegen_array_parse(expr) == (CodegenArrayElementwiseAdd(M, CodegenArrayPermuteDims(M, Permutation([1,0]))), (i, j))
expr = (M*N*P)[i, j]
assert _codegen_array_parse(expr) == (CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j))
expr = expr.function # Disregard summation in previous expression
ret1, ret2 = _codegen_array_parse(expr)
assert ret1 == CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P), (1, 2), (3, 4))
assert str(ret2) == "(i, j, _i_1, _i_2)"
expr = KroneckerDelta(i, j)*M[i, k]
assert _codegen_array_parse(expr) == (M, ({i, j}, k))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l]
assert _codegen_array_parse(expr) == (M, ({i, j, k}, l))
expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _codegen_array_parse(expr) == (CodegenArrayDiagonal(CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, k})))
expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _codegen_array_parse(expr) == (CodegenArrayDiagonal(CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, m, k})))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n)
assert _codegen_array_parse(expr) == (M, ({i,j,k,m,n}, 0))
expr = M[i, i]
assert _codegen_array_parse(expr) == (CodegenArrayDiagonal(M, (0, 1)), (i,))
def test_codegen_array_diagonal():
cg = CodegenArrayDiagonal(M, (1, 0))
assert cg == CodegenArrayDiagonal(M, (0, 1))
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P), (4, 1), (2, 0))
assert cg == CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P), (1, 4), (0, 2))
def test_codegen_recognize_matrix_expression():
expr = CodegenArrayElementwiseAdd(M, CodegenArrayPermuteDims(M, [1, 0]))
rec = _recognize_matrix_expression(expr)
assert rec == _RecognizeMatOp(MatAdd, [M, _RecognizeMatOp(Transpose, [M])])
assert _unfold_recognized_expr(rec) == M + Transpose(M)
expr = M[i,j] + N[i,j]
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatOp(MatAdd, [M, N])
assert _unfold_recognized_expr(rec) == M + N
expr = M[i,j] + N[j,i]
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatOp(MatAdd, [M, _RecognizeMatOp(Transpose, [N])])
assert _unfold_recognized_expr(rec) == M + N.T
expr = M[i,j]*N[k,l] + N[i,j]*M[k,l]
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatOp(MatAdd, [_RecognizeMatMulLines([M, N]), _RecognizeMatMulLines([N, M])])
#assert _unfold_recognized_expr(rec) == TensorProduct(M, N) + TensorProduct(N, M) maybe?
expr = (M*N*P)[i, j]
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatMulLines([_RecognizeMatOp(MatMul, [M, N, P])])
assert _unfold_recognized_expr(rec) == M*N*P
expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1))
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatOp(MatMul, [M, N, P])
assert _unfold_recognized_expr(rec) == M*N*P
expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1))
p1, p2 = _codegen_array_parse(expr)
rec = _recognize_matrix_expression(p1)
assert rec == _RecognizeMatOp(MatAdd, [
_RecognizeMatOp(MatMul, [M, _RecognizeMatOp(MatAdd, [P, _RecognizeMatOp(Transpose, [P])]), N]),
_RecognizeMatOp(MatMul, [N, _RecognizeMatOp(MatAdd, [P, _RecognizeMatOp(Transpose, [P])]), M])
])
assert _unfold_recognized_expr(rec) == M*(P + P.T)*N + N*(P + P.T)*M
def test_codegen_array_shape():
expr = CodegenArrayTensorProduct(M, N, P, Q)
assert expr.shape == (k, k, k, k, k, k, k, k)
Z = MatrixSymbol("Z", m, n)
expr = CodegenArrayTensorProduct(M, Z)
assert expr.shape == (k, k, m, n)
expr2 = CodegenArrayContraction(expr, (0, 1))
assert expr2.shape == (m, n)
expr2 = CodegenArrayDiagonal(expr, (0, 1))
assert expr2.shape == (m, n, k)
exprp = CodegenArrayPermuteDims(expr, [2, 1, 3, 0])
assert exprp.shape == (m, k, n, k)
expr3 = CodegenArrayTensorProduct(N, Z)
expr2 = CodegenArrayElementwiseAdd(expr, expr3)
assert expr2.shape == (k, k, m, n)
# Contraction along axes with discordant dimensions:
raises(ValueError, lambda: CodegenArrayContraction(expr, (1, 2)))
# Also diagonal needs the same dimensions:
raises(ValueError, lambda: CodegenArrayDiagonal(expr, (1, 2)))
# Diagonal requires at least to axes to compute the diagonal:
raises(ValueError, lambda: CodegenArrayDiagonal(expr, (1,)))
def test_codegen_array_parse_out_of_bounds():
expr = Sum(M[i, i], (i, 0, 4))
raises(ValueError, lambda: parse_indexed_expression(expr))
expr = Sum(M[i, i], (i, 0, k))
raises(ValueError, lambda: parse_indexed_expression(expr))
expr = Sum(M[i, i], (i, 1, k-1))
raises(ValueError, lambda: parse_indexed_expression(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, 4))
raises(ValueError, lambda: parse_indexed_expression(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, k))
raises(ValueError, lambda: parse_indexed_expression(expr))
expr = Sum(M[i, j]*N[j,m], (j, 1, k-1))
raises(ValueError, lambda: parse_indexed_expression(expr))
def test_codegen_permutedims_sink():
cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [0, 1, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayTensorProduct(M, CodegenArrayPermuteDims(N, [1, 0]))
assert recognize_matrix_expression(sunk) == [M, N.T]
cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayTensorProduct(CodegenArrayPermuteDims(M, [1, 0]), CodegenArrayPermuteDims(N, [1, 0]))
assert recognize_matrix_expression(sunk) == [M.T, N.T]
cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [3, 2, 1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayTensorProduct(CodegenArrayPermuteDims(N, [1, 0]), CodegenArrayPermuteDims(M, [1, 0]))
assert recognize_matrix_expression(sunk) == [N.T, M.T]
cg = CodegenArrayPermuteDims(CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayContraction(CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [[0, 3]]), (1, 2))
cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayTensorProduct(CodegenArrayPermuteDims(M, [1, 0]), CodegenArrayPermuteDims(N, [1, 0]))
cg = CodegenArrayPermuteDims(CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == CodegenArrayContraction(CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N, P), [[0, 5]]), (1, 2), (3, 4))
def test_parsing_of_matrix_expressions():
expr = M*N
assert parse_matrix_expression(expr) == CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2))
expr = Transpose(M)
assert parse_matrix_expression(expr) == CodegenArrayPermuteDims(M, [1, 0])
expr = M*Transpose(N)
assert parse_matrix_expression(expr) == CodegenArrayContraction(CodegenArrayTensorProduct(M, CodegenArrayPermuteDims(N, [1, 0])), (1, 2))
expr = 3*M*N
res = parse_matrix_expression(expr)
rexpr = recognize_matrix_expression(res)
assert expr == rexpr
expr = 3*M + N*M.T*M + 4*k*N
res = parse_matrix_expression(expr)
rexpr = recognize_matrix_expression(res)
assert expr == rexpr
expr = Inverse(M)*N
rexpr = recognize_matrix_expression(parse_matrix_expression(expr))
assert expr == rexpr
expr = M**2
rexpr = recognize_matrix_expression(parse_matrix_expression(expr))
assert expr == rexpr
expr = M*(2*N + 3*M)
res = parse_matrix_expression(expr)
rexpr = recognize_matrix_expression(res)
assert expr.expand() == rexpr.doit()
expr = Trace(M)
result = CodegenArrayContraction(M, (0, 1))
assert parse_matrix_expression(expr) == result
def test_special_matrices():
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
expr = a.T*b
elem = expr[0, 0]
cg = parse_indexed_expression(elem)
assert cg == CodegenArrayContraction(CodegenArrayTensorProduct(a, b), (0, 2))
assert recognize_matrix_expression(cg) == a.T*b
def test_push_indices_up_and_down():
indices = list(range(12))
contr_diag_indices = [(0, 6), (2, 8)]
assert CodegenArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15)
assert CodegenArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7)
assert CodegenArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None)
assert CodegenArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None)
contr_diag_indices = [(1, 2), (7, 8)]
assert CodegenArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15)
assert CodegenArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7)
assert CodegenArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None)
assert CodegenArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None)
def test_recognize_diagonalized_vectors():
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
X = MatrixSymbol("X", k, k)
x = MatrixSymbol("x", k, 1)
I1 = Identity(1)
I = Identity(k)
# Check matrix recognition over trivial dimensions:
cg = CodegenArrayTensorProduct(a, b)
assert recognize_matrix_expression(cg) == a*b.T
cg = CodegenArrayTensorProduct(I1, a, b)
assert recognize_matrix_expression(cg) == a*I1*b.T
# Recognize trace inside a tensor product:
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, B, C), (0, 3), (1, 2))
assert recognize_matrix_expression(cg) == Trace(A*B)*C
# Transform diagonal operator to contraction:
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(A, a), (1, 2))
assert cg.transform_to_product() == CodegenArrayContraction(CodegenArrayTensorProduct(A, DiagMatrix(a)), (1, 2))
assert recognize_matrix_expression(cg) == A*DiagMatrix(a)
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(a, b), (0, 2))
assert cg.transform_to_product() == CodegenArrayContraction(CodegenArrayTensorProduct(DiagMatrix(a), b), (0, 2))
assert recognize_matrix_expression(cg).doit() == DiagMatrix(a)*b
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(A, a), (0, 2))
assert cg.transform_to_product() == CodegenArrayContraction(CodegenArrayTensorProduct(A, DiagMatrix(a)), (0, 2))
assert recognize_matrix_expression(cg) == A.T*DiagMatrix(a)
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(I, x, I1), (0, 2), (3, 5))
assert cg.transform_to_product() == CodegenArrayContraction(CodegenArrayTensorProduct(I, DiagMatrix(x), I1), (0, 2))
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(I, x, A, B), (1, 2), (5, 6))
assert cg.transform_to_product() == CodegenArrayDiagonal(CodegenArrayContraction(CodegenArrayTensorProduct(I, DiagMatrix(x), A, B), (1, 2)), (3, 4))
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(x, I1), (1, 2))
assert isinstance(cg, CodegenArrayDiagonal)
assert cg.diagonal_indices == ((1, 2),)
assert recognize_matrix_expression(cg) == x
cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(x, I), (0, 2))
assert cg.transform_to_product() == CodegenArrayContraction(CodegenArrayTensorProduct(DiagMatrix(x), I), (0, 2))
assert recognize_matrix_expression(cg).doit() == DiagMatrix(x)
raises(ValueError, lambda: CodegenArrayDiagonal(x, (1,)))
# Ignore identity matrices with contractions:
cg = CodegenArrayContraction(CodegenArrayTensorProduct(I, A, I, I), (0, 2), (1, 3), (5, 7))
assert cg.split_multiple_contractions() == cg
assert recognize_matrix_expression(cg) == Trace(A)*I
cg = CodegenArrayContraction(CodegenArrayTensorProduct(Trace(A) * I, I, I), (1, 5), (3, 4))
assert cg.split_multiple_contractions() == cg
assert recognize_matrix_expression(cg).doit() == Trace(A)*I
# Add DiagMatrix when required:
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a), (1, 2))
assert cg.split_multiple_contractions() == cg
assert recognize_matrix_expression(cg) == A*a
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a, B), (1, 2, 4))
assert cg.split_multiple_contractions() == CodegenArrayContraction(CodegenArrayTensorProduct(A, DiagMatrix(a), B), (1, 2), (3, 4))
assert recognize_matrix_expression(cg) == A*DiagMatrix(a)*B
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a, B), (0, 2, 4))
assert cg.split_multiple_contractions() == CodegenArrayContraction(CodegenArrayTensorProduct(A, DiagMatrix(a), B), (0, 2), (3, 4))
assert recognize_matrix_expression(cg) == A.T*DiagMatrix(a)*B
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a, b, a.T, B), (0, 2, 4, 7, 9))
assert cg.split_multiple_contractions() == CodegenArrayContraction(CodegenArrayTensorProduct(A, DiagMatrix(a), DiagMatrix(b),
DiagMatrix(a), B),
(0, 2), (3, 4), (5, 7), (6, 9))
assert recognize_matrix_expression(cg).doit() == A.T*DiagMatrix(a)*DiagMatrix(b)*DiagMatrix(a)*B.T
cg = CodegenArrayContraction(CodegenArrayTensorProduct(I1, I1, I1), (1, 2, 4))
assert cg.split_multiple_contractions() == CodegenArrayContraction(CodegenArrayTensorProduct(I1, I1, I1), (1, 2), (3, 4))
assert recognize_matrix_expression(cg).doit() == Identity(1)
cg = CodegenArrayContraction(CodegenArrayTensorProduct(I, I, I, I, A), (1, 2, 8), (5, 6, 9))
assert recognize_matrix_expression(cg.split_multiple_contractions()).doit() == A
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8))
expected = CodegenArrayContraction(CodegenArrayTensorProduct(DiagMatrix(a), DiagMatrix(a), C, A, B), (0, 4), (1, 7), (2, 5), (3, 8))
assert cg.split_multiple_contractions() == expected
assert recognize_matrix_expression(cg).doit() == A*DiagMatrix(a)*C*DiagMatrix(a)*B
cg = CodegenArrayContraction(CodegenArrayTensorProduct(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
assert cg.split_multiple_contractions().dummy_eq(CodegenArrayContraction(CodegenArrayTensorProduct((a.T * b).applyfunc(cos), I1, I1, a, b), (0, 2), (1, 4), (3, 7), (5, 9)))
assert recognize_matrix_expression(cg).doit().dummy_eq(MatMul(a, (a.T*b).applyfunc(cos), b.T))
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
assert cg.split_multiple_contractions().dummy_eq(CodegenArrayContraction(CodegenArrayTensorProduct(DiagMatrix(a), (A*X*b).applyfunc(cos), A.T, b, b.T), (0, 2), (1, 5), (3, 7, 8)))
# assert recognize_matrix_expression(cg)
# Check no overlap of lines:
cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7))
assert cg.split_multiple_contractions() == cg
cg = CodegenArrayContraction(CodegenArrayTensorProduct(a, b, A), (0, 2, 4), (1, 3))
assert cg.split_multiple_contractions() == cg
def test_nested_permutations():
cg = CodegenArrayPermuteDims(CodegenArrayPermuteDims(M, (1, 0)), (1, 0))
assert cg == M
times = 3
plist1 = [list(range(6)) for i in range(times)]
plist2 = [list(range(6)) for i in range(times)]
for i in range(times):
random.shuffle(plist1[i])
random.shuffle(plist2[i])
plist1.append([2, 5, 4, 1, 0, 3])
plist2.append([3, 5, 0, 4, 1, 2])
plist1.append([2, 5, 4, 0, 3, 1])
plist2.append([3, 0, 5, 1, 2, 4])
plist1.append([5, 4, 2, 0, 3, 1])
plist2.append([4, 5, 0, 2, 3, 1])
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
Pe = P.subs(k, 3).as_explicit()
cge = tensorproduct(Me, Ne, Pe)
for permutation_array1, permutation_array2 in zip(plist1, plist2):
p1 = Permutation(permutation_array1)
p2 = Permutation(permutation_array2)
cg = CodegenArrayPermuteDims(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(M, N, P),
p1),
p2
)
result = CodegenArrayPermuteDims(
CodegenArrayTensorProduct(M, N, P),
p2*p1
)
assert cg == result
# Check that `permutedims` behaves the same way with explicit-component arrays:
result1 = permutedims(permutedims(cge, p1), p2)
result2 = permutedims(cge, p2*p1)
assert result1 == result2
def test_contraction_permutation_mix():
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
cg1 = CodegenArrayContraction(CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), Permutation([0, 2, 1, 3])), (2, 3))
cg2 = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 3))
assert cg1 == cg2
assert recognize_matrix_expression(cg2) == M*N.T
cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3))
cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3))
assert cge1 == cge2
cg1 = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), Permutation([0, 1, 3, 2]))
cg2 = CodegenArrayTensorProduct(M, CodegenArrayPermuteDims(N, Permutation([1, 0])))
assert cg1 == cg2
assert recognize_matrix_expression(cg1) == [M, N.T]
assert recognize_matrix_expression(cg2) == [M, N.T]
cg1 = CodegenArrayContraction(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
(1, 2), (3, 5)
)
cg2 = CodegenArrayContraction(
CodegenArrayTensorProduct(M, N, P, CodegenArrayPermuteDims(Q, Permutation([1, 0]))),
(1, 5), (2, 3)
)
assert cg1 == cg2
assert recognize_matrix_expression(cg1) == [M*P.T*Trace(N), Q.T]
assert recognize_matrix_expression(cg2) == [M*P.T*Trace(N), Q.T]
cg1 = CodegenArrayContraction(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = CodegenArrayPermuteDims(
CodegenArrayContraction(
CodegenArrayTensorProduct(M, P, Q, N),
(0, 1), (2, 3), (4, 7)),
[1, 0]
)
assert cg1 == cg2
cg1 = CodegenArrayContraction(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = CodegenArrayPermuteDims(
CodegenArrayContraction(
CodegenArrayTensorProduct(CodegenArrayPermuteDims(M, [1, 0]), N, P, Q),
(0, 1), (3, 6), (4, 5)
),
Permutation([1, 0])
)
assert cg1 == cg2
def test_permute_tensor_product():
cg1 = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7]))
cg2 = CodegenArrayTensorProduct(N, CodegenArrayPermuteDims(M, [1, 0]),
CodegenArrayPermuteDims(P, [1, 0]), Q)
assert cg1 == cg2
# TODO: reverse operation starting with `CodegenArrayPermuteDims` and getting down to `bb`...
cg1 = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7]))
cg2 = CodegenArrayTensorProduct(N, P, M, Q)
assert cg1 == cg2
cg1 = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1]))
assert cg1.expr == CodegenArrayTensorProduct(N, P, Q, M)
assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7])
cg1 = CodegenArrayContraction(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6])
cg2 = CodegenArrayPermuteDims(CodegenArrayContraction(CodegenArrayTensorProduct(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4])
assert cg1 == cg2
cg1 = CodegenArrayContraction(
CodegenArrayContraction(
CodegenArrayContraction(
CodegenArrayContraction(
CodegenArrayPermuteDims(
CodegenArrayTensorProduct(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6]),
[1, 3, 4]),
[1]),
[0])
cg2 = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,))
assert cg1 == cg2
def test_normalize_diagonal_permutedims():
tp = CodegenArrayTensorProduct(M, Q, N, P)
expr = CodegenArrayDiagonal(
CodegenArrayPermuteDims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7),
(0, 3))
result = CodegenArrayDiagonal(tp, (2, 6, 7), (3, 5), (0, 4))
assert expr == result
tp = CodegenArrayTensorProduct(M, N, P, Q)
expr = CodegenArrayDiagonal(CodegenArrayPermuteDims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4))
result = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, P, N, Q), (3, 4, 5), (1, 2))
assert expr == result
def test_normalize_diagonal_contraction():
tp = CodegenArrayTensorProduct(M, N, P, Q)
expr = CodegenArrayContraction(CodegenArrayDiagonal(tp, (1, 3, 4)), (0, 3))
result = CodegenArrayDiagonal(CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 6)), (0, 2, 3))
assert expr == result
expr = CodegenArrayContraction(CodegenArrayDiagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3))
result = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7))
assert expr == result
expr = CodegenArrayContraction(CodegenArrayDiagonal(tp, (0, 2, 6, 7)), (1, 2, 3))
result = CodegenArrayDiagonal(CodegenArrayContraction(tp, (3, 4, 5)), (0, 2, 3, 4))
assert expr == result
td = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N, P, Q), (0, 3))
expr = CodegenArrayContraction(td, (2, 1), (0, 4, 6, 5, 3))
result = CodegenArrayContraction(CodegenArrayTensorProduct(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4))
assert expr == result
|
b228ee285bb693d5b4e983c0abca55bbcf46e55f80d8bbfa5f7ba97ce53d1c9a | import tempfile
import sympy as sp
from sympy.codegen.ast import Assignment
from sympy.codegen.algorithms import newtons_method, newtons_method_function
from sympy.codegen.fnodes import bind_C
from sympy.codegen.futils import render_as_module as f_module
from sympy.codegen.pyutils import render_as_module as py_module
from sympy.external import import_module
from sympy.printing import ccode
from sympy.utilities._compilation import compile_link_import_strings, has_c, has_fortran
from sympy.utilities._compilation.util import may_xfail
from sympy.testing.pytest import skip, raises
cython = import_module('cython')
wurlitzer = import_module('wurlitzer')
def test_newtons_method():
x, dx, atol = sp.symbols('x dx atol')
expr = sp.cos(x) - x**3
algo = newtons_method(expr, x, atol, dx)
assert algo.has(Assignment(dx, -expr/expr.diff(x)))
@may_xfail
def test_newtons_method_function__ccode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x)
if not cython:
skip("cython not installed.")
if not has_c():
skip("No C compiler found.")
compile_kw = dict(std='c99')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton.c', ('#include <math.h>\n'
'#include <stdio.h>\n') + ccode(func)),
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double)\n"
"def py_newton(x):\n"
" return newton(x)\n"))
], build_dir=folder, compile_kwargs=compile_kw)
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
@may_xfail
def test_newtons_method_function__fcode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x, attrs=[bind_C(name='newton')])
if not cython:
skip("cython not installed.")
if not has_fortran():
skip("No Fortran compiler found.")
f_mod = f_module([func], 'mod_newton')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton.f90', f_mod),
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double*)\n"
"def py_newton(double x):\n"
" return newton(&x)\n"))
], build_dir=folder)
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
def test_newtons_method_function__pycode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x)
py_mod = py_module(func)
namespace = {}
exec(py_mod, namespace, namespace)
res = eval('newton(0.5)', namespace)
assert abs(res - 0.865474033102) < 1e-12
@may_xfail
def test_newtons_method_function__ccode_parameters():
args = x, A, k, p = sp.symbols('x A k p')
expr = A*sp.cos(k*x) - p*x**3
raises(ValueError, lambda: newtons_method_function(expr, x))
use_wurlitzer = wurlitzer
func = newtons_method_function(expr, x, args, debug=use_wurlitzer)
if not has_c():
skip("No C compiler found.")
if not cython:
skip("cython not installed.")
compile_kw = dict(std='c99')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton_par.c', ('#include <math.h>\n'
'#include <stdio.h>\n') + ccode(func)),
('_newton_par.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double, double, double, double)\n"
"def py_newton(x, A=1, k=1, p=1):\n"
" return newton(x, A, k, p)\n"))
], compile_kwargs=compile_kw, build_dir=folder)
if use_wurlitzer:
with wurlitzer.pipes() as (out, err):
result = mod.py_newton(0.5)
else:
result = mod.py_newton(0.5)
assert abs(result - 0.865474033102) < 1e-12
if not use_wurlitzer:
skip("C-level output only tested when package 'wurlitzer' is available.")
out, err = out.read(), err.read()
assert err == ''
assert out == """\
x= 0.5 d_x= 0.61214
x= 1.1121 d_x= -0.20247
x= 0.90967 d_x= -0.042409
x= 0.86726 d_x= -0.0017867
x= 0.86548 d_x= -3.1022e-06
x= 0.86547 d_x= -9.3421e-12
x= 0.86547 d_x= 3.6902e-17
""" # try to run tests with LC_ALL=C if this assertion fails
|
3bd9d065f3b7f15185744ba23dcd346276276a9ca04b8df12defdc6b6bf676dc | """
Handlers for keys related to number theory: prime, even, odd, etc.
"""
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
from sympy.ntheory import isprime
from sympy.core import S, Float
class AskPrimeHandler(CommonHandler):
"""
Handler for key 'prime'.
Explanation
===========
Test that an expression represents a prime number. When the
expression is an exact number, the result (when True) is subject to
the limitations of isprime() which is used to return the result.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_prime
@staticmethod
def _number(expr, assumptions):
# helper method
exact = not expr.atoms(Float)
try:
i = int(expr.round())
if (expr - i).equals(0) is False:
raise TypeError
except TypeError:
return False
if exact:
return isprime(i)
# when not exact, we won't give a True or False
# since the number represents an approximate value
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
return AskPrimeHandler._number(expr, assumptions)
@staticmethod
def Mul(expr, assumptions):
if expr.is_number:
return AskPrimeHandler._number(expr, assumptions)
for arg in expr.args:
if not ask(Q.integer(arg), assumptions):
return None
for arg in expr.args:
if arg.is_number and arg.is_composite:
return False
@staticmethod
def Pow(expr, assumptions):
"""
Integer**Integer -> !Prime
"""
if expr.is_number:
return AskPrimeHandler._number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions) and \
ask(Q.integer(expr.base), assumptions):
return False
@staticmethod
def Integer(expr, assumptions):
return isprime(expr)
Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4
@staticmethod
def Float(expr, assumptions):
return AskPrimeHandler._number(expr, assumptions)
@staticmethod
def NumberSymbol(expr, assumptions):
return AskPrimeHandler._number(expr, assumptions)
class AskCompositeHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_composite
@staticmethod
def Basic(expr, assumptions):
_positive = ask(Q.positive(expr), assumptions)
if _positive:
_integer = ask(Q.integer(expr), assumptions)
if _integer:
_prime = ask(Q.prime(expr), assumptions)
if _prime is None:
return
# Positive integer which is not prime is not
# necessarily composite
if expr.equals(1):
return False
return not _prime
else:
return _integer
else:
return _positive
class AskEvenHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_even
@staticmethod
def _number(expr, assumptions):
# helper method
try:
i = int(expr.round())
if not (expr - i).equals(0):
raise TypeError
except TypeError:
return False
if isinstance(expr, (float, Float)):
return False
return i % 2 == 0
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
return AskEvenHandler._number(expr, assumptions)
@staticmethod
def Mul(expr, assumptions):
"""
Even * Integer -> Even
Even * Odd -> Even
Integer * Odd -> ?
Odd * Odd -> Odd
Even * Even -> Even
Integer * Integer -> Even if Integer + Integer = Odd
otherwise -> ?
"""
if expr.is_number:
return AskEvenHandler._number(expr, assumptions)
even, odd, irrational, acc = False, 0, False, 1
for arg in expr.args:
# check for all integers and at least one even
if ask(Q.integer(arg), assumptions):
if ask(Q.even(arg), assumptions):
even = True
elif ask(Q.odd(arg), assumptions):
odd += 1
elif not even and acc != 1:
if ask(Q.odd(acc + arg), assumptions):
even = True
elif ask(Q.irrational(arg), assumptions):
# one irrational makes the result False
# two makes it undefined
if irrational:
break
irrational = True
else:
break
acc = arg
else:
if irrational:
return False
if even:
return True
if odd == len(expr.args):
return False
@staticmethod
def Add(expr, assumptions):
"""
Even + Odd -> Odd
Even + Even -> Even
Odd + Odd -> Even
"""
if expr.is_number:
return AskEvenHandler._number(expr, assumptions)
_result = True
for arg in expr.args:
if ask(Q.even(arg), assumptions):
pass
elif ask(Q.odd(arg), assumptions):
_result = not _result
else:
break
else:
return _result
@staticmethod
def Pow(expr, assumptions):
if expr.is_number:
return AskEvenHandler._number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions):
if ask(Q.positive(expr.exp), assumptions):
return ask(Q.even(expr.base), assumptions)
elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions):
return False
elif expr.base is S.NegativeOne:
return False
@staticmethod
def Integer(expr, assumptions):
return not bool(expr.p & 1)
Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4
@staticmethod
def NumberSymbol(expr, assumptions):
return AskEvenHandler._number(expr, assumptions)
@staticmethod
def Abs(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return ask(Q.even(expr.args[0]), assumptions)
@staticmethod
def re(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return ask(Q.even(expr.args[0]), assumptions)
@staticmethod
def im(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
class AskOddHandler(CommonHandler):
"""
Handler for key 'odd'.
Test that an expression represents an odd number.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_odd
@staticmethod
def Basic(expr, assumptions):
_integer = ask(Q.integer(expr), assumptions)
if _integer:
_even = ask(Q.even(expr), assumptions)
if _even is None:
return None
return not _even
return _integer
|
a2e17045ced3145854c946acb92b70b0022dc3d2c60b58a76eed6cad975bf7bf | """
This module contains query handlers responsible for calculus queries:
infinitesimal, finite, etc.
"""
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
class AskFiniteHandler(CommonHandler):
"""
Handler for key 'finite'.
Explanation
===========
Test that an expression is bounded respect to all its variables.
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.handlers.calculus import AskFiniteHandler
>>> from sympy.abc import x
>>> a = AskFiniteHandler()
>>> a.Symbol(x, Q.positive(x)) is None
True
>>> a.Symbol(x, Q.finite(x))
True
"""
@staticmethod
def Symbol(expr, assumptions):
"""
Handles Symbol.
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.handlers.calculus import AskFiniteHandler
>>> from sympy.abc import x
>>> a = AskFiniteHandler()
>>> a.Symbol(x, Q.positive(x)) is None
True
>>> a.Symbol(x, Q.finite(x))
True
"""
if expr.is_finite is not None:
return expr.is_finite
if Q.finite(expr) in conjuncts(assumptions):
return True
return None
@staticmethod
def Add(expr, assumptions):
"""
Return True if expr is bounded, False if not and None if unknown.
Truth Table:
+-------+-----+-----------+-----------+
| | | | |
| | B | U | ? |
| | | | |
+-------+-----+---+---+---+---+---+---+
| | | | | | | | |
| | |'+'|'-'|'x'|'+'|'-'|'x'|
| | | | | | | | |
+-------+-----+---+---+---+---+---+---+
| | | | |
| B | B | U | ? |
| | | | |
+---+---+-----+---+---+---+---+---+---+
| | | | | | | | | |
| |'+'| | U | ? | ? | U | ? | ? |
| | | | | | | | | |
| +---+-----+---+---+---+---+---+---+
| | | | | | | | | |
| U |'-'| | ? | U | ? | ? | U | ? |
| | | | | | | | | |
| +---+-----+---+---+---+---+---+---+
| | | | | |
| |'x'| | ? | ? |
| | | | | |
+---+---+-----+---+---+---+---+---+---+
| | | | |
| ? | | | ? |
| | | | |
+-------+-----+-----------+---+---+---+
* 'B' = Bounded
* 'U' = Unbounded
* '?' = unknown boundedness
* '+' = positive sign
* '-' = negative sign
* 'x' = sign unknown
|
* All Bounded -> True
* 1 Unbounded and the rest Bounded -> False
* >1 Unbounded, all with same known sign -> False
* Any Unknown and unknown sign -> None
* Else -> None
When the signs are not the same you can have an undefined
result as in oo - oo, hence 'bounded' is also undefined.
"""
sign = -1 # sign of unknown or infinite
result = True
for arg in expr.args:
_bounded = ask(Q.finite(arg), assumptions)
if _bounded:
continue
s = ask(Q.positive(arg), assumptions)
# if there has been more than one sign or if the sign of this arg
# is None and Bounded is None or there was already
# an unknown sign, return None
if sign != -1 and s != sign or \
s is None and (s == _bounded or s == sign):
return None
else:
sign = s
# once False, do not change
if result is not False:
result = _bounded
return result
@staticmethod
def Mul(expr, assumptions):
"""
Return True if expr is bounded, False if not and None if unknown.
Truth Table:
+---+---+---+--------+
| | | | |
| | B | U | ? |
| | | | |
+---+---+---+---+----+
| | | | | |
| | | | s | /s |
| | | | | |
+---+---+---+---+----+
| | | | |
| B | B | U | ? |
| | | | |
+---+---+---+---+----+
| | | | | |
| U | | U | U | ? |
| | | | | |
+---+---+---+---+----+
| | | | |
| ? | | | ? |
| | | | |
+---+---+---+---+----+
* B = Bounded
* U = Unbounded
* ? = unknown boundedness
* s = signed (hence nonzero)
* /s = not signed
"""
result = True
for arg in expr.args:
_bounded = ask(Q.finite(arg), assumptions)
if _bounded:
continue
elif _bounded is None:
if result is None:
return None
if ask(Q.nonzero(arg), assumptions) is None:
return None
if result is not False:
result = None
else:
result = False
return result
@staticmethod
def Pow(expr, assumptions):
"""
Unbounded ** NonZero -> Unbounded
Bounded ** Bounded -> Bounded
Abs()<=1 ** Positive -> Bounded
Abs()>=1 ** Negative -> Bounded
Otherwise unknown
"""
base_bounded = ask(Q.finite(expr.base), assumptions)
exp_bounded = ask(Q.finite(expr.exp), assumptions)
if base_bounded is None and exp_bounded is None: # Common Case
return None
if base_bounded is False and ask(Q.nonzero(expr.exp), assumptions):
return False
if base_bounded and exp_bounded:
return True
if (abs(expr.base) <= 1) == True and ask(Q.positive(expr.exp), assumptions):
return True
if (abs(expr.base) >= 1) == True and ask(Q.negative(expr.exp), assumptions):
return True
if (abs(expr.base) >= 1) == True and exp_bounded is False:
return False
return None
@staticmethod
def log(expr, assumptions):
return ask(Q.finite(expr.args[0]), assumptions)
exp = log
cos, sin, Number, Pi, Exp1, GoldenRatio, TribonacciConstant, ImaginaryUnit, sign = \
[staticmethod(CommonHandler.AlwaysTrue)]*9
Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysFalse)]*2
|
52f6cbfd403a420fa15eb436d47e5f9823ef4eb3b3f185474b3fd9198344b821 | from sympy.core.logic import _fuzzy_group
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
class AskHandler:
"""Base class that all Ask Handlers must inherit."""
pass
class CommonHandler(AskHandler):
"""Defines some useful methods common to most Handlers. """
@staticmethod
def AlwaysTrue(expr, assumptions):
return True
@staticmethod
def AlwaysFalse(expr, assumptions):
return False
@staticmethod
def AlwaysNone(expr, assumptions):
return None
NaN = AlwaysFalse
class AskCommutativeHandler(CommonHandler):
"""
Handler for key 'commutative'
"""
@staticmethod
def Symbol(expr, assumptions):
"""Objects are expected to be commutative unless otherwise stated"""
assumps = conjuncts(assumptions)
if expr.is_commutative is not None:
return expr.is_commutative and not ~Q.commutative(expr) in assumps
if Q.commutative(expr) in assumps:
return True
elif ~Q.commutative(expr) in assumps:
return False
return True
@staticmethod
def Basic(expr, assumptions):
for arg in expr.args:
if not ask(Q.commutative(arg), assumptions):
return False
return True
@staticmethod
def Number(expr, assumptions):
return True
@staticmethod
def NaN(expr, assumptions):
return True
class TautologicalHandler(AskHandler):
"""Wrapper allowing to query the truth value of a boolean expression."""
@staticmethod
def bool(expr, assumptions):
return expr
BooleanTrue = staticmethod(CommonHandler.AlwaysTrue)
BooleanFalse = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def AppliedPredicate(expr, assumptions):
return ask(expr, assumptions)
@staticmethod
def Not(expr, assumptions):
value = ask(expr.args[0], assumptions=assumptions)
if value in (True, False):
return not value
else:
return None
@staticmethod
def Or(expr, assumptions):
result = False
for arg in expr.args:
p = ask(arg, assumptions=assumptions)
if p is True:
return True
if p is None:
result = None
return result
@staticmethod
def And(expr, assumptions):
result = True
for arg in expr.args:
p = ask(arg, assumptions=assumptions)
if p is False:
return False
if p is None:
result = None
return result
@staticmethod
def Implies(expr, assumptions):
p, q = expr.args
return ask(~p | q, assumptions=assumptions)
@staticmethod
def Equivalent(expr, assumptions):
p, q = expr.args
pt = ask(p, assumptions=assumptions)
if pt is None:
return None
qt = ask(q, assumptions=assumptions)
if qt is None:
return None
return pt == qt
#### Helper methods
def test_closed_group(expr, assumptions, key):
"""
Test for membership in a group with respect
to the current operation.
"""
return _fuzzy_group(
(ask(key(a), assumptions) for a in expr.args), quick_exit=True)
|
e85bfb512998b3ddfadc5e8a67ef1f0770139797e2e0740948a1731d082ad5f6 | """
This module contains query handlers responsible for calculus queries:
infinitesimal, bounded, etc.
"""
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler, test_closed_group
from sympy.matrices.expressions import MatMul, MatrixExpr
from sympy.core.logic import fuzzy_and
from sympy.utilities.iterables import sift
from sympy.core import Basic
from functools import partial
def _Factorization(predicate, expr, assumptions):
if predicate in expr.predicates:
return True
class AskSquareHandler(CommonHandler):
"""
Handler for key 'square'.
"""
@staticmethod
def MatrixExpr(expr, assumptions):
return expr.shape[0] == expr.shape[1]
class AskSymmetricHandler(CommonHandler):
"""
Handler for key 'symmetric'.
"""
@staticmethod
def MatMul(expr, assumptions):
factor, mmul = expr.as_coeff_mmul()
if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args):
return True
# TODO: implement sathandlers system for the matrices.
# Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
if ask(Q.diagonal(expr), assumptions):
return True
if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T:
if len(mmul.args) == 2:
return True
return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions)
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.symmetric(base), assumptions)
return None
@staticmethod
def MatAdd(expr, assumptions):
return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args)
@staticmethod
def MatrixSymbol(expr, assumptions):
if not expr.is_square:
return False
# TODO: implement sathandlers system for the matrices.
# Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
if ask(Q.diagonal(expr), assumptions):
return True
if Q.symmetric(expr) in conjuncts(assumptions):
return True
@staticmethod
def ZeroMatrix(expr, assumptions):
return ask(Q.square(expr), assumptions)
OneMatrix = ZeroMatrix
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.symmetric(expr.arg), assumptions)
Inverse = Transpose
@staticmethod
def MatrixSlice(expr, assumptions):
# TODO: implement sathandlers system for the matrices.
# Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
if ask(Q.diagonal(expr), assumptions):
return True
if not expr.on_diag:
return None
else:
return ask(Q.symmetric(expr.parent), assumptions)
Identity = staticmethod(CommonHandler.AlwaysTrue)
class AskInvertibleHandler(CommonHandler):
"""
Handler for key 'invertible'.
"""
@staticmethod
def MatMul(expr, assumptions):
factor, mmul = expr.as_coeff_mmul()
if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args):
return True
if any(ask(Q.invertible(arg), assumptions) is False
for arg in mmul.args):
return False
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
if exp.is_negative == False:
return ask(Q.invertible(base), assumptions)
return None
@staticmethod
def MatAdd(expr, assumptions):
return None
@staticmethod
def MatrixSymbol(expr, assumptions):
if not expr.is_square:
return False
if Q.invertible(expr) in conjuncts(assumptions):
return True
Identity, Inverse = [staticmethod(CommonHandler.AlwaysTrue)]*2
ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.invertible(expr.arg), assumptions)
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.invertible(expr.parent), assumptions)
@staticmethod
def MatrixBase(expr, assumptions):
if not expr.is_square:
return False
return expr.rank() == expr.rows
@staticmethod
def MatrixExpr(expr, assumptions):
if not expr.is_square:
return False
return None
@staticmethod
def BlockMatrix(expr, assumptions):
from sympy.matrices.expressions.blockmatrix import reblock_2x2
if not expr.is_square:
return False
if expr.blockshape == (1, 1):
return ask(Q.invertible(expr.blocks[0, 0]), assumptions)
expr = reblock_2x2(expr)
if expr.blockshape == (2, 2):
[[A, B], [C, D]] = expr.blocks.tolist()
if ask(Q.invertible(A), assumptions) == True:
invertible = ask(Q.invertible(D - C * A.I * B), assumptions)
if invertible is not None:
return invertible
if ask(Q.invertible(B), assumptions) == True:
invertible = ask(Q.invertible(C - D * B.I * A), assumptions)
if invertible is not None:
return invertible
if ask(Q.invertible(C), assumptions) == True:
invertible = ask(Q.invertible(B - A * C.I * D), assumptions)
if invertible is not None:
return invertible
if ask(Q.invertible(D), assumptions) == True:
invertible = ask(Q.invertible(A - B * D.I * C), assumptions)
if invertible is not None:
return invertible
return None
@staticmethod
def BlockDiagMatrix(expr, assumptions):
if expr.rowblocksizes != expr.colblocksizes:
return None
return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag])
class AskOrthogonalHandler(CommonHandler):
"""
Handler for key 'orthogonal'.
"""
predicate = Q.orthogonal
@staticmethod
def MatMul(expr, assumptions):
factor, mmul = expr.as_coeff_mmul()
if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and
factor == 1):
return True
if any(ask(Q.invertible(arg), assumptions) is False
for arg in mmul.args):
return False
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if int_exp:
return ask(Q.orthogonal(base), assumptions)
return None
@staticmethod
def MatAdd(expr, assumptions):
if (len(expr.args) == 1 and
ask(Q.orthogonal(expr.args[0]), assumptions)):
return True
@staticmethod
def MatrixSymbol(expr, assumptions):
if (not expr.is_square or
ask(Q.invertible(expr), assumptions) is False):
return False
if Q.orthogonal(expr) in conjuncts(assumptions):
return True
Identity = staticmethod(CommonHandler.AlwaysTrue)
ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.orthogonal(expr.arg), assumptions)
Inverse = Transpose
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.orthogonal(expr.parent), assumptions)
Factorization = staticmethod(partial(_Factorization, Q.orthogonal))
class AskUnitaryHandler(CommonHandler):
"""
Handler for key 'unitary'.
"""
predicate = Q.unitary
@staticmethod
def MatMul(expr, assumptions):
factor, mmul = expr.as_coeff_mmul()
if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and
abs(factor) == 1):
return True
if any(ask(Q.invertible(arg), assumptions) is False
for arg in mmul.args):
return False
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if int_exp:
return ask(Q.unitary(base), assumptions)
return None
@staticmethod
def MatrixSymbol(expr, assumptions):
if (not expr.is_square or
ask(Q.invertible(expr), assumptions) is False):
return False
if Q.unitary(expr) in conjuncts(assumptions):
return True
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.unitary(expr.arg), assumptions)
Inverse = Transpose
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.unitary(expr.parent), assumptions)
@staticmethod
def DFT(expr, assumptions):
return True
Factorization = staticmethod(partial(_Factorization, Q.unitary))
Identity = staticmethod(CommonHandler.AlwaysTrue)
ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse)
class AskFullRankHandler(CommonHandler):
"""
Handler for key 'fullrank'.
"""
@staticmethod
def MatMul(expr, assumptions):
if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args):
return True
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if int_exp and ask(~Q.negative(exp), assumptions):
return ask(Q.fullrank(base), assumptions)
return None
Identity = staticmethod(CommonHandler.AlwaysTrue)
ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.fullrank(expr.arg), assumptions)
Inverse = Transpose
@staticmethod
def MatrixSlice(expr, assumptions):
if ask(Q.orthogonal(expr.parent), assumptions):
return True
class AskPositiveDefiniteHandler(CommonHandler):
"""
Handler for key 'positive_definite'.
"""
@staticmethod
def MatMul(expr, assumptions):
factor, mmul = expr.as_coeff_mmul()
if (all(ask(Q.positive_definite(arg), assumptions)
for arg in mmul.args) and factor > 0):
return True
if (len(mmul.args) >= 2
and mmul.args[0] == mmul.args[-1].T
and ask(Q.fullrank(mmul.args[0]), assumptions)):
return ask(Q.positive_definite(
MatMul(*mmul.args[1:-1])), assumptions)
@staticmethod
def MatPow(expr, assumptions):
# a power of a positive definite matrix is positive definite
if ask(Q.positive_definite(expr.args[0]), assumptions):
return True
@staticmethod
def MatAdd(expr, assumptions):
if all(ask(Q.positive_definite(arg), assumptions)
for arg in expr.args):
return True
@staticmethod
def MatrixSymbol(expr, assumptions):
if not expr.is_square:
return False
if Q.positive_definite(expr) in conjuncts(assumptions):
return True
Identity = staticmethod(CommonHandler.AlwaysTrue)
ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.positive_definite(expr.arg), assumptions)
Inverse = Transpose
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.positive_definite(expr.parent), assumptions)
class AskUpperTriangularHandler(CommonHandler):
"""
Handler for key 'upper_triangular'.
"""
@staticmethod
def MatMul(expr, assumptions):
factor, matrices = expr.as_coeff_matrices()
if all(ask(Q.upper_triangular(m), assumptions) for m in matrices):
return True
@staticmethod
def MatAdd(expr, assumptions):
if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args):
return True
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.upper_triangular(base), assumptions)
return None
@staticmethod
def MatrixSymbol(expr, assumptions):
if Q.upper_triangular(expr) in conjuncts(assumptions):
return True
Identity, ZeroMatrix = [staticmethod(CommonHandler.AlwaysTrue)]*2
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.lower_triangular(expr.arg), assumptions)
@staticmethod
def Inverse(expr, assumptions):
return ask(Q.upper_triangular(expr.arg), assumptions)
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.upper_triangular(expr.parent), assumptions)
Factorization = staticmethod(partial(_Factorization, Q.upper_triangular))
class AskLowerTriangularHandler(CommonHandler):
"""
Handler for key 'lower_triangular'.
"""
@staticmethod
def MatMul(expr, assumptions):
factor, matrices = expr.as_coeff_matrices()
if all(ask(Q.lower_triangular(m), assumptions) for m in matrices):
return True
@staticmethod
def MatAdd(expr, assumptions):
if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args):
return True
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.lower_triangular(base), assumptions)
return None
@staticmethod
def MatrixSymbol(expr, assumptions):
if Q.lower_triangular(expr) in conjuncts(assumptions):
return True
Identity, ZeroMatrix = [staticmethod(CommonHandler.AlwaysTrue)]*2
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.upper_triangular(expr.arg), assumptions)
@staticmethod
def Inverse(expr, assumptions):
return ask(Q.lower_triangular(expr.arg), assumptions)
@staticmethod
def MatrixSlice(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.lower_triangular(expr.parent), assumptions)
Factorization = staticmethod(partial(_Factorization, Q.lower_triangular))
class AskDiagonalHandler(CommonHandler):
"""
Handler for key 'diagonal'.
"""
@staticmethod
def _is_empty_or_1x1(expr):
return expr.shape == (0, 0) or expr.shape == (1, 1)
@staticmethod
def MatMul(expr, assumptions):
if AskDiagonalHandler._is_empty_or_1x1(expr):
return True
factor, matrices = expr.as_coeff_matrices()
if all(ask(Q.diagonal(m), assumptions) for m in matrices):
return True
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.diagonal(base), assumptions)
return None
@staticmethod
def MatAdd(expr, assumptions):
if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args):
return True
@staticmethod
def MatrixSymbol(expr, assumptions):
if AskDiagonalHandler._is_empty_or_1x1(expr):
return True
if Q.diagonal(expr) in conjuncts(assumptions):
return True
@staticmethod
def ZeroMatrix(expr, assumptions):
return True
@staticmethod
def OneMatrix(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@staticmethod
def Transpose(expr, assumptions):
return ask(Q.diagonal(expr.arg), assumptions)
@staticmethod
def Inverse(expr, assumptions):
return ask(Q.diagonal(expr.arg), assumptions)
@staticmethod
def MatrixSlice(expr, assumptions):
if AskDiagonalHandler._is_empty_or_1x1(expr):
return True
if not expr.on_diag:
return None
else:
return ask(Q.diagonal(expr.parent), assumptions)
@staticmethod
def DiagonalMatrix(expr, assumptions):
return True
@staticmethod
def DiagMatrix(expr, assumptions):
return True
@staticmethod
def Identity(expr, assumptions):
return True
Factorization = staticmethod(partial(_Factorization, Q.diagonal))
def BM_elements(predicate, expr, assumptions):
""" Block Matrix elements. """
return all(ask(predicate(b), assumptions) for b in expr.blocks)
def MS_elements(predicate, expr, assumptions):
""" Matrix Slice elements. """
return ask(predicate(expr.parent), assumptions)
def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions):
d = sift(expr.args, lambda x: isinstance(x, MatrixExpr))
factors, matrices = d[False], d[True]
return fuzzy_and([
test_closed_group(Basic(*factors), assumptions, scalar_predicate),
test_closed_group(Basic(*matrices), assumptions, matrix_predicate)])
class AskIntegerElementsHandler(CommonHandler):
@staticmethod
def MatAdd(expr, assumptions):
return test_closed_group(expr, assumptions, Q.integer_elements)
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
if exp.is_negative == False:
return ask(Q.integer_elements(base), assumptions)
return None
HadamardProduct, Determinant, Trace, Transpose = [MatAdd]*4
ZeroMatrix, OneMatrix, Identity = [staticmethod(CommonHandler.AlwaysTrue)]*3
MatMul = staticmethod(partial(MatMul_elements, Q.integer_elements,
Q.integer))
MatrixSlice = staticmethod(partial(MS_elements, Q.integer_elements))
BlockMatrix = staticmethod(partial(BM_elements, Q.integer_elements))
class AskRealElementsHandler(CommonHandler):
@staticmethod
def MatAdd(expr, assumptions):
return test_closed_group(expr, assumptions, Q.real_elements)
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.real_elements(base), assumptions)
return None
HadamardProduct, Determinant, Trace, Transpose, \
Factorization = [MatAdd]*5
MatMul = staticmethod(partial(MatMul_elements, Q.real_elements, Q.real))
MatrixSlice = staticmethod(partial(MS_elements, Q.real_elements))
BlockMatrix = staticmethod(partial(BM_elements, Q.real_elements))
class AskComplexElementsHandler(CommonHandler):
@staticmethod
def MatAdd(expr, assumptions):
return test_closed_group(expr, assumptions, Q.complex_elements)
@staticmethod
def MatPow(expr, assumptions):
# only for integer powers
base, exp = expr.args
int_exp = ask(Q.integer(exp), assumptions)
if not int_exp:
return None
non_negative = ask(~Q.negative(exp), assumptions)
if (non_negative or non_negative == False
and ask(Q.invertible(base), assumptions)):
return ask(Q.complex_elements(base), assumptions)
return None
HadamardProduct, Determinant, Trace, Transpose, Inverse, \
Factorization = [MatAdd]*6
MatMul = staticmethod(partial(MatMul_elements, Q.complex_elements,
Q.complex))
MatrixSlice = staticmethod(partial(MS_elements, Q.complex_elements))
BlockMatrix = staticmethod(partial(BM_elements, Q.complex_elements))
DFT = staticmethod(CommonHandler.AlwaysTrue)
|
bc93b5a09265c51e5730513d3d9c9438d7e7f4769c144462ade510bd853a1cd4 | """
AskHandlers related to order relations: positive, negative, etc.
"""
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or
class AskNegativeHandler(CommonHandler):
"""
This is called by ask() when key='negative'.
Test that an expression is less (strict) than zero.
Examples
========
>>> from sympy import ask, Q, pi
>>> ask(Q.negative(pi+1)) # this calls AskNegativeHandler.Add
False
>>> ask(Q.negative(pi**2)) # this calls AskNegativeHandler.Pow
False
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_negative
@staticmethod
def _number(expr, assumptions):
r, i = expr.as_real_imag()
# If the imaginary part can symbolically be shown to be zero then
# we just evaluate the real part; otherwise we evaluate the imaginary
# part to see if it actually evaluates to zero and if it does then
# we make the comparison between the real part and zero.
if not i:
r = r.evalf(2)
if r._prec != 1:
return r < 0
else:
i = i.evalf(2)
if i._prec != 1:
if i != 0:
return False
r = r.evalf(2)
if r._prec != 1:
return r < 0
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
return AskNegativeHandler._number(expr, assumptions)
@staticmethod
def Add(expr, assumptions):
"""
Positive + Positive -> Positive,
Negative + Negative -> Negative
"""
if expr.is_number:
return AskNegativeHandler._number(expr, assumptions)
r = ask(Q.real(expr), assumptions)
if r is not True:
return r
nonpos = 0
for arg in expr.args:
if ask(Q.negative(arg), assumptions) is not True:
if ask(Q.positive(arg), assumptions) is False:
nonpos += 1
else:
break
else:
if nonpos < len(expr.args):
return True
@staticmethod
def Mul(expr, assumptions):
if expr.is_number:
return AskNegativeHandler._number(expr, assumptions)
result = None
for arg in expr.args:
if result is None:
result = False
if ask(Q.negative(arg), assumptions):
result = not result
elif ask(Q.positive(arg), assumptions):
pass
else:
return
return result
@staticmethod
def Pow(expr, assumptions):
"""
Real ** Even -> NonNegative
Real ** Odd -> same_as_base
NonNegative ** Positive -> NonNegative
"""
if expr.is_number:
return AskNegativeHandler._number(expr, assumptions)
if ask(Q.real(expr.base), assumptions):
if ask(Q.positive(expr.base), assumptions):
if ask(Q.real(expr.exp), assumptions):
return False
if ask(Q.even(expr.exp), assumptions):
return False
if ask(Q.odd(expr.exp), assumptions):
return ask(Q.negative(expr.base), assumptions)
ImaginaryUnit, Abs = [staticmethod(CommonHandler.AlwaysFalse)]*2
@staticmethod
def exp(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return False
class AskNonNegativeHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_nonnegative
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
notnegative = fuzzy_not(AskNegativeHandler._number(expr, assumptions))
if notnegative:
return ask(Q.real(expr), assumptions)
else:
return notnegative
class AskNonZeroHandler(CommonHandler):
"""
Handler for key 'zero'.
Test that an expression is not identically zero.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_nonzero
@staticmethod
def Basic(expr, assumptions):
if ask(Q.real(expr)) is False:
return False
if expr.is_number:
# if there are no symbols just evalf
i = expr.evalf(2)
def nonz(i):
if i._prec != 1:
return i != 0
return fuzzy_or(nonz(i) for i in i.as_real_imag())
@staticmethod
def Add(expr, assumptions):
if all(ask(Q.positive(x), assumptions) for x in expr.args) \
or all(ask(Q.negative(x), assumptions) for x in expr.args):
return True
@staticmethod
def Mul(expr, assumptions):
for arg in expr.args:
result = ask(Q.nonzero(arg), assumptions)
if result:
continue
return result
return True
@staticmethod
def Pow(expr, assumptions):
return ask(Q.nonzero(expr.base), assumptions)
@staticmethod
def NaN(expr, assumptions):
return True
@staticmethod
def Abs(expr, assumptions):
return ask(Q.nonzero(expr.args[0]), assumptions)
class AskZeroHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_zero
@staticmethod
def Basic(expr, assumptions):
return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)),
ask(Q.real(expr), assumptions)])
@staticmethod
def Mul(expr, assumptions):
# TODO: This should be deducible from the nonzero handler
return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args)
class AskNonPositiveHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_nonpositive
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
notpositive = fuzzy_not(AskPositiveHandler._number(expr, assumptions))
if notpositive:
return ask(Q.real(expr), assumptions)
else:
return notpositive
class AskPositiveHandler(CommonHandler):
"""
Handler for key 'positive'.
Test that an expression is greater (strict) than zero.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_positive
@staticmethod
def _number(expr, assumptions):
r, i = expr.as_real_imag()
# If the imaginary part can symbolically be shown to be zero then
# we just evaluate the real part; otherwise we evaluate the imaginary
# part to see if it actually evaluates to zero and if it does then
# we make the comparison between the real part and zero.
if not i:
r = r.evalf(2)
if r._prec != 1:
return r > 0
else:
i = i.evalf(2)
if i._prec != 1:
if i != 0:
return False
r = r.evalf(2)
if r._prec != 1:
return r > 0
@staticmethod
def Basic(expr, assumptions):
if expr.is_number:
return AskPositiveHandler._number(expr, assumptions)
@staticmethod
def Mul(expr, assumptions):
if expr.is_number:
return AskPositiveHandler._number(expr, assumptions)
result = True
for arg in expr.args:
if ask(Q.positive(arg), assumptions):
continue
elif ask(Q.negative(arg), assumptions):
result = result ^ True
else:
return
return result
@staticmethod
def Add(expr, assumptions):
if expr.is_number:
return AskPositiveHandler._number(expr, assumptions)
r = ask(Q.real(expr), assumptions)
if r is not True:
return r
nonneg = 0
for arg in expr.args:
if ask(Q.positive(arg), assumptions) is not True:
if ask(Q.negative(arg), assumptions) is False:
nonneg += 1
else:
break
else:
if nonneg < len(expr.args):
return True
@staticmethod
def Pow(expr, assumptions):
if expr.is_number:
return AskPositiveHandler._number(expr, assumptions)
if ask(Q.positive(expr.base), assumptions):
if ask(Q.real(expr.exp), assumptions):
return True
if ask(Q.negative(expr.base), assumptions):
if ask(Q.even(expr.exp), assumptions):
return True
if ask(Q.odd(expr.exp), assumptions):
return False
@staticmethod
def exp(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
if ask(Q.imaginary(expr.args[0]), assumptions):
from sympy import pi, I
return ask(Q.even(expr.args[0]/(I*pi)), assumptions)
@staticmethod
def log(expr, assumptions):
r = ask(Q.real(expr.args[0]), assumptions)
if r is not True:
return r
if ask(Q.positive(expr.args[0] - 1), assumptions):
return True
if ask(Q.negative(expr.args[0] - 1), assumptions):
return False
@staticmethod
def factorial(expr, assumptions):
x = expr.args[0]
if ask(Q.integer(x) & Q.positive(x), assumptions):
return True
ImaginaryUnit = staticmethod(CommonHandler.AlwaysFalse)
@staticmethod
def Abs(expr, assumptions):
return ask(Q.nonzero(expr), assumptions)
@staticmethod
def Trace(expr, assumptions):
if ask(Q.positive_definite(expr.arg), assumptions):
return True
@staticmethod
def Determinant(expr, assumptions):
if ask(Q.positive_definite(expr.arg), assumptions):
return True
@staticmethod
def MatrixElement(expr, assumptions):
if (expr.i == expr.j
and ask(Q.positive_definite(expr.parent), assumptions)):
return True
@staticmethod
def atan(expr, assumptions):
return ask(Q.positive(expr.args[0]), assumptions)
@staticmethod
def asin(expr, assumptions):
x = expr.args[0]
if ask(Q.positive(x) & Q.nonpositive(x - 1), assumptions):
return True
if ask(Q.negative(x) & Q.nonnegative(x + 1), assumptions):
return False
@staticmethod
def acos(expr, assumptions):
x = expr.args[0]
if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions):
return True
@staticmethod
def acot(expr, assumptions):
return ask(Q.real(expr.args[0]), assumptions)
|
5e28a3e40efe7a340e9f16cab07369fe225d6bb35568e2c73e70db78d644c393 | """
Handlers for predicates related to set membership: integer, rational, etc.
"""
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler, test_closed_group
from sympy.core.numbers import pi
from sympy.core.logic import fuzzy_bool
from sympy.functions.elementary.exponential import exp, log
from sympy import I, Eq, conjugate, MatrixBase
class AskIntegerHandler(CommonHandler):
"""
Handler for Q.integer.
Test that an expression belongs to the field of integer numbers.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_integer
@staticmethod
def _number(expr, assumptions):
# helper method
try:
i = int(expr.round())
if not (expr - i).equals(0):
raise TypeError
return True
except TypeError:
return False
@staticmethod
def Add(expr, assumptions):
"""
Integer + Integer -> Integer
Integer + !Integer -> !Integer
!Integer + !Integer -> ?
"""
if expr.is_number:
return AskIntegerHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.integer)
@staticmethod
def Mul(expr, assumptions):
"""
Integer*Integer -> Integer
Integer*Irrational -> !Integer
Odd/Even -> !Integer
Integer*Rational -> ?
"""
if expr.is_number:
return AskIntegerHandler._number(expr, assumptions)
_output = True
for arg in expr.args:
if not ask(Q.integer(arg), assumptions):
if arg.is_Rational:
if arg.q == 2:
return ask(Q.even(2*expr), assumptions)
if ~(arg.q & 1):
return None
elif ask(Q.irrational(arg), assumptions):
if _output:
_output = False
else:
return
else:
return
return _output
Pow = Add
int, Integer = [staticmethod(CommonHandler.AlwaysTrue)]*2
Pi, Exp1, GoldenRatio, TribonacciConstant, Infinity, NegativeInfinity, ImaginaryUnit = \
[staticmethod(CommonHandler.AlwaysFalse)]*7
@staticmethod
def Rational(expr, assumptions):
# rationals with denominator one get
# evaluated to Integers
return False
@staticmethod
def Abs(expr, assumptions):
return ask(Q.integer(expr.args[0]), assumptions)
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.integer_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskRationalHandler(CommonHandler):
"""
Handler for Q.rational.
Test that an expression belongs to the field of rational numbers.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_rational
@staticmethod
def Add(expr, assumptions):
"""
Rational + Rational -> Rational
Rational + !Rational -> !Rational
!Rational + !Rational -> ?
"""
if expr.is_number:
if expr.as_real_imag()[1]:
return False
return test_closed_group(expr, assumptions, Q.rational)
Mul = Add
@staticmethod
def Pow(expr, assumptions):
"""
Rational ** Integer -> Rational
Irrational ** Rational -> Irrational
Rational ** Irrational -> ?
"""
if ask(Q.integer(expr.exp), assumptions):
return ask(Q.rational(expr.base), assumptions)
elif ask(Q.rational(expr.exp), assumptions):
if ask(Q.prime(expr.base), assumptions):
return False
Rational = staticmethod(CommonHandler.AlwaysTrue)
Float = staticmethod(CommonHandler.AlwaysNone)
ImaginaryUnit, Infinity, NegativeInfinity, Pi, Exp1, GoldenRatio, TribonacciConstant = \
[staticmethod(CommonHandler.AlwaysFalse)]*7
@staticmethod
def exp(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@staticmethod
def cot(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return False
@staticmethod
def log(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
sin, cos, tan, asin, atan = [exp]*5
acos, acot = log, cot
class AskIrrationalHandler(CommonHandler):
@staticmethod
def Expr(expr, assumptions):
return expr.is_irrational
@staticmethod
def Basic(expr, assumptions):
_real = ask(Q.real(expr), assumptions)
if _real:
_rational = ask(Q.rational(expr), assumptions)
if _rational is None:
return None
return not _rational
else:
return _real
class AskRealHandler(CommonHandler):
"""
Handler for Q.real.
Test that an expression belongs to the field of real numbers.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_real
@staticmethod
def _number(expr, assumptions):
# let as_real_imag() work first since the expression may
# be simpler to evaluate
i = expr.as_real_imag()[1].evalf(2)
if i._prec != 1:
return not i
# allow None to be returned if we couldn't show for sure
# that i was 0
@staticmethod
def Add(expr, assumptions):
"""
Real + Real -> Real
Real + (Complex & !Real) -> !Real
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.real)
@staticmethod
def Mul(expr, assumptions):
"""
Real*Real -> Real
Real*Imaginary -> !Real
Imaginary*Imaginary -> Real
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
result = True
for arg in expr.args:
if ask(Q.real(arg), assumptions):
pass
elif ask(Q.imaginary(arg), assumptions):
result = result ^ True
else:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Real**Integer -> Real
Positive**Real -> Real
Real**(Integer/Even) -> Real if base is nonnegative
Real**(Integer/Odd) -> Real
Imaginary**(Integer/Even) -> Real
Imaginary**(Integer/Odd) -> not Real
Imaginary**Real -> ? since Real could be 0 (giving real) or 1 (giving imaginary)
b**Imaginary -> Real if log(b) is imaginary and b != 0 and exponent != integer multiple of I*pi/log(b)
Real**Real -> ? e.g. sqrt(-1) is imaginary and sqrt(2) is not
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
if expr.base.func == exp:
if ask(Q.imaginary(expr.base.args[0]), assumptions):
if ask(Q.imaginary(expr.exp), assumptions):
return True
# If the i = (exp's arg)/(I*pi) is an integer or half-integer
# multiple of I*pi then 2*i will be an integer. In addition,
# exp(i*I*pi) = (-1)**i so the overall realness of the expr
# can be determined by replacing exp(i*I*pi) with (-1)**i.
i = expr.base.args[0]/I/pi
if ask(Q.integer(2*i), assumptions):
return ask(Q.real(((-1)**i)**expr.exp), assumptions)
return
if ask(Q.imaginary(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
odd = ask(Q.odd(expr.exp), assumptions)
if odd is not None:
return not odd
return
if ask(Q.imaginary(expr.exp), assumptions):
imlog = ask(Q.imaginary(log(expr.base)), assumptions)
if imlog is not None:
# I**i -> real, log(I) is imag;
# (2*I)**i -> complex, log(2*I) is not imag
return imlog
if ask(Q.real(expr.base), assumptions):
if ask(Q.real(expr.exp), assumptions):
if expr.exp.is_Rational and \
ask(Q.even(expr.exp.q), assumptions):
return ask(Q.positive(expr.base), assumptions)
elif ask(Q.integer(expr.exp), assumptions):
return True
elif ask(Q.positive(expr.base), assumptions):
return True
elif ask(Q.negative(expr.base), assumptions):
return False
Rational, Float, Pi, Exp1, GoldenRatio, TribonacciConstant, Abs, re, im = \
[staticmethod(CommonHandler.AlwaysTrue)]*9
ImaginaryUnit, Infinity, NegativeInfinity = \
[staticmethod(CommonHandler.AlwaysFalse)]*3
@staticmethod
def sin(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
cos = sin
@staticmethod
def exp(expr, assumptions):
return ask(Q.integer(expr.args[0]/I/pi) | Q.real(expr.args[0]), assumptions)
@staticmethod
def log(expr, assumptions):
return ask(Q.positive(expr.args[0]), assumptions)
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.real_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskExtendedRealHandler(AskRealHandler):
"""
Handler for Q.extended_real.
Test that an expression belongs to the field of extended real numbers,
that is real numbers union {Infinity, -Infinity}.
"""
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.extended_real)
Mul, Pow = [Add]*2
Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysTrue)]*2
class AskHermitianHandler(AskRealHandler):
"""
Handler for Q.hermitian.
Test that an expression belongs to the field of Hermitian operators.
"""
@staticmethod
def Expr(expr, assumptions):
if isinstance(expr, MatrixBase):
return None
return AskRealHandler.Expr(expr, assumptions)
@staticmethod
def Add(expr, assumptions):
"""
Hermitian + Hermitian -> Hermitian
Hermitian + !Hermitian -> !Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.hermitian)
@staticmethod
def Mul(expr, assumptions):
"""
As long as there is at most only one noncommutative term:
Hermitian*Hermitian -> Hermitian
Hermitian*Antihermitian -> !Hermitian
Antihermitian*Antihermitian -> Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
nccount = 0
result = True
for arg in expr.args:
if ask(Q.antihermitian(arg), assumptions):
result = result ^ True
elif not ask(Q.hermitian(arg), assumptions):
break
if ask(~Q.commutative(arg), assumptions):
nccount += 1
if nccount > 1:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Hermitian**Integer -> Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
if ask(Q.hermitian(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
return True
@staticmethod
def sin(expr, assumptions):
if ask(Q.hermitian(expr.args[0]), assumptions):
return True
cos, exp = [sin]*2
@staticmethod
def MatrixBase(mat, assumptions):
rows, cols = mat.shape
ret_val = True
for i in range(rows):
for j in range(i, cols):
cond = fuzzy_bool(Eq(mat[i, j], conjugate(mat[j, i])))
if cond == None:
ret_val = None
if cond == False:
return False
return ret_val
class AskComplexHandler(CommonHandler):
"""
Handler for Q.complex.
Test that an expression belongs to the field of complex numbers.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_complex
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.complex)
Mul, Pow = [Add]*2
Number, sin, cos, log, exp, re, im, NumberSymbol, Abs, ImaginaryUnit = \
[staticmethod(CommonHandler.AlwaysTrue)]*10 # they are all complex functions or expressions
Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysFalse)]*2
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.complex_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskImaginaryHandler(CommonHandler):
"""
Handler for Q.imaginary.
Test that an expression belongs to the field of imaginary numbers,
that is, numbers in the form x*I, where x is real.
"""
@staticmethod
def Expr(expr, assumptions):
return expr.is_imaginary
@staticmethod
def _number(expr, assumptions):
# let as_real_imag() work first since the expression may
# be simpler to evaluate
r = expr.as_real_imag()[0].evalf(2)
if r._prec != 1:
return not r
# allow None to be returned if we couldn't show for sure
# that r was 0
@staticmethod
def Add(expr, assumptions):
"""
Imaginary + Imaginary -> Imaginary
Imaginary + Complex -> ?
Imaginary + Real -> !Imaginary
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
reals = 0
for arg in expr.args:
if ask(Q.imaginary(arg), assumptions):
pass
elif ask(Q.real(arg), assumptions):
reals += 1
else:
break
else:
if reals == 0:
return True
if reals == 1 or (len(expr.args) == reals):
# two reals could sum 0 thus giving an imaginary
return False
@staticmethod
def Mul(expr, assumptions):
"""
Real*Imaginary -> Imaginary
Imaginary*Imaginary -> Real
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
result = False
reals = 0
for arg in expr.args:
if ask(Q.imaginary(arg), assumptions):
result = result ^ True
elif not ask(Q.real(arg), assumptions):
break
else:
if reals == len(expr.args):
return False
return result
@staticmethod
def Pow(expr, assumptions):
"""
Imaginary**Odd -> Imaginary
Imaginary**Even -> Real
b**Imaginary -> !Imaginary if exponent is an integer multiple of I*pi/log(b)
Imaginary**Real -> ?
Positive**Real -> Real
Negative**Integer -> Real
Negative**(Integer/2) -> Imaginary
Negative**Real -> not Imaginary if exponent is not Rational
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
if expr.base.func == exp:
if ask(Q.imaginary(expr.base.args[0]), assumptions):
if ask(Q.imaginary(expr.exp), assumptions):
return False
i = expr.base.args[0]/I/pi
if ask(Q.integer(2*i), assumptions):
return ask(Q.imaginary(((-1)**i)**expr.exp), assumptions)
if ask(Q.imaginary(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
odd = ask(Q.odd(expr.exp), assumptions)
if odd is not None:
return odd
return
if ask(Q.imaginary(expr.exp), assumptions):
imlog = ask(Q.imaginary(log(expr.base)), assumptions)
if imlog is not None:
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions):
if ask(Q.positive(expr.base), assumptions):
return False
else:
rat = ask(Q.rational(expr.exp), assumptions)
if not rat:
return rat
if ask(Q.integer(expr.exp), assumptions):
return False
else:
half = ask(Q.integer(2*expr.exp), assumptions)
if half:
return ask(Q.negative(expr.base), assumptions)
return half
@staticmethod
def log(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
if ask(Q.positive(expr.args[0]), assumptions):
return False
return
# XXX it should be enough to do
# return ask(Q.nonpositive(expr.args[0]), assumptions)
# but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None;
# it should return True since exp(x) will be either 0 or complex
if expr.args[0].func == exp:
if expr.args[0].args[0] in [I, -I]:
return True
im = ask(Q.imaginary(expr.args[0]), assumptions)
if im is False:
return False
@staticmethod
def exp(expr, assumptions):
a = expr.args[0]/I/pi
return ask(Q.integer(2*a) & ~Q.integer(a), assumptions)
@staticmethod
def Number(expr, assumptions):
return not (expr.as_real_imag()[1] == 0)
NumberSymbol = Number
ImaginaryUnit = staticmethod(CommonHandler.AlwaysTrue)
class AskAntiHermitianHandler(AskImaginaryHandler):
"""
Handler for Q.antihermitian.
Test that an expression belongs to the field of anti-Hermitian operators,
that is, operators in the form x*I, where x is Hermitian.
"""
@staticmethod
def Expr(expr, assumptions):
if isinstance(expr, MatrixBase):
return None
return AskImaginaryHandler.Expr(expr, assumptions)
@staticmethod
def Add(expr, assumptions):
"""
Antihermitian + Antihermitian -> Antihermitian
Antihermitian + !Antihermitian -> !Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.antihermitian)
@staticmethod
def Mul(expr, assumptions):
"""
As long as there is at most only one noncommutative term:
Hermitian*Hermitian -> !Antihermitian
Hermitian*Antihermitian -> Antihermitian
Antihermitian*Antihermitian -> !Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
nccount = 0
result = False
for arg in expr.args:
if ask(Q.antihermitian(arg), assumptions):
result = result ^ True
elif not ask(Q.hermitian(arg), assumptions):
break
if ask(~Q.commutative(arg), assumptions):
nccount += 1
if nccount > 1:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Hermitian**Integer -> !Antihermitian
Antihermitian**Even -> !Antihermitian
Antihermitian**Odd -> Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
if ask(Q.hermitian(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
return False
elif ask(Q.antihermitian(expr.base), assumptions):
if ask(Q.even(expr.exp), assumptions):
return False
elif ask(Q.odd(expr.exp), assumptions):
return True
@staticmethod
def MatrixBase(mat, assumptions):
rows, cols = mat.shape
ret_val = True
for i in range(rows):
for j in range(i, cols):
cond = fuzzy_bool(Eq(mat[i, j], -conjugate(mat[j, i])))
if cond == None:
ret_val = None
if cond == False:
return False
return ret_val
class AskAlgebraicHandler(CommonHandler):
"""Handler for Q.algebraic key. """
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.algebraic)
@staticmethod
def Mul(expr, assumptions):
return test_closed_group(expr, assumptions, Q.algebraic)
@staticmethod
def Pow(expr, assumptions):
return expr.exp.is_Rational and ask(
Q.algebraic(expr.base), assumptions)
@staticmethod
def Rational(expr, assumptions):
return expr.q != 0
Float, GoldenRatio, TribonacciConstant, ImaginaryUnit, AlgebraicNumber = \
[staticmethod(CommonHandler.AlwaysTrue)]*5
Infinity, NegativeInfinity, ComplexInfinity, Pi, Exp1 = \
[staticmethod(CommonHandler.AlwaysFalse)]*5
@staticmethod
def exp(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@staticmethod
def cot(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return False
@staticmethod
def log(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
sin, cos, tan, asin, atan = [exp]*5
acos, acot = log, cot
|
0ef83bd8bf03b979f06cc06adbea62217113d6db894e735a82e6498d2bc25229 | from typing import List
from functools import reduce
from sympy.core import S, sympify, Dummy, Mod
from sympy.core.cache import cacheit
from sympy.core.compatibility import HAS_GMPY
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.logic import fuzzy_and
from sympy.core.numbers import Integer, pi
from sympy.core.relational import Eq
from sympy.ntheory import sieve
from sympy.polys.polytools import Poly
from math import sqrt as _sqrt
class CombinatorialFunction(Function):
"""Base class for combinatorial functions. """
def _eval_simplify(self, **kwargs):
from sympy.simplify.combsimp import combsimp
# combinatorial function with non-integer arguments is
# automatically passed to gammasimp
expr = combsimp(self)
measure = kwargs['measure']
if measure(expr) <= kwargs['ratio']*measure(self):
return expr
return self
###############################################################################
######################## FACTORIAL and MULTI-FACTORIAL ########################
###############################################################################
class factorial(CombinatorialFunction):
r"""Implementation of factorial function over nonnegative integers.
By convention (consistent with the gamma function and the binomial
coefficients), factorial of a negative integer is complex infinity.
The factorial is very important in combinatorics where it gives
the number of ways in which `n` objects can be permuted. It also
arises in calculus, probability, number theory, etc.
There is strict relation of factorial with gamma function. In
fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this
kind is very useful in case of combinatorial simplification.
Computation of the factorial is done using two algorithms. For
small arguments a precomputed look up table is used. However for bigger
input algorithm Prime-Swing is used. It is the fastest algorithm
known and computes `n!` via prime factorization of special class
of numbers, called here the 'Swing Numbers'.
Examples
========
>>> from sympy import Symbol, factorial, S
>>> n = Symbol('n', integer=True)
>>> factorial(0)
1
>>> factorial(7)
5040
>>> factorial(-2)
zoo
>>> factorial(n)
factorial(n)
>>> factorial(2*n)
factorial(2*n)
>>> factorial(S(1)/2)
factorial(1/2)
See Also
========
factorial2, RisingFactorial, FallingFactorial
"""
def fdiff(self, argindex=1):
from sympy import gamma, polygamma
if argindex == 1:
return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1)
else:
raise ArgumentIndexError(self, argindex)
_small_swing = [
1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395,
12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075,
35102025, 5014575, 145422675, 9694845, 300540195, 300540195
]
_small_factorials = [] # type: List[int]
@classmethod
def _swing(cls, n):
if n < 33:
return cls._small_swing[n]
else:
N, primes = int(_sqrt(n)), []
for prime in sieve.primerange(3, N + 1):
p, q = 1, n
while True:
q //= prime
if q > 0:
if q & 1 == 1:
p *= prime
else:
break
if p > 1:
primes.append(p)
for prime in sieve.primerange(N + 1, n//3 + 1):
if (n // prime) & 1 == 1:
primes.append(prime)
L_product = R_product = 1
for prime in sieve.primerange(n//2 + 1, n + 1):
L_product *= prime
for prime in primes:
R_product *= prime
return L_product*R_product
@classmethod
def _recursive(cls, n):
if n < 2:
return 1
else:
return (cls._recursive(n//2)**2)*cls._swing(n)
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Number:
if n.is_zero:
return S.One
elif n is S.Infinity:
return S.Infinity
elif n.is_Integer:
if n.is_negative:
return S.ComplexInfinity
else:
n = n.p
if n < 20:
if not cls._small_factorials:
result = 1
for i in range(1, 20):
result *= i
cls._small_factorials.append(result)
result = cls._small_factorials[n-1]
# GMPY factorial is faster, use it when available
elif HAS_GMPY:
from sympy.core.compatibility import gmpy
result = gmpy.fac(n)
else:
bits = bin(n).count('1')
result = cls._recursive(n)*2**(n - bits)
return Integer(result)
def _facmod(self, n, q):
res, N = 1, int(_sqrt(n))
# Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ...
# for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m,
# occur consecutively and are grouped together in pw[m] for
# simultaneous exponentiation at a later stage
pw = [1]*N
m = 2 # to initialize the if condition below
for prime in sieve.primerange(2, n + 1):
if m > 1:
m, y = 0, n // prime
while y:
m += y
y //= prime
if m < N:
pw[m] = pw[m]*prime % q
else:
res = res*pow(prime, m, q) % q
for ex, bs in enumerate(pw):
if ex == 0 or bs == 1:
continue
if bs == 0:
return 0
res = res*pow(bs, ex, q) % q
return res
def _eval_Mod(self, q):
n = self.args[0]
if n.is_integer and n.is_nonnegative and q.is_integer:
aq = abs(q)
d = aq - n
if d.is_nonpositive:
return S.Zero
else:
isprime = aq.is_prime
if d == 1:
# Apply Wilson's theorem (if a natural number n > 1
# is a prime number, then (n-1)! = -1 mod n) and
# its inverse (if n > 4 is a composite number, then
# (n-1)! = 0 mod n)
if isprime:
return S(-1 % q)
elif isprime is False and (aq - 6).is_nonnegative:
return S.Zero
elif n.is_Integer and q.is_Integer:
n, d, aq = map(int, (n, d, aq))
if isprime and (d - 1 < n):
fc = self._facmod(d - 1, aq)
fc = pow(fc, aq - 2, aq)
if d%2:
fc = -fc
else:
fc = self._facmod(n, aq)
return S(fc % q)
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
from sympy import gamma
return gamma(n + 1)
def _eval_rewrite_as_Product(self, n, **kwargs):
from sympy import Product
if n.is_nonnegative and n.is_integer:
i = Dummy('i', integer=True)
return Product(i, (i, 1, n))
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_positive(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_even(self):
x = self.args[0]
if x.is_integer and x.is_nonnegative:
return (x - 2).is_nonnegative
def _eval_is_composite(self):
x = self.args[0]
if x.is_integer and x.is_nonnegative:
return (x - 3).is_nonnegative
def _eval_is_real(self):
x = self.args[0]
if x.is_nonnegative or x.is_noninteger:
return True
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0]
arg_1 = arg.as_leading_term(x)
if Order(x, x).contains(arg_1):
return S.One
if Order(1, x).contains(arg_1):
return self.func(arg_1)
####################################################
# The correct result here should be 'None'. #
# Indeed arg in not bounded as x tends to 0. #
# Consequently the series expansion does not admit #
# the leading term. #
# For compatibility reasons, the return value here #
# is the original function, i.e. factorial(arg), #
# instead of None. #
####################################################
return self.func(arg)
class MultiFactorial(CombinatorialFunction):
pass
class subfactorial(CombinatorialFunction):
r"""The subfactorial counts the derangements of n items and is
defined for non-negative integers as:
.. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\
(n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases}
It can also be written as ``int(round(n!/exp(1)))`` but the
recursive definition with caching is implemented for this function.
An interesting analytic expression is the following [2]_
.. math:: !x = \Gamma(x + 1, -1)/e
which is valid for non-negative integers `x`. The above formula
is not very useful incase of non-integers. :math:`\Gamma(x + 1, -1)` is
single-valued only for integral arguments `x`, elsewhere on the positive
real axis it has an infinite number of branches none of which are real.
References
==========
.. [1] https://en.wikipedia.org/wiki/Subfactorial
.. [2] http://mathworld.wolfram.com/Subfactorial.html
Examples
========
>>> from sympy import subfactorial
>>> from sympy.abc import n
>>> subfactorial(n + 1)
subfactorial(n + 1)
>>> subfactorial(5)
44
See Also
========
sympy.functions.combinatorial.factorials.factorial,
sympy.utilities.iterables.generate_derangements,
sympy.functions.special.gamma_functions.uppergamma
"""
@classmethod
@cacheit
def _eval(self, n):
if not n:
return S.One
elif n == 1:
return S.Zero
else:
z1, z2 = 1, 0
for i in range(2, n + 1):
z1, z2 = z2, (i - 1)*(z2 + z1)
return z2
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg.is_Integer and arg.is_nonnegative:
return cls._eval(arg)
elif arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
def _eval_is_even(self):
if self.args[0].is_odd and self.args[0].is_nonnegative:
return True
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_rewrite_as_factorial(self, arg, **kwargs):
from sympy import summation
i = Dummy('i')
f = S.NegativeOne**i / factorial(i)
return factorial(arg) * summation(f, (i, 0, arg))
def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs):
from sympy import exp, gamma, I, lowergamma
return ((-1)**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1) + gamma(arg + 1))*exp(-1)
def _eval_rewrite_as_uppergamma(self, arg, **kwargs):
from sympy import uppergamma
return uppergamma(arg + 1, -1)/S.Exp1
def _eval_is_nonnegative(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_odd(self):
if self.args[0].is_even and self.args[0].is_nonnegative:
return True
class factorial2(CombinatorialFunction):
r"""The double factorial `n!!`, not to be confused with `(n!)!`
The double factorial is defined for nonnegative integers and for odd
negative integers as:
.. math:: n!! = \begin{cases} 1 & n = 0 \\
n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\
n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\
(n+2)!!/(n+2) & n\ \text{negative odd} \end{cases}
References
==========
.. [1] https://en.wikipedia.org/wiki/Double_factorial
Examples
========
>>> from sympy import factorial2, var
>>> n = var('n')
>>> n
n
>>> factorial2(n + 1)
factorial2(n + 1)
>>> factorial2(5)
15
>>> factorial2(-1)
1
>>> factorial2(-5)
1/3
See Also
========
factorial, RisingFactorial, FallingFactorial
"""
@classmethod
def eval(cls, arg):
# TODO: extend this to complex numbers?
if arg.is_Number:
if not arg.is_Integer:
raise ValueError("argument must be nonnegative integer "
"or negative odd integer")
# This implementation is faster than the recursive one
# It also avoids "maximum recursion depth exceeded" runtime error
if arg.is_nonnegative:
if arg.is_even:
k = arg / 2
return 2**k * factorial(k)
return factorial(arg) / factorial2(arg - 1)
if arg.is_odd:
return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg)
raise ValueError("argument must be nonnegative integer "
"or negative odd integer")
def _eval_is_even(self):
# Double factorial is even for every positive even input
n = self.args[0]
if n.is_integer:
if n.is_odd:
return False
if n.is_even:
if n.is_positive:
return True
if n.is_zero:
return False
def _eval_is_integer(self):
# Double factorial is an integer for every nonnegative input, and for
# -1 and -3
n = self.args[0]
if n.is_integer:
if (n + 1).is_nonnegative:
return True
if n.is_odd:
return (n + 3).is_nonnegative
def _eval_is_odd(self):
# Double factorial is odd for every odd input not smaller than -3, and
# for 0
n = self.args[0]
if n.is_odd:
return (n + 3).is_nonnegative
if n.is_even:
if n.is_positive:
return False
if n.is_zero:
return True
def _eval_is_positive(self):
# Double factorial is positive for every nonnegative input, and for
# every odd negative input which is of the form -1-4k for an
# nonnegative integer k
n = self.args[0]
if n.is_integer:
if (n + 1).is_nonnegative:
return True
if n.is_odd:
return ((n + 1) / 2).is_even
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
from sympy import gamma, Piecewise, sqrt
return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)),
(sqrt(2/pi), Eq(Mod(n, 2), 1)))
###############################################################################
######################## RISING and FALLING FACTORIALS ########################
###############################################################################
class RisingFactorial(CombinatorialFunction):
r"""
Rising factorial (also called Pochhammer symbol) is a double valued
function arising in concrete mathematics, hypergeometric functions
and series expansions. It is defined by:
.. math:: rf(x,k) = x \cdot (x+1) \cdots (x+k-1)
where `x` can be arbitrary expression and `k` is an integer. For
more information check "Concrete mathematics" by Graham, pp. 66
or visit http://mathworld.wolfram.com/RisingFactorial.html page.
When `x` is a Poly instance of degree >= 1 with a single variable,
`rf(x,k) = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the
variable of `x`. This is as described in Peter Paule, "Greatest
Factorial Factorization and Symbolic Summation", Journal of
Symbolic Computation, vol. 20, pp. 235-268, 1995.
Examples
========
>>> from sympy import rf, Poly
>>> from sympy.abc import x
>>> rf(x, 0)
1
>>> rf(1, 5)
120
>>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
True
>>> rf(Poly(x**3, x), 2)
Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ')
Rewriting is complicated unless the relationship between
the arguments is known, but rising factorial can
be rewritten in terms of gamma, factorial and binomial
and falling factorial.
>>> from sympy import Symbol, factorial, ff, binomial, gamma
>>> n = Symbol('n', integer=True, positive=True)
>>> R = rf(n, n + 2)
>>> for i in (rf, ff, factorial, binomial, gamma):
... R.rewrite(i)
...
RisingFactorial(n, n + 2)
FallingFactorial(2*n + 1, n + 2)
factorial(2*n + 1)/factorial(n - 1)
binomial(2*n + 1, n + 2)*factorial(n + 2)
gamma(2*n + 2)/gamma(n)
See Also
========
factorial, factorial2, FallingFactorial
References
==========
.. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol
"""
@classmethod
def eval(cls, x, k):
x = sympify(x)
k = sympify(k)
if x is S.NaN or k is S.NaN:
return S.NaN
elif x is S.One:
return factorial(k)
elif k.is_Integer:
if k.is_zero:
return S.One
else:
if k.is_positive:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
if k.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("rf only defined for "
"polynomials on one generator")
else:
return reduce(lambda r, i:
r*(x.shift(i)),
range(0, int(k)), 1)
else:
return reduce(lambda r, i: r*(x + i),
range(0, int(k)), 1)
else:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("rf only defined for "
"polynomials on one generator")
else:
return 1/reduce(lambda r, i:
r*(x.shift(-i)),
range(1, abs(int(k)) + 1), 1)
else:
return 1/reduce(lambda r, i:
r*(x - i),
range(1, abs(int(k)) + 1), 1)
if k.is_integer == False:
if x.is_integer and x.is_negative:
return S.Zero
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
from sympy import gamma, Piecewise
if not piecewise:
if (x <= 0) == True:
return (-1)**k*gamma(1 - x) / gamma(-k - x + 1)
return gamma(x + k) / gamma(x)
return Piecewise(
(gamma(x + k) / gamma(x), x > 0),
((-1)**k*gamma(1 - x) / gamma(-k - x + 1), True))
def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs):
return FallingFactorial(x + k - 1, k)
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
from sympy import Piecewise
if x.is_integer and k.is_integer:
return Piecewise(
(factorial(k + x - 1)/factorial(x - 1), x > 0),
((-1)**k*factorial(-x)/factorial(-k - x), True))
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
if k.is_integer:
return factorial(k) * binomial(x + k - 1, k)
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
from sympy import gamma
if limitvar:
k_lim = k.subs(limitvar, S.Infinity)
if k_lim is S.Infinity:
return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x))
elif k_lim is S.NegativeInfinity:
return ((-1)**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True))
return self.rewrite(gamma).rewrite('tractable', deep=True)
def _eval_is_integer(self):
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
self.args[1].is_nonnegative))
def _sage_(self):
import sage.all as sage
return sage.rising_factorial(self.args[0]._sage_(),
self.args[1]._sage_())
class FallingFactorial(CombinatorialFunction):
r"""
Falling factorial (related to rising factorial) is a double valued
function arising in concrete mathematics, hypergeometric functions
and series expansions. It is defined by
.. math:: ff(x,k) = x \cdot (x-1) \cdots (x-k+1)
where `x` can be arbitrary expression and `k` is an integer. For
more information check "Concrete mathematics" by Graham, pp. 66
or visit http://mathworld.wolfram.com/FallingFactorial.html page.
When `x` is a Poly instance of degree >= 1 with single variable,
`ff(x,k) = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the
variable of `x`. This is as described in Peter Paule, "Greatest
Factorial Factorization and Symbolic Summation", Journal of
Symbolic Computation, vol. 20, pp. 235-268, 1995.
>>> from sympy import ff, Poly, Symbol
>>> from sympy.abc import x
>>> n = Symbol('n', integer=True)
>>> ff(x, 0)
1
>>> ff(5, 5)
120
>>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
True
>>> ff(Poly(x**2, x), 2)
Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
>>> ff(n, n)
factorial(n)
Rewriting is complicated unless the relationship between
the arguments is known, but falling factorial can
be rewritten in terms of gamma, factorial and binomial
and rising factorial.
>>> from sympy import factorial, rf, gamma, binomial, Symbol
>>> n = Symbol('n', integer=True, positive=True)
>>> F = ff(n, n - 2)
>>> for i in (rf, ff, factorial, binomial, gamma):
... F.rewrite(i)
...
RisingFactorial(3, n - 2)
FallingFactorial(n, n - 2)
factorial(n)/2
binomial(n, n - 2)*factorial(n - 2)
gamma(n + 1)/2
See Also
========
factorial, factorial2, RisingFactorial
References
==========
.. [1] http://mathworld.wolfram.com/FallingFactorial.html
"""
@classmethod
def eval(cls, x, k):
x = sympify(x)
k = sympify(k)
if x is S.NaN or k is S.NaN:
return S.NaN
elif k.is_integer and x == k:
return factorial(x)
elif k.is_Integer:
if k.is_zero:
return S.One
else:
if k.is_positive:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
if k.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("ff only defined for "
"polynomials on one generator")
else:
return reduce(lambda r, i:
r*(x.shift(-i)),
range(0, int(k)), 1)
else:
return reduce(lambda r, i: r*(x - i),
range(0, int(k)), 1)
else:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("rf only defined for "
"polynomials on one generator")
else:
return 1/reduce(lambda r, i:
r*(x.shift(i)),
range(1, abs(int(k)) + 1), 1)
else:
return 1/reduce(lambda r, i: r*(x + i),
range(1, abs(int(k)) + 1), 1)
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
from sympy import gamma, Piecewise
if not piecewise:
if (x < 0) == True:
return (-1)**k*gamma(k - x) / gamma(-x)
return gamma(x + 1) / gamma(x - k + 1)
return Piecewise(
(gamma(x + 1) / gamma(x - k + 1), x >= 0),
((-1)**k*gamma(k - x) / gamma(-x), True))
def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs):
return rf(x - k + 1, k)
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
if k.is_integer:
return factorial(k) * binomial(x, k)
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
from sympy import Piecewise
if x.is_integer and k.is_integer:
return Piecewise(
(factorial(x)/factorial(-k + x), x >= 0),
((-1)**k*factorial(k - x - 1)/factorial(-x - 1), True))
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
from sympy import gamma
if limitvar:
k_lim = k.subs(limitvar, S.Infinity)
if k_lim is S.Infinity:
return ((-1)**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x))
elif k_lim is S.NegativeInfinity:
return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True))
return self.rewrite(gamma).rewrite('tractable', deep=True)
def _eval_is_integer(self):
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
self.args[1].is_nonnegative))
def _sage_(self):
import sage.all as sage
return sage.falling_factorial(self.args[0]._sage_(),
self.args[1]._sage_())
rf = RisingFactorial
ff = FallingFactorial
###############################################################################
########################### BINOMIAL COEFFICIENTS #############################
###############################################################################
class binomial(CombinatorialFunction):
r"""Implementation of the binomial coefficient. It can be defined
in two ways depending on its desired interpretation:
.. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\
\binom{n}{k} = \frac{ff(n, k)}{k!}
First, in a strict combinatorial sense it defines the
number of ways we can choose `k` elements from a set of
`n` elements. In this case both arguments are nonnegative
integers and binomial is computed using an efficient
algorithm based on prime factorization.
The other definition is generalization for arbitrary `n`,
however `k` must also be nonnegative. This case is very
useful when evaluating summations.
For the sake of convenience for negative integer `k` this function
will return zero no matter what valued is the other argument.
To expand the binomial when `n` is a symbol, use either
``expand_func()`` or ``expand(func=True)``. The former will keep
the polynomial in factored form while the latter will expand the
polynomial itself. See examples for details.
Examples
========
>>> from sympy import Symbol, Rational, binomial, expand_func
>>> n = Symbol('n', integer=True, positive=True)
>>> binomial(15, 8)
6435
>>> binomial(n, -1)
0
Rows of Pascal's triangle can be generated with the binomial function:
>>> for N in range(8):
... print([binomial(N, i) for i in range(N + 1)])
...
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
As can a given diagonal, e.g. the 4th diagonal:
>>> N = -4
>>> [binomial(N, i) for i in range(1 - N)]
[1, -4, 10, -20, 35]
>>> binomial(Rational(5, 4), 3)
-5/128
>>> binomial(Rational(-5, 4), 3)
-195/128
>>> binomial(n, 3)
binomial(n, 3)
>>> binomial(n, 3).expand(func=True)
n**3/6 - n**2/2 + n/3
>>> expand_func(binomial(n, 3))
n*(n - 2)*(n - 1)/6
References
==========
.. [1] https://www.johndcook.com/blog/binomial_coefficients/
"""
def fdiff(self, argindex=1):
from sympy import polygamma
if argindex == 1:
# http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/
n, k = self.args
return binomial(n, k)*(polygamma(0, n + 1) - \
polygamma(0, n - k + 1))
elif argindex == 2:
# http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/
n, k = self.args
return binomial(n, k)*(polygamma(0, n - k + 1) - \
polygamma(0, k + 1))
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def _eval(self, n, k):
# n.is_Number and k.is_Integer and k != 1 and n != k
if k.is_Integer:
if n.is_Integer and n >= 0:
n, k = int(n), int(k)
if k > n:
return S.Zero
elif k > n // 2:
k = n - k
if HAS_GMPY:
from sympy.core.compatibility import gmpy
return Integer(gmpy.bincoef(n, k))
d, result = n - k, 1
for i in range(1, k + 1):
d += 1
result = result * d // i
return Integer(result)
else:
d, result = n - k, 1
for i in range(1, k + 1):
d += 1
result *= d
result /= i
return result
@classmethod
def eval(cls, n, k):
n, k = map(sympify, (n, k))
d = n - k
n_nonneg, n_isint = n.is_nonnegative, n.is_integer
if k.is_zero or ((n_nonneg or n_isint is False)
and d.is_zero):
return S.One
if (k - 1).is_zero or ((n_nonneg or n_isint is False)
and (d - 1).is_zero):
return n
if k.is_integer:
if k.is_negative or (n_nonneg and n_isint and d.is_negative):
return S.Zero
elif n.is_number:
res = cls._eval(n, k)
return res.expand(basic=True) if res else res
elif n_nonneg is False and n_isint:
# a special case when binomial evaluates to complex infinity
return S.ComplexInfinity
elif k.is_number:
from sympy import gamma
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
def _eval_Mod(self, q):
n, k = self.args
if any(x.is_integer is False for x in (n, k, q)):
raise ValueError("Integers expected for binomial Mod")
if all(x.is_Integer for x in (n, k, q)):
n, k = map(int, (n, k))
aq, res = abs(q), 1
# handle negative integers k or n
if k < 0:
return S.Zero
if n < 0:
n = -n + k - 1
res = -1 if k%2 else 1
# non negative integers k and n
if k > n:
return S.Zero
isprime = aq.is_prime
aq = int(aq)
if isprime:
if aq < n:
# use Lucas Theorem
N, K = n, k
while N or K:
res = res*binomial(N % aq, K % aq) % aq
N, K = N // aq, K // aq
else:
# use Factorial Modulo
d = n - k
if k > d:
k, d = d, k
kf = 1
for i in range(2, k + 1):
kf = kf*i % aq
df = kf
for i in range(k + 1, d + 1):
df = df*i % aq
res *= df
for i in range(d + 1, n + 1):
res = res*i % aq
res *= pow(kf*df % aq, aq - 2, aq)
res %= aq
else:
# Binomial Factorization is performed by calculating the
# exponents of primes <= n in `n! /(k! (n - k)!)`,
# for non-negative integers n and k. As the exponent of
# prime in n! is e_p(n) = [n/p] + [n/p**2] + ...
# the exponent of prime in binomial(n, k) would be
# e_p(n) - e_p(k) - e_p(n - k)
M = int(_sqrt(n))
for prime in sieve.primerange(2, n + 1):
if prime > n - k:
res = res*prime % aq
elif prime > n // 2:
continue
elif prime > M:
if n % prime < k % prime:
res = res*prime % aq
else:
N, K = n, k
exp = a = 0
while N > 0:
a = int((N % prime) < (K % prime + a))
N, K = N // prime, K // prime
exp += a
if exp > 0:
res *= pow(prime, exp, aq)
res %= aq
return S(res % q)
def _eval_expand_func(self, **hints):
"""
Function to expand binomial(n, k) when m is positive integer
Also,
n is self.args[0] and k is self.args[1] while using binomial(n, k)
"""
n = self.args[0]
if n.is_Number:
return binomial(*self.args)
k = self.args[1]
if (n-k).is_Integer:
k = n - k
if k.is_Integer:
if k.is_zero:
return S.One
elif k.is_negative:
return S.Zero
else:
n, result = self.args[0], 1
for i in range(1, k + 1):
result *= n - k + i
result /= i
return result
else:
return binomial(*self.args)
def _eval_rewrite_as_factorial(self, n, k, **kwargs):
return factorial(n)/(factorial(k)*factorial(n - k))
def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs):
from sympy import gamma
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs):
return self._eval_rewrite_as_gamma(n, k).rewrite('tractable')
def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs):
if k.is_integer:
return ff(n, k) / factorial(k)
def _eval_is_integer(self):
n, k = self.args
if n.is_integer and k.is_integer:
return True
elif k.is_integer is False:
return False
def _eval_is_nonnegative(self):
n, k = self.args
if n.is_integer and k.is_integer:
if n.is_nonnegative or k.is_negative or k.is_even:
return True
elif k.is_even is False:
return False
|
6ca4089999ada8204c0b0336041b307beb55bbb053c20759e2543f58d1bca43a | from sympy.core import Basic, S, Function, diff, Tuple, Dummy
from sympy.core.basic import as_Basic
from sympy.core.numbers import Rational, NumberSymbol
from sympy.core.relational import (Equality, Unequality, Relational,
_canonical)
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or,
true, false, Or, ITE, simplify_logic)
from sympy.utilities.iterables import uniq, ordered, product, sift
from sympy.utilities.misc import filldedent, func_name
Undefined = S.NaN # Piecewise()
class ExprCondPair(Tuple):
"""Represents an expression, condition pair."""
def __new__(cls, expr, cond):
expr = as_Basic(expr)
if cond == True:
return Tuple.__new__(cls, expr, true)
elif cond == False:
return Tuple.__new__(cls, expr, false)
elif isinstance(cond, Basic) and cond.has(Piecewise):
cond = piecewise_fold(cond)
if isinstance(cond, Piecewise):
cond = cond.rewrite(ITE)
if not isinstance(cond, Boolean):
raise TypeError(filldedent('''
Second argument must be a Boolean,
not `%s`''' % func_name(cond)))
return Tuple.__new__(cls, expr, cond)
@property
def expr(self):
"""
Returns the expression of this pair.
"""
return self.args[0]
@property
def cond(self):
"""
Returns the condition of this pair.
"""
return self.args[1]
@property
def is_commutative(self):
return self.expr.is_commutative
def __iter__(self):
yield self.expr
yield self.cond
def _eval_simplify(self, **kwargs):
return self.func(*[a.simplify(**kwargs) for a in self.args])
class Piecewise(Function):
"""
Represents a piecewise function.
Usage:
Piecewise( (expr,cond), (expr,cond), ... )
- Each argument is a 2-tuple defining an expression and condition
- The conds are evaluated in turn returning the first that is True.
If any of the evaluated conds are not determined explicitly False,
e.g. x < 1, the function is returned in symbolic form.
- If the function is evaluated at a place where all conditions are False,
nan will be returned.
- Pairs where the cond is explicitly False, will be removed.
Examples
========
>>> from sympy import Piecewise, log, piecewise_fold
>>> from sympy.abc import x, y
>>> f = x**2
>>> g = log(x)
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
>>> p.subs(x,1)
1
>>> p.subs(x,5)
log(5)
Booleans can contain Piecewise elements:
>>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
Piecewise((2, x < 0), (3, True)) < y
The folded version of this results in a Piecewise whose
expressions are Booleans:
>>> folded_cond = piecewise_fold(cond); folded_cond
Piecewise((2 < y, x < 0), (3 < y, True))
When a Boolean containing Piecewise (like cond) or a Piecewise
with Boolean expressions (like folded_cond) is used as a condition,
it is converted to an equivalent ITE object:
>>> Piecewise((1, folded_cond))
Piecewise((1, ITE(x < 0, y > 2, y > 3)))
When a condition is an ITE, it will be converted to a simplified
Boolean expression:
>>> piecewise_fold(_)
Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
See Also
========
piecewise_fold, ITE
"""
nargs = None
is_Piecewise = True
def __new__(cls, *args, **options):
if len(args) == 0:
raise TypeError("At least one (expr, cond) pair expected.")
# (Try to) sympify args first
newargs = []
for ec in args:
# ec could be a ExprCondPair or a tuple
pair = ExprCondPair(*getattr(ec, 'args', ec))
cond = pair.cond
if cond is false:
continue
newargs.append(pair)
if cond is true:
break
if options.pop('evaluate', True):
r = cls.eval(*newargs)
else:
r = None
if r is None:
return Basic.__new__(cls, *newargs, **options)
else:
return r
@classmethod
def eval(cls, *_args):
"""Either return a modified version of the args or, if no
modifications were made, return None.
Modifications that are made here:
1) relationals are made canonical
2) any False conditions are dropped
3) any repeat of a previous condition is ignored
3) any args past one with a true condition are dropped
If there are no args left, nan will be returned.
If there is a single arg with a True condition, its
corresponding expression will be returned.
"""
from sympy.functions.elementary.complexes import im, re
if not _args:
return Undefined
if len(_args) == 1 and _args[0][-1] == True:
return _args[0][0]
newargs = [] # the unevaluated conditions
current_cond = set() # the conditions up to a given e, c pair
# make conditions canonical
args = []
for e, c in _args:
if (not c.is_Atom and not isinstance(c, Relational) and
not c.has(im, re)):
free = c.free_symbols
if len(free) == 1:
funcs = [i for i in c.atoms(Function)
if not isinstance(i, Boolean)]
if len(funcs) == 1 and len(
c.xreplace({list(funcs)[0]: Dummy()}
).free_symbols) == 1:
# we can treat function like a symbol
free = funcs
_c = c
x = free.pop()
try:
c = c.as_set().as_relational(x)
except NotImplementedError:
pass
else:
reps = {}
for i in c.atoms(Relational):
ic = i.canonical
if ic.rhs in (S.Infinity, S.NegativeInfinity):
if not _c.has(ic.rhs):
# don't accept introduction of
# new Relationals with +/-oo
reps[i] = S.true
elif ('=' not in ic.rel_op and
c.xreplace({x: i.rhs}) !=
_c.xreplace({x: i.rhs})):
reps[i] = Relational(
i.lhs, i.rhs, i.rel_op + '=')
c = c.xreplace(reps)
args.append((e, _canonical(c)))
for expr, cond in args:
# Check here if expr is a Piecewise and collapse if one of
# the conds in expr matches cond. This allows the collapsing
# of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
# This is important when using piecewise_fold to simplify
# multiple Piecewise instances having the same conds.
# Eventually, this code should be able to collapse Piecewise's
# having different intervals, but this will probably require
# using the new assumptions.
if isinstance(expr, Piecewise):
unmatching = []
for i, (e, c) in enumerate(expr.args):
if c in current_cond:
# this would already have triggered
continue
if c == cond:
if c != True:
# nothing past this condition will ever
# trigger and only those args before this
# that didn't match a previous condition
# could possibly trigger
if unmatching:
expr = Piecewise(*(
unmatching + [(e, c)]))
else:
expr = e
break
else:
unmatching.append((e, c))
# check for condition repeats
got = False
# -- if an And contains a condition that was
# already encountered, then the And will be
# False: if the previous condition was False
# then the And will be False and if the previous
# condition is True then then we wouldn't get to
# this point. In either case, we can skip this condition.
for i in ([cond] +
(list(cond.args) if isinstance(cond, And) else
[])):
if i in current_cond:
got = True
break
if got:
continue
# -- if not(c) is already in current_cond then c is
# a redundant condition in an And. This does not
# apply to Or, however: (e1, c), (e2, Or(~c, d))
# is not (e1, c), (e2, d) because if c and d are
# both False this would give no results when the
# true answer should be (e2, True)
if isinstance(cond, And):
nonredundant = []
for c in cond.args:
if (isinstance(c, Relational) and
c.negated.canonical in current_cond):
continue
nonredundant.append(c)
cond = cond.func(*nonredundant)
elif isinstance(cond, Relational):
if cond.negated.canonical in current_cond:
cond = S.true
current_cond.add(cond)
# collect successive e,c pairs when exprs or cond match
if newargs:
if newargs[-1].expr == expr:
orcond = Or(cond, newargs[-1].cond)
if isinstance(orcond, (And, Or)):
orcond = distribute_and_over_or(orcond)
newargs[-1] = ExprCondPair(expr, orcond)
continue
elif newargs[-1].cond == cond:
newargs[-1] = ExprCondPair(expr, cond)
continue
newargs.append(ExprCondPair(expr, cond))
# some conditions may have been redundant
missing = len(newargs) != len(_args)
# some conditions may have changed
same = all(a == b for a, b in zip(newargs, _args))
# if either change happened we return the expr with the
# updated args
if not newargs:
raise ValueError(filldedent('''
There are no conditions (or none that
are not trivially false) to define an
expression.'''))
if missing or not same:
return cls(*newargs)
def doit(self, **hints):
"""
Evaluate this piecewise function.
"""
newargs = []
for e, c in self.args:
if hints.get('deep', True):
if isinstance(e, Basic):
newe = e.doit(**hints)
if newe != self:
e = newe
if isinstance(c, Basic):
c = c.doit(**hints)
newargs.append((e, c))
return self.func(*newargs)
def _eval_simplify(self, **kwargs):
return piecewise_simplify(self, **kwargs)
def _eval_as_leading_term(self, x, cdir=0):
for e, c in self.args:
if c == True or c.subs(x, 0) == True:
return e.as_leading_term(x)
def _eval_adjoint(self):
return self.func(*[(e.adjoint(), c) for e, c in self.args])
def _eval_conjugate(self):
return self.func(*[(e.conjugate(), c) for e, c in self.args])
def _eval_derivative(self, x):
return self.func(*[(diff(e, x), c) for e, c in self.args])
def _eval_evalf(self, prec):
return self.func(*[(e._evalf(prec), c) for e, c in self.args])
def piecewise_integrate(self, x, **kwargs):
"""Return the Piecewise with each expression being
replaced with its antiderivative. To obtain a continuous
antiderivative, use the `integrate` function or method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
Note that this does not give a continuous function, e.g.
at x = 1 the 3rd condition applies and the antiderivative
there is 2*x so the value of the antiderivative is 2:
>>> anti = _
>>> anti.subs(x, 1)
2
The continuous derivative accounts for the integral *up to*
the point of interest, however:
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> _.subs(x, 1)
1
See Also
========
Piecewise._eval_integral
"""
from sympy.integrals import integrate
return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
def _handle_irel(self, x, handler):
"""Return either None (if the conditions of self depend only on x) else
a Piecewise expression whose expressions (handled by the handler that
was passed) are paired with the governing x-independent relationals,
e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
Piecewise(
(handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
(handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
"""
# identify governing relationals
rel = self.atoms(Relational)
irel = list(ordered([r for r in rel if x not in r.free_symbols
and r not in (S.true, S.false)]))
if irel:
args = {}
exprinorder = []
for truth in product((1, 0), repeat=len(irel)):
reps = dict(zip(irel, truth))
# only store the true conditions since the false are implied
# when they appear lower in the Piecewise args
if 1 not in truth:
cond = None # flag this one so it doesn't get combined
else:
andargs = Tuple(*[i for i in reps if reps[i]])
free = list(andargs.free_symbols)
if len(free) == 1:
from sympy.solvers.inequalities import (
reduce_inequalities, _solve_inequality)
try:
t = reduce_inequalities(andargs, free[0])
# ValueError when there are potentially
# nonvanishing imaginary parts
except (ValueError, NotImplementedError):
# at least isolate free symbol on left
t = And(*[_solve_inequality(
a, free[0], linear=True)
for a in andargs])
else:
t = And(*andargs)
if t is S.false:
continue # an impossible combination
cond = t
expr = handler(self.xreplace(reps))
if isinstance(expr, self.func) and len(expr.args) == 1:
expr, econd = expr.args[0]
cond = And(econd, True if cond is None else cond)
# the ec pairs are being collected since all possibilities
# are being enumerated, but don't put the last one in since
# its expr might match a previous expression and it
# must appear last in the args
if cond is not None:
args.setdefault(expr, []).append(cond)
# but since we only store the true conditions we must maintain
# the order so that the expression with the most true values
# comes first
exprinorder.append(expr)
# convert collected conditions as args of Or
for k in args:
args[k] = Or(*args[k])
# take them in the order obtained
args = [(e, args[e]) for e in uniq(exprinorder)]
# add in the last arg
args.append((expr, True))
return Piecewise(*args)
def _eval_integral(self, x, _first=True, **kwargs):
"""Return the indefinite integral of the
Piecewise such that subsequent substitution of x with a
value will give the value of the integral (not including
the constant of integration) up to that point. To only
integrate the individual parts of Piecewise, use the
`piecewise_integrate` method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
See Also
========
Piecewise.piecewise_integrate
"""
from sympy.integrals.integrals import integrate
if _first:
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_integral(x, _first=False, **kwargs)
else:
return ipw.integrate(x, **kwargs)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
# handle a Piecewise from -oo to oo with and no x-independent relationals
# -----------------------------------------------------------------------
try:
abei = self._intervals(x)
except NotImplementedError:
from sympy import Integral
return Integral(self, x) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
oo = S.Infinity
done = [(-oo, oo, -1)]
for k, p in enumerate(pieces):
if p == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# append an arg if there is a hole so a reference to
# argument -1 will give Undefined
if any(i == -1 for (a, b, i) in done):
abei.append((-oo, oo, Undefined, -1))
# return the sum of the intervals
args = []
sum = None
for a, b, i in done:
anti = integrate(abei[i][-2], x, **kwargs)
if sum is None:
sum = anti
else:
sum = sum.subs(x, a)
if sum == Undefined:
sum = 0
sum += anti._eval_interval(x, a, x)
# see if we know whether b is contained in original
# condition
if b is S.Infinity:
cond = True
elif self.args[abei[i][-1]].cond.subs(x, b) == False:
cond = (x < b)
else:
cond = (x <= b)
args.append((sum, cond))
return Piecewise(*args)
def _eval_interval(self, sym, a, b, _first=True):
"""Evaluates the function along the sym in a given interval [a, b]"""
# FIXME: Currently complex intervals are not supported. A possible
# replacement algorithm, discussed in issue 5227, can be found in the
# following papers;
# http://portal.acm.org/citation.cfm?id=281649
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
from sympy.core.symbol import Dummy
if a is None or b is None:
# In this case, it is just simple substitution
return super()._eval_interval(sym, a, b)
else:
x, lo, hi = map(as_Basic, (sym, a, b))
if _first: # get only x-dependent relationals
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_interval(x, lo, hi, _first=None)
else:
return ipw._eval_interval(x, lo, hi)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
if (lo < hi) is S.false or (
lo is S.Infinity or hi is S.NegativeInfinity):
rv = self._eval_interval(x, hi, lo, _first=False)
if isinstance(rv, Piecewise):
rv = Piecewise(*[(-e, c) for e, c in rv.args])
else:
rv = -rv
return rv
if (lo < hi) is S.true or (
hi is S.Infinity or lo is S.NegativeInfinity):
pass
else:
_a = Dummy('lo')
_b = Dummy('hi')
a = lo if lo.is_comparable else _a
b = hi if hi.is_comparable else _b
pos = self._eval_interval(x, a, b, _first=False)
if a == _a and b == _b:
# it's purely symbolic so just swap lo and hi and
# change the sign to get the value for when lo > hi
neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
pos.xreplace({_a: lo, _b: hi}))
else:
# at least one of the bounds was comparable, so allow
# _eval_interval to use that information when computing
# the interval with lo and hi reversed
neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
pos.xreplace({_a: lo, _b: hi}))
# allow simplification based on ordering of lo and hi
p = Dummy('', positive=True)
if lo.is_Symbol:
pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
elif hi.is_Symbol:
pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
# assemble return expression; make the first condition be Lt
# b/c then the first expression will look the same whether
# the lo or hi limit is symbolic
if a == _a: # the lower limit was symbolic
rv = Piecewise(
(pos,
lo < hi),
(neg,
True))
else:
rv = Piecewise(
(neg,
hi < lo),
(pos,
True))
if rv == Undefined:
raise ValueError("Can't integrate across undefined region.")
if any(isinstance(i, Piecewise) for i in (pos, neg)):
rv = piecewise_fold(rv)
return rv
# handle a Piecewise with lo <= hi and no x-independent relationals
# -----------------------------------------------------------------
try:
abei = self._intervals(x)
except NotImplementedError:
from sympy import Integral
# not being able to do the interval of f(x) can
# be stated as not being able to do the integral
# of f'(x) over the same range
return Integral(self.diff(x), (x, lo, hi)) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
done = [(lo, hi, -1)]
oo = S.Infinity
for k, p in enumerate(pieces):
if p[:2] == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# return the sum of the intervals
sum = S.Zero
upto = None
for a, b, i in done:
if i == -1:
if upto is None:
return Undefined
# TODO simplify hi <= upto
return Piecewise((sum, hi <= upto), (Undefined, True))
sum += abei[i][-2]._eval_interval(x, a, b)
upto = b
return sum
def _intervals(self, sym):
"""Return a list of unique tuples, (a, b, e, i), where a and b
are the lower and upper bounds in which the expression e of
argument i in self is defined and a < b (when involving
numbers) or a <= b when involving symbols.
If there are any relationals not involving sym, or any
relational cannot be solved for sym, NotImplementedError is
raised. The calling routine should have removed such
relationals before calling this routine.
The evaluated conditions will be returned as ranges.
Discontinuous ranges will be returned separately with
identical expressions. The first condition that evaluates to
True will be returned as the last tuple with a, b = -oo, oo.
"""
from sympy.solvers.inequalities import _solve_inequality
from sympy.logic.boolalg import to_cnf, distribute_or_over_and
assert isinstance(self, Piecewise)
def _solve_relational(r):
if sym not in r.free_symbols:
nonsymfail(r)
rv = _solve_inequality(r, sym)
if isinstance(rv, Relational):
free = rv.args[1].free_symbols
if rv.args[0] != sym or sym in free:
raise NotImplementedError(filldedent('''
Unable to solve relational
%s for %s.''' % (r, sym)))
if rv.rel_op == '==':
# this equality has been affirmed to have the form
# Eq(sym, rhs) where rhs is sym-free; it represents
# a zero-width interval which will be ignored
# whether it is an isolated condition or contained
# within an And or an Or
rv = S.false
elif rv.rel_op == '!=':
try:
rv = Or(sym < rv.rhs, sym > rv.rhs)
except TypeError:
# e.g. x != I ==> all real x satisfy
rv = S.true
elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
rv = S.true
return rv
def nonsymfail(cond):
raise NotImplementedError(filldedent('''
A condition not involving
%s appeared: %s''' % (sym, cond)))
# make self canonical wrt Relationals
reps = {
r: _solve_relational(r) for r in self.atoms(Relational)}
# process args individually so if any evaluate, their position
# in the original Piecewise will be known
args = [i.xreplace(reps) for i in self.args]
# precondition args
expr_cond = []
default = idefault = None
for i, (expr, cond) in enumerate(args):
if cond is S.false:
continue
elif cond is S.true:
default = expr
idefault = i
break
cond = to_cnf(cond)
if isinstance(cond, And):
cond = distribute_or_over_and(cond)
if isinstance(cond, Or):
expr_cond.extend(
[(i, expr, o) for o in cond.args
if not isinstance(o, Equality)])
elif cond is not S.false:
expr_cond.append((i, expr, cond))
# determine intervals represented by conditions
int_expr = []
for iarg, expr, cond in expr_cond:
if isinstance(cond, And):
lower = S.NegativeInfinity
upper = S.Infinity
for cond2 in cond.args:
if isinstance(cond2, Equality):
lower = upper # ignore
break
elif cond2.lts == sym:
upper = Min(cond2.gts, upper)
elif cond2.gts == sym:
lower = Max(cond2.lts, lower)
else:
nonsymfail(cond2) # should never get here
elif isinstance(cond, Relational):
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
if cond.lts == sym: # part 1a: expand the side ...
lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
elif cond.gts == sym: # part 1a: ... that can be expanded
upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
else:
nonsymfail(cond)
else:
raise NotImplementedError(
'unrecognized condition: %s' % cond)
lower, upper = lower, Max(lower, upper)
if (lower >= upper) is not S.true:
int_expr.append((lower, upper, expr, iarg))
if default is not None:
int_expr.append(
(S.NegativeInfinity, S.Infinity, default, idefault))
return list(uniq(int_expr))
def _eval_nseries(self, x, n, logx, cdir=0):
args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
return self.func(*args)
def _eval_power(self, s):
return self.func(*[(e**s, c) for e, c in self.args])
def _eval_subs(self, old, new):
# this is strictly not necessary, but we can keep track
# of whether True or False conditions arise and be
# somewhat more efficient by avoiding other substitutions
# and avoiding invalid conditions that appear after a
# True condition
args = list(self.args)
args_exist = False
for i, (e, c) in enumerate(args):
c = c._subs(old, new)
if c != False:
args_exist = True
e = e._subs(old, new)
args[i] = (e, c)
if c == True:
break
if not args_exist:
args = ((Undefined, True),)
return self.func(*args)
def _eval_transpose(self):
return self.func(*[(e.transpose(), c) for e, c in self.args])
def _eval_template_is_attr(self, is_attr):
b = None
for expr, _ in self.args:
a = getattr(expr, is_attr)
if a is None:
return
if b is None:
b = a
elif b is not a:
return
return b
_eval_is_finite = lambda self: self._eval_template_is_attr(
'is_finite')
_eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
_eval_is_even = lambda self: self._eval_template_is_attr('is_even')
_eval_is_imaginary = lambda self: self._eval_template_is_attr(
'is_imaginary')
_eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
_eval_is_irrational = lambda self: self._eval_template_is_attr(
'is_irrational')
_eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
_eval_is_nonnegative = lambda self: self._eval_template_is_attr(
'is_nonnegative')
_eval_is_nonpositive = lambda self: self._eval_template_is_attr(
'is_nonpositive')
_eval_is_nonzero = lambda self: self._eval_template_is_attr(
'is_nonzero')
_eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
_eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
_eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
_eval_is_extended_real = lambda self: self._eval_template_is_attr(
'is_extended_real')
_eval_is_extended_positive = lambda self: self._eval_template_is_attr(
'is_extended_positive')
_eval_is_extended_negative = lambda self: self._eval_template_is_attr(
'is_extended_negative')
_eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
'is_extended_nonzero')
_eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
'is_extended_nonpositive')
_eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
'is_extended_nonnegative')
_eval_is_real = lambda self: self._eval_template_is_attr('is_real')
_eval_is_zero = lambda self: self._eval_template_is_attr(
'is_zero')
@classmethod
def __eval_cond(cls, cond):
"""Return the truth value of the condition."""
if cond == True:
return True
if isinstance(cond, Equality):
try:
diff = cond.lhs - cond.rhs
if diff.is_commutative:
return diff.is_zero
except TypeError:
pass
def as_expr_set_pairs(self, domain=S.Reals):
"""Return tuples for each argument of self that give
the expression and the interval in which it is valid
which is contained within the given domain.
If a condition cannot be converted to a set, an error
will be raised. The variable of the conditions is
assumed to be real; sets of real values are returned.
Examples
========
>>> from sympy import Piecewise, Interval
>>> from sympy.abc import x
>>> p = Piecewise(
... (1, x < 2),
... (2,(x > 0) & (x < 4)),
... (3, True))
>>> p.as_expr_set_pairs()
[(1, Interval.open(-oo, 2)),
(2, Interval.Ropen(2, 4)),
(3, Interval(4, oo))]
>>> p.as_expr_set_pairs(Interval(0, 3))
[(1, Interval.Ropen(0, 2)),
(2, Interval(2, 3)), (3, EmptySet)]
"""
exp_sets = []
U = domain
complex = not domain.is_subset(S.Reals)
cond_free = set()
for expr, cond in self.args:
cond_free |= cond.free_symbols
if len(cond_free) > 1:
raise NotImplementedError(filldedent('''
multivariate conditions are not handled.'''))
if complex:
for i in cond.atoms(Relational):
if not isinstance(i, (Equality, Unequality)):
raise ValueError(filldedent('''
Inequalities in the complex domain are
not supported. Try the real domain by
setting domain=S.Reals'''))
cond_int = U.intersect(cond.as_set())
U = U - cond_int
exp_sets.append((expr, cond_int))
return exp_sets
def _eval_rewrite_as_ITE(self, *args, **kwargs):
byfree = {}
args = list(args)
default = any(c == True for b, c in args)
for i, (b, c) in enumerate(args):
if not isinstance(b, Boolean) and b != True:
raise TypeError(filldedent('''
Expecting Boolean or bool but got `%s`
''' % func_name(b)))
if c == True:
break
# loop over independent conditions for this b
for c in c.args if isinstance(c, Or) else [c]:
free = c.free_symbols
x = free.pop()
try:
byfree[x] = byfree.setdefault(
x, S.EmptySet).union(c.as_set())
except NotImplementedError:
if not default:
raise NotImplementedError(filldedent('''
A method to determine whether a multivariate
conditional is consistent with a complete coverage
of all variables has not been implemented so the
rewrite is being stopped after encountering `%s`.
This error would not occur if a default expression
like `(foo, True)` were given.
''' % c))
if byfree[x] in (S.UniversalSet, S.Reals):
# collapse the ith condition to True and break
args[i] = list(args[i])
c = args[i][1] = True
break
if c == True:
break
if c != True:
raise ValueError(filldedent('''
Conditions must cover all reals or a final default
condition `(foo, True)` must be given.
'''))
last, _ = args[i] # ignore all past ith arg
for a, c in reversed(args[:i]):
last = ITE(c, a, last)
return _canonical(last)
def _eval_rewrite_as_KroneckerDelta(self, *args):
from sympy import Ne, Eq, Not, KroneckerDelta
rules = {
And: [False, False],
Or: [True, True],
Not: [True, False],
Eq: [None, None],
Ne: [None, None]
}
class UnrecognizedCondition(Exception):
pass
def rewrite(cond):
if isinstance(cond, Eq):
return KroneckerDelta(*cond.args)
if isinstance(cond, Ne):
return 1 - KroneckerDelta(*cond.args)
cls, args = type(cond), cond.args
if cls not in rules:
raise UnrecognizedCondition(cls)
b1, b2 = rules[cls]
k = 1
for c in args:
if b1:
k *= 1 - rewrite(c)
else:
k *= rewrite(c)
if b2:
return 1 - k
return k
conditions = []
true_value = None
for value, cond in args:
if type(cond) in rules:
conditions.append((value, cond))
elif cond is S.true:
if true_value is None:
true_value = value
else:
return
if true_value is not None:
result = true_value
for value, cond in conditions[::-1]:
try:
k = rewrite(cond)
result = k * value + (1 - k) * result
except UnrecognizedCondition:
return
return result
def piecewise_fold(expr):
"""
Takes an expression containing a piecewise function and returns the
expression in piecewise form. In addition, any ITE conditions are
rewritten in negation normal form and simplified.
Examples
========
>>> from sympy import Piecewise, piecewise_fold, sympify as S
>>> from sympy.abc import x
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, True))
See Also
========
Piecewise
"""
if not isinstance(expr, Basic) or not expr.has(Piecewise):
return expr
new_args = []
if isinstance(expr, (ExprCondPair, Piecewise)):
for e, c in expr.args:
if not isinstance(e, Piecewise):
e = piecewise_fold(e)
# we don't keep Piecewise in condition because
# it has to be checked to see that it's complete
# and we convert it to ITE at that time
assert not c.has(Piecewise) # pragma: no cover
if isinstance(c, ITE):
c = c.to_nnf()
c = simplify_logic(c, form='cnf')
if isinstance(e, Piecewise):
new_args.extend([(piecewise_fold(ei), And(ci, c))
for ei, ci in e.args])
else:
new_args.append((e, c))
else:
from sympy.utilities.iterables import cartes, sift, common_prefix
# Given
# P1 = Piecewise((e11, c1), (e12, c2), A)
# P2 = Piecewise((e21, c1), (e22, c2), B)
# ...
# the folding of f(P1, P2) is trivially
# Piecewise(
# (f(e11, e21), c1),
# (f(e12, e22), c2),
# (f(Piecewise(A), Piecewise(B)), True))
# Certain objects end up rewriting themselves as thus, so
# we do that grouping before the more generic folding.
# The following applies this idea when f = Add or f = Mul
# (and the expression is commutative).
if expr.is_Add or expr.is_Mul and expr.is_commutative:
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
for c in list(ordered(pc)):
if len(pc[c]) > 1:
pargs = [list(i.args) for i in pc[c]]
# the first one is the same; there may be more
com = common_prefix(*[
[i.cond for i in j] for j in pargs])
n = len(com)
collected = []
for i in range(n):
collected.append((
expr.func(*[ai[i].expr for ai in pargs]),
com[i]))
remains = []
for a in pargs:
if n == len(a): # no more args
continue
if a[n].cond == True: # no longer Piecewise
remains.append(a[n].expr)
else: # restore the remaining Piecewise
remains.append(
Piecewise(*a[n:], evaluate=False))
if remains:
collected.append((expr.func(*remains), True))
args.append(Piecewise(*collected, evaluate=False))
continue
args.extend(pc[c])
else:
args = expr.args
# fold
folded = list(map(piecewise_fold, args))
for ec in cartes(*[
(i.args if isinstance(i, Piecewise) else
[(i, true)]) for i in folded]):
e, c = zip(*ec)
new_args.append((expr.func(*e), And(*c)))
return Piecewise(*new_args)
def _clip(A, B, k):
"""Return interval B as intervals that are covered by A (keyed
to k) and all other intervals of B not covered by A keyed to -1.
The reference point of each interval is the rhs; if the lhs is
greater than the rhs then an interval of zero width interval will
result, e.g. (4, 1) is treated like (1, 1).
Examples
========
>>> from sympy.functions.elementary.piecewise import _clip
>>> from sympy import Tuple
>>> A = Tuple(1, 3)
>>> B = Tuple(2, 4)
>>> _clip(A, B, 0)
[(2, 3, 0), (3, 4, -1)]
Interpretation: interval portion (2, 3) of interval (2, 4) is
covered by interval (1, 3) and is keyed to 0 as requested;
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
"""
a, b = B
c, d = A
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
a, b = Min(a, b), b
p = []
if a != c:
p.append((a, c, -1))
else:
pass
if c != d:
p.append((c, d, k))
else:
pass
if b != d:
if d == c and p and p[-1][-1] == -1:
p[-1] = p[-1][0], b, -1
else:
p.append((d, b, -1))
else:
pass
return p
def piecewise_simplify_arguments(expr, **kwargs):
from sympy import simplify
args = []
for e, c in expr.args:
if isinstance(e, Basic):
doit = kwargs.pop('doit', None)
# Skip doit to avoid growth at every call for some integrals
# and sums, see sympy/sympy#17165
newe = simplify(e, doit=False, **kwargs)
if newe != expr:
e = newe
if isinstance(c, Basic):
c = simplify(c, doit=doit, **kwargs)
args.append((e, c))
return Piecewise(*args)
def piecewise_simplify(expr, **kwargs):
expr = piecewise_simplify_arguments(expr, **kwargs)
if not isinstance(expr, Piecewise):
return expr
args = list(expr.args)
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
getattr(e.rhs, '_diff_wrt', None) or
isinstance(e.rhs, (Rational, NumberSymbol)))
for i, (expr, cond) in enumerate(args):
# try to simplify conditions and the expression for
# equalities that are part of the condition, e.g.
# Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
# -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Equality), binary=True)
elif isinstance(cond, Equality):
eqs, other = [cond], []
else:
eqs = other = []
if eqs:
eqs = list(ordered(eqs))
for j, e in enumerate(eqs):
# these blessed lhs objects behave like Symbols
# and the rhs are simple replacements for the "symbols"
if _blessed(e):
expr = expr.subs(*e.args)
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
other = [ei.subs(*e.args) for ei in other]
cond = And(*(eqs + other))
args[i] = args[i].func(expr, cond)
# See if expressions valid for an Equal expression happens to evaluate
# to the same function as in the next piecewise segment, see:
# https://github.com/sympy/sympy/issues/8458
prevexpr = None
for i, (expr, cond) in reversed(list(enumerate(args))):
if prevexpr is not None:
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Equality), binary=True)
elif isinstance(cond, Equality):
eqs, other = [cond], []
else:
eqs = other = []
_prevexpr = prevexpr
_expr = expr
if eqs and not other:
eqs = list(ordered(eqs))
for e in eqs:
# allow 2 args to collapse into 1 for any e
# otherwise limit simplification to only simple-arg
# Eq instances
if len(args) == 2 or _blessed(e):
_prevexpr = _prevexpr.subs(*e.args)
_expr = _expr.subs(*e.args)
# Did it evaluate to the same?
if _prevexpr == _expr:
# Set the expression for the Not equal section to the same
# as the next. These will be merged when creating the new
# Piecewise
args[i] = args[i].func(args[i+1][0], cond)
else:
# Update the expression that we compare against
prevexpr = expr
else:
prevexpr = expr
return Piecewise(*args)
|
96b3e74c063309ca30d16a95adb410e3e3fdb02bb8cc8a92ec2f704b174d358e | from sympy.core import sympify
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.function import (Function, ArgumentIndexError, _coeff_isneg,
expand_mul)
from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
from sympy.core.mul import Mul
from sympy.core.numbers import Integer, Rational
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Wild, Dummy
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.ntheory import multiplicity, perfect_power
# NOTE IMPORTANT
# The series expansion code in this file is an important part of the gruntz
# algorithm for determining limits. _eval_nseries has to return a generalized
# power series with coefficients in C(log(x), log).
# In more detail, the result of _eval_nseries(self, x, n) must be
# c_0*x**e_0 + ... (finitely many terms)
# where e_i are numbers (not necessarily integers) and c_i involve only
# numbers, the function log, and log(x). [This also means it must not contain
# log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
# p.is_positive.]
class ExpBase(Function):
unbranched = True
_singularities = (S.ComplexInfinity,)
def inverse(self, argindex=1):
"""
Returns the inverse function of ``exp(x)``.
"""
return log
def as_numer_denom(self):
"""
Returns this with a positive exponent as a 2-tuple (a fraction).
Examples
========
>>> from sympy.functions import exp
>>> from sympy.abc import x
>>> exp(-x).as_numer_denom()
(1, exp(x))
>>> exp(x).as_numer_denom()
(exp(x), 1)
"""
# this should be the same as Pow.as_numer_denom wrt
# exponent handling
exp = self.exp
neg_exp = exp.is_negative
if not neg_exp and not (-exp).is_negative:
neg_exp = _coeff_isneg(exp)
if neg_exp:
return S.One, self.func(-exp)
return self, S.One
@property
def exp(self):
"""
Returns the exponent of the function.
"""
return self.args[0]
def as_base_exp(self):
"""
Returns the 2-tuple (base, exponent).
"""
return self.func(1), Mul(*self.args)
def _eval_adjoint(self):
return self.func(self.args[0].adjoint())
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_transpose(self):
return self.func(self.args[0].transpose())
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_infinite:
if arg.is_extended_negative:
return True
if arg.is_extended_positive:
return False
if arg.is_finite:
return True
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
z = s.exp.is_zero
if z:
return True
elif s.exp.is_rational and fuzzy_not(z):
return False
else:
return s.is_rational
def _eval_is_zero(self):
return (self.args[0] is S.NegativeInfinity)
def _eval_power(self, other):
"""exp(arg)**e -> exp(arg*e) if assumptions allow it.
"""
b, e = self.as_base_exp()
return Pow._eval_power(Pow(b, e, evaluate=False), other)
def _eval_expand_power_exp(self, **hints):
from sympy import Sum, Product
arg = self.args[0]
if arg.is_Add and arg.is_commutative:
return Mul.fromiter(self.func(x) for x in arg.args)
elif isinstance(arg, Sum) and arg.is_commutative:
return Product(self.func(arg.function), *arg.limits)
return self.func(arg)
class exp_polar(ExpBase):
r"""
Represent a 'polar number' (see g-function Sphinx documentation).
Explanation
===========
``exp_polar`` represents the function
`Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
`z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
the main functions to construct polar numbers.
Examples
========
>>> from sympy import exp_polar, pi, I, exp
The main difference is that polar numbers don't "wrap around" at `2 \pi`:
>>> exp(2*pi*I)
1
>>> exp_polar(2*pi*I)
exp_polar(2*I*pi)
apart from that they behave mostly like classical complex numbers:
>>> exp_polar(2)*exp_polar(3)
exp_polar(5)
See Also
========
sympy.simplify.powsimp.powsimp
polar_lift
periodic_argument
principal_branch
"""
is_polar = True
is_comparable = False # cannot be evalf'd
def _eval_Abs(self): # Abs is never a polar number
from sympy.functions.elementary.complexes import re
return exp(re(self.args[0]))
def _eval_evalf(self, prec):
""" Careful! any evalf of polar numbers is flaky """
from sympy import im, pi, re
i = im(self.args[0])
try:
bad = (i <= -pi or i > pi)
except TypeError:
bad = True
if bad:
return self # cannot evalf for this argument
res = exp(self.args[0])._eval_evalf(prec)
if i > 0 and im(res) < 0:
# i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
return re(res)
return res
def _eval_power(self, other):
return self.func(self.args[0]*other)
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def as_base_exp(self):
# XXX exp_polar(0) is special!
if self.args[0] == 0:
return self, S.One
return ExpBase.as_base_exp(self)
class exp(ExpBase):
"""
The exponential function, :math:`e^x`.
Examples
========
>>> from sympy.functions import exp
>>> from sympy.abc import x
>>> from sympy import I, pi
>>> exp(x)
exp(x)
>>> exp(x).diff(x)
exp(x)
>>> exp(I*pi)
-1
Parameters
==========
arg : Expr
See Also
========
log
"""
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return self
else:
raise ArgumentIndexError(self, argindex)
def _eval_refine(self, assumptions):
from sympy.assumptions import ask, Q
arg = self.args[0]
if arg.is_Mul:
Ioo = S.ImaginaryUnit*S.Infinity
if arg in [Ioo, -Ioo]:
return S.NaN
coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
if coeff:
if ask(Q.integer(2*coeff)):
if ask(Q.even(coeff)):
return S.One
elif ask(Q.odd(coeff)):
return S.NegativeOne
elif ask(Q.even(coeff + S.Half)):
return -S.ImaginaryUnit
elif ask(Q.odd(coeff + S.Half)):
return S.ImaginaryUnit
@classmethod
def eval(cls, arg):
from sympy.calculus import AccumBounds
from sympy.sets.setexpr import SetExpr
from sympy.matrices.matrices import MatrixBase
from sympy import im, logcombine, re
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.One
elif arg is S.One:
return S.Exp1
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Zero
elif arg is S.ComplexInfinity:
return S.NaN
elif isinstance(arg, log):
return arg.args[0]
elif isinstance(arg, AccumBounds):
return AccumBounds(exp(arg.min), exp(arg.max))
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
elif arg.is_Mul:
coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
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 -S.ImaginaryUnit
elif (coeff + S.Half).is_odd:
return S.ImaginaryUnit
elif coeff.is_Rational:
ncoeff = coeff % 2 # restrict to [0, 2pi)
if ncoeff > 1: # restrict to (-pi, pi]
ncoeff -= 2
if ncoeff != coeff:
return cls(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 [S.NegativeInfinity, S.Infinity]:
if terms.is_number:
if coeff is S.NegativeInfinity:
terms = -terms
if re(terms).is_zero and terms is not S.Zero:
return S.NaN
if re(terms).is_positive and im(terms) is not S.Zero:
return S.ComplexInfinity
if re(terms).is_negative:
return S.Zero
return None
coeffs, log_term = [coeff], None
for term in Mul.make_args(terms):
term_ = logcombine(term)
if isinstance(term_, log):
if log_term is None:
log_term = term_.args[0]
else:
return None
elif term.is_comparable:
coeffs.append(term)
else:
return None
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 = cls(a)
if isinstance(newa, cls):
if newa.args[0] != a:
add.append(newa.args[0])
argchanged = True
else:
add.append(a)
else:
out.append(newa)
if out or argchanged:
return Mul(*out)*cls(Add(*add), evaluate=False)
elif isinstance(arg, MatrixBase):
return arg.exp()
if arg.is_zero:
return S.One
@property
def base(self):
"""
Returns the base of the exponential function.
"""
return S.Exp1
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Calculates the next term in the Taylor series expansion.
"""
if n < 0:
return S.Zero
if n == 0:
return S.One
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
return x**n/factorial(n)
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a 2-tuple representing a complex number.
Examples
========
>>> from sympy import I
>>> from sympy.abc import x
>>> from sympy.functions import exp
>>> exp(x).as_real_imag()
(exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
>>> exp(1).as_real_imag()
(E, 0)
>>> exp(I).as_real_imag()
(cos(1), sin(1))
>>> exp(1+I).as_real_imag()
(E*cos(1), E*sin(1))
See Also
========
sympy.functions.elementary.complexes.re
sympy.functions.elementary.complexes.im
"""
import sympy
re, im = self.args[0].as_real_imag()
if deep:
re = re.expand(deep, **hints)
im = im.expand(deep, **hints)
cos, sin = sympy.cos(im), sympy.sin(im)
return (exp(re)*cos, exp(re)*sin)
def _eval_subs(self, old, new):
# keep processing of power-like args centralized in Pow
if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
old = exp(old.exp*log(old.base))
elif old is S.Exp1 and new.is_Function:
old = exp
if isinstance(old, exp) or old is S.Exp1:
f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
a.is_Pow or isinstance(a, exp)) else a
return Pow._eval_subs(f(self), f(old), new)
if old is exp and not new.is_Function:
return new**self.exp._subs(old, new)
return Function._eval_subs(self, old, new)
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
elif self.args[0].is_imaginary:
arg2 = -S(2) * S.ImaginaryUnit * self.args[0] / S.Pi
return arg2.is_even
def _eval_is_complex(self):
def complex_extended_negative(arg):
yield arg.is_complex
yield arg.is_extended_negative
return fuzzy_or(complex_extended_negative(self.args[0]))
def _eval_is_algebraic(self):
if (self.exp / S.Pi / S.ImaginaryUnit).is_rational:
return True
if fuzzy_not(self.exp.is_zero):
if self.exp.is_algebraic:
return False
elif (self.exp / S.Pi).is_rational:
return False
def _eval_is_extended_positive(self):
if self.args[0].is_extended_real:
return not self.args[0] is S.NegativeInfinity
elif self.args[0].is_imaginary:
arg2 = -S.ImaginaryUnit * self.args[0] / S.Pi
return arg2.is_even
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
from sympy import ceiling, limit, oo, Order, powsimp, Wild, expand_complex
arg = self.args[0]
arg_series = arg._eval_nseries(x, n=n, logx=logx)
if arg_series.is_Order:
return 1 + arg_series
arg0 = limit(arg_series.removeO(), x, 0)
if arg0 in [-oo, oo]:
return self
t = Dummy("t")
nterms = n
try:
cf = Order(arg.as_leading_term(x), x).getn()
except NotImplementedError:
cf = 0
if cf and cf > 0:
nterms = ceiling(n/cf)
exp_series = exp(t)._taylor(t, nterms)
r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
if cf and cf > 1:
r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
else:
r += Order((arg_series - arg0)**n, x)
r = r.expand()
r = powsimp(r, deep=True, combine='exp')
# powsimp may introduce unexpanded (-1)**Rational; see PR #17201
simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
w = Wild('w', properties=[simplerat])
r = r.replace((-1)**w, expand_complex((-1)**w))
return r
def _taylor(self, x, n):
l = []
g = None
for i in range(n):
g = self.taylor_term(i, self.args[0], g)
g = g.nseries(x, n=n)
l.append(g.removeO())
return Add(*l)
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0]
if arg.is_Add:
return Mul(*[exp(f).as_leading_term(x) for f in arg.args])
arg_1 = arg.as_leading_term(x)
if Order(x, x).contains(arg_1):
return S.One
if Order(1, x).contains(arg_1):
return exp(arg_1)
####################################################
# The correct result here should be 'None'. #
# Indeed arg in not bounded as x tends to 0. #
# Consequently the series expansion does not admit #
# the leading term. #
# For compatibility reasons, the return value here #
# is the original function, i.e. exp(arg), #
# instead of None. #
####################################################
return exp(arg)
def _eval_rewrite_as_sin(self, arg, **kwargs):
from sympy import sin
I = S.ImaginaryUnit
return sin(I*arg + S.Pi/2) - I*sin(I*arg)
def _eval_rewrite_as_cos(self, arg, **kwargs):
from sympy import cos
I = S.ImaginaryUnit
return cos(I*arg) + I*cos(I*arg + S.Pi/2)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
from sympy import tanh
return (1 + tanh(arg/2))/(1 - tanh(arg/2))
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
from sympy.functions.elementary.trigonometric import sin, cos
if arg.is_Mul:
coeff = arg.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 _eval_rewrite_as_Pow(self, arg, **kwargs):
if arg.is_Mul:
logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
if logs:
return Pow(logs[0].args[0], arg.coeff(logs[0]))
def match_real_imag(expr):
"""
Try to match expr with a + b*I for real a and b.
``match_real_imag`` returns a tuple containing the real and imaginary
parts of expr or (None, None) if direct matching is not possible. Contrary
to ``re()``, ``im()``, ``as_real_imag()``, this helper won't force things
by returning expressions themselves containing ``re()`` or ``im()`` and it
doesn't expand its argument either.
"""
r_, i_ = expr.as_independent(S.ImaginaryUnit, as_Add=True)
if i_ == 0 and r_.is_real:
return (r_, i_)
i_ = i_.as_coefficient(S.ImaginaryUnit)
if i_ and i_.is_real and r_.is_real:
return (r_, i_)
else:
return (None, None) # simpler to check for than None
class log(Function):
r"""
The natural logarithm function `\ln(x)` or `\log(x)`.
Explanation
===========
Logarithms are taken with the natural base, `e`. To get
a logarithm of a different base ``b``, use ``log(x, b)``,
which is essentially short-hand for ``log(x)/log(b)``.
``log`` represents the principal branch of the natural
logarithm. As such it has a branch cut along the negative
real axis and returns values having a complex argument in
`(-\pi, \pi]`.
Examples
========
>>> from sympy import log, sqrt, S, I
>>> log(8, 2)
3
>>> log(S(8)/3, 2)
-log(3)/log(2) + 3
>>> log(-1 + I*sqrt(3))
log(2) + 2*I*pi/3
See Also
========
exp
"""
_singularities = (S.Zero, S.ComplexInfinity)
def fdiff(self, argindex=1):
"""
Returns the first derivative of the function.
"""
if argindex == 1:
return 1/self.args[0]
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
r"""
Returns `e^x`, the inverse function of `\log(x)`.
"""
return exp
@classmethod
def eval(cls, arg, base=None):
from sympy import unpolarify
from sympy.calculus import AccumBounds
from sympy.sets.setexpr import SetExpr
from sympy.functions.elementary.complexes import Abs
arg = sympify(arg)
if base is not None:
base = sympify(base)
if base == 1:
if arg == 1:
return S.NaN
else:
return S.ComplexInfinity
try:
# handle extraction of powers of the base now
# or else expand_log in Mul would have to handle this
n = multiplicity(base, arg)
if n:
return n + log(arg / base**n) / log(base)
else:
return log(arg)/log(base)
except ValueError:
pass
if base is not S.Exp1:
return cls(arg)/cls(base)
else:
return cls(arg)
if arg.is_Number:
if arg.is_zero:
return S.ComplexInfinity
elif arg is S.One:
return S.Zero
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg is S.NaN:
return S.NaN
elif arg.is_Rational and arg.p == 1:
return -cls(arg.q)
I = S.ImaginaryUnit
if isinstance(arg, exp) and arg.args[0].is_extended_real:
return arg.args[0]
elif isinstance(arg, exp) and arg.args[0].is_number:
r_, i_ = match_real_imag(arg.args[0])
if i_ and i_.is_comparable:
i_ %= 2*S.Pi
if i_ > S.Pi:
i_ -= 2*S.Pi
return r_ + expand_mul(i_ * I, deep=False)
elif isinstance(arg, exp_polar):
return unpolarify(arg.exp)
elif isinstance(arg, AccumBounds):
if arg.min.is_positive:
return AccumBounds(log(arg.min), log(arg.max))
else:
return
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.is_number:
if arg.is_negative:
return S.Pi * I + cls(-arg)
elif arg is S.ComplexInfinity:
return S.ComplexInfinity
elif arg is S.Exp1:
return S.One
if arg.is_zero:
return S.ComplexInfinity
# don't autoexpand Pow or Mul (see the issue 3351):
if not arg.is_Add:
coeff = arg.as_coefficient(I)
if coeff is not None:
if coeff is S.Infinity:
return S.Infinity
elif coeff is S.NegativeInfinity:
return S.Infinity
elif coeff.is_Rational:
if coeff.is_nonnegative:
return S.Pi * I * S.Half + cls(coeff)
else:
return -S.Pi * I * S.Half + cls(-coeff)
if arg.is_number and arg.is_algebraic:
# Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
coeff, arg_ = arg.as_independent(I, as_Add=False)
if coeff.is_negative:
coeff *= -1
arg_ *= -1
arg_ = expand_mul(arg_, deep=False)
r_, i_ = arg_.as_independent(I, as_Add=True)
i_ = i_.as_coefficient(I)
if coeff.is_real and i_ and i_.is_real and r_.is_real:
if r_.is_zero:
if i_.is_positive:
return S.Pi * I * S.Half + cls(coeff * i_)
elif i_.is_negative:
return -S.Pi * I * S.Half + cls(coeff * -i_)
else:
from sympy.simplify import ratsimp
# Check for arguments involving rational multiples of pi
t = (i_/r_).cancel()
t1 = (-t).cancel()
atan_table = {
# first quadrant only
sqrt(3): S.Pi/3,
1: S.Pi/4,
sqrt(5 - 2*sqrt(5)): S.Pi/5,
sqrt(2)*sqrt(5 - sqrt(5))/(1 + sqrt(5)): S.Pi/5,
sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5),
sqrt(2)*sqrt(sqrt(5) + 5)/(-1 + sqrt(5)): S.Pi*Rational(2, 5),
sqrt(3)/3: S.Pi/6,
sqrt(2) - 1: S.Pi/8,
sqrt(2 - sqrt(2))/sqrt(sqrt(2) + 2): S.Pi/8,
sqrt(2) + 1: S.Pi*Rational(3, 8),
sqrt(sqrt(2) + 2)/sqrt(2 - sqrt(2)): S.Pi*Rational(3, 8),
sqrt(1 - 2*sqrt(5)/5): S.Pi/10,
(-sqrt(2) + sqrt(10))/(2*sqrt(sqrt(5) + 5)): S.Pi/10,
sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10),
(sqrt(2) + sqrt(10))/(2*sqrt(5 - sqrt(5))): S.Pi*Rational(3, 10),
2 - sqrt(3): S.Pi/12,
(-1 + sqrt(3))/(1 + sqrt(3)): S.Pi/12,
2 + sqrt(3): S.Pi*Rational(5, 12),
(1 + sqrt(3))/(-1 + sqrt(3)): S.Pi*Rational(5, 12)
}
if t in atan_table:
modulus = ratsimp(coeff * Abs(arg_))
if r_.is_positive:
return cls(modulus) + I * atan_table[t]
else:
return cls(modulus) + I * (atan_table[t] - S.Pi)
elif t1 in atan_table:
modulus = ratsimp(coeff * Abs(arg_))
if r_.is_positive:
return cls(modulus) + I * (-atan_table[t1])
else:
return cls(modulus) + I * (S.Pi - atan_table[t1])
def as_base_exp(self):
"""
Returns this function in the form (base, exponent).
"""
return self, S.One
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms): # of log(1+x)
r"""
Returns the next term in the Taylor series expansion of `\log(1+x)`.
"""
from sympy import powsimp
if n < 0:
return S.Zero
x = sympify(x)
if n == 0:
return x
if previous_terms:
p = previous_terms[-1]
if p is not None:
return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
def _eval_expand_log(self, deep=True, **hints):
from sympy import unpolarify, expand_log, factorint
from sympy.concrete import Sum, Product
force = hints.get('force', False)
factor = hints.get('factor', False)
if (len(self.args) == 2):
return expand_log(self.func(*self.args), deep=deep, force=force)
arg = self.args[0]
if arg.is_Integer:
# remove perfect powers
p = perfect_power(arg)
logarg = None
coeff = 1
if p is not False:
arg, coeff = p
logarg = self.func(arg)
# expand as product of its prime factors if factor=True
if factor:
p = factorint(arg)
if arg not in p.keys():
logarg = sum(n*log(val) for val, n in p.items())
if logarg is not None:
return coeff*logarg
elif arg.is_Rational:
return log(arg.p) - log(arg.q)
elif arg.is_Mul:
expr = []
nonpos = []
for x in arg.args:
if force or x.is_positive or x.is_polar:
a = self.func(x)
if isinstance(a, log):
expr.append(self.func(x)._eval_expand_log(**hints))
else:
expr.append(a)
elif x.is_negative:
a = self.func(-x)
expr.append(a)
nonpos.append(S.NegativeOne)
else:
nonpos.append(x)
return Add(*expr) + log(Mul(*nonpos))
elif arg.is_Pow or isinstance(arg, exp):
if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
.is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
b = arg.base
e = arg.exp
a = self.func(b)
if isinstance(a, log):
return unpolarify(e) * a._eval_expand_log(**hints)
else:
return unpolarify(e) * a
elif isinstance(arg, Product):
if force or arg.function.is_positive:
return Sum(log(arg.function), *arg.limits)
return self.func(arg)
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import expand_log, simplify, inversecombine
if len(self.args) == 2: # it's unevaluated
return simplify(self.func(*self.args), **kwargs)
expr = self.func(simplify(self.args[0], **kwargs))
if kwargs['inverse']:
expr = inversecombine(expr)
expr = expand_log(expr, deep=True)
return min([expr, self], key=kwargs['measure'])
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a complex coordinate.
Examples
========
>>> from sympy import I
>>> from sympy.abc import x
>>> from sympy.functions import log
>>> log(x).as_real_imag()
(log(Abs(x)), arg(x))
>>> log(I).as_real_imag()
(0, pi/2)
>>> log(1 + I).as_real_imag()
(log(sqrt(2)), pi/4)
>>> log(I*x).as_real_imag()
(log(Abs(x)), arg(I*x))
"""
from sympy import Abs, arg
sarg = self.args[0]
if deep:
sarg = self.args[0].expand(deep, **hints)
abs = Abs(sarg)
if abs == sarg:
return self, S.Zero
arg = arg(sarg)
if hints.get('log', False): # Expand the log
hints['complex'] = False
return (log(abs).expand(deep, **hints), arg)
else:
return log(abs), arg
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if (self.args[0] - 1).is_zero:
return True
if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
return False
else:
return s.is_rational
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if (self.args[0] - 1).is_zero:
return True
elif fuzzy_not((self.args[0] - 1).is_zero):
if self.args[0].is_algebraic:
return False
else:
return s.is_algebraic
def _eval_is_extended_real(self):
return self.args[0].is_extended_positive
def _eval_is_complex(self):
z = self.args[0]
return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_zero:
return False
return arg.is_finite
def _eval_is_extended_positive(self):
return (self.args[0] - 1).is_extended_positive
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
def _eval_is_extended_nonnegative(self):
return (self.args[0] - 1).is_extended_nonnegative
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
from sympy import im, cancel, I, Order, logcombine
from itertools import product
if not logx:
logx = log(x)
if self.args[0] == x:
return logx
arg = self.args[0]
k, l = Wild("k"), Wild("l")
r = arg.match(k*x**l)
if r is not None:
k, l = r[k], r[l]
if l != 0 and not l.has(x) and not k.has(x):
r = log(k) + l*logx # XXX true regardless of assumptions?
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
# TODO new and probably slow
try:
a, b = arg.leadterm(x)
s = arg.nseries(x, n=n+b, logx=logx)
except (ValueError, NotImplementedError):
s = arg.nseries(x, n=n, logx=logx)
while s.is_Order:
n += 1
s = arg.nseries(x, n=n, logx=logx)
a, b = s.removeO().leadterm(x)
p = cancel(s/(a*x**b) - 1).expand().powsimp()
if p.has(exp):
p = logcombine(p)
if isinstance(p, Order):
n = p.getn()
_, d = coeff_exp(p, x)
if not d.is_positive:
return log(a) + b*logx + Order(x**n, x)
def mul(d1, d2):
res = {}
for e1, e2 in product(d1, d2):
ex = e1 + e2
if ex < n:
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
return res
pterms = {}
for term in Add.make_args(p):
co1, e1 = coeff_exp(term, x)
pterms[e1] = pterms.get(e1, S.Zero) + co1.removeO()
k = S.One
terms = {}
pk = pterms
while k*d < n:
coeff = -(-1)**k/k
for ex in pk:
terms[ex] = terms.get(ex, S.Zero) + coeff*pk[ex]
pk = mul(pk, pterms)
k += S.One
res = log(a) + b*logx
for ex in terms:
res += terms[ex]*x**(ex)
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if a.is_real and a.is_negative and im(cdir) < 0:
res -= 2*I*S.Pi
return res + Order(x**n, x)
def _eval_as_leading_term(self, x, cdir=0):
from sympy import I, im
arg = self.args[0].together()
x0 = arg.subs(x, 0)
if x0 == 1:
return (arg - S.One).as_leading_term(x)
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if x0.is_real and x0.is_negative and im(cdir) < 0:
return self.func(x0) -2*I*S.Pi
return self.func(arg.as_leading_term(x))
class LambertW(Function):
r"""
The Lambert W function `W(z)` is defined as the inverse
function of `w \exp(w)` [1]_.
Explanation
===========
In other words, the value of `W(z)` is such that `z = W(z) \exp(W(z))`
for any complex number `z`. The Lambert W function is a multivalued
function with infinitely many branches `W_k(z)`, indexed by
`k \in \mathbb{Z}`. Each branch gives a different solution `w`
of the equation `z = w \exp(w)`.
The Lambert W function has two partially real branches: the
principal branch (`k = 0`) is real for real `z > -1/e`, and the
`k = -1` branch is real for `-1/e < z < 0`. All branches except
`k = 0` have a logarithmic singularity at `z = 0`.
Examples
========
>>> from sympy import LambertW
>>> LambertW(1.2)
0.635564016364870
>>> LambertW(1.2, -1).n()
-1.34747534407696 - 4.41624341514535*I
>>> LambertW(-1).is_real
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Lambert_W_function
"""
_singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
@classmethod
def eval(cls, x, k=None):
if k == S.Zero:
return cls(x)
elif k is None:
k = S.Zero
if k.is_zero:
if x.is_zero:
return S.Zero
if x is S.Exp1:
return S.One
if x == -1/S.Exp1:
return S.NegativeOne
if x == -log(2)/2:
return -log(2)
if x == 2*log(2):
return log(2)
if x == -S.Pi/2:
return S.ImaginaryUnit*S.Pi/2
if x == exp(1 + S.Exp1):
return S.Exp1
if x is S.Infinity:
return S.Infinity
if x.is_zero:
return S.Zero
if fuzzy_not(k.is_zero):
if x.is_zero:
return S.NegativeInfinity
if k is S.NegativeOne:
if x == -S.Pi/2:
return -S.ImaginaryUnit*S.Pi/2
elif x == -1/S.Exp1:
return S.NegativeOne
elif x == -2*exp(-2):
return -Integer(2)
def fdiff(self, argindex=1):
"""
Return the first derivative of this function.
"""
x = self.args[0]
if len(self.args) == 1:
if argindex == 1:
return LambertW(x)/(x*(1 + LambertW(x)))
else:
k = self.args[1]
if argindex == 1:
return LambertW(x, k)/(x*(1 + LambertW(x, k)))
raise ArgumentIndexError(self, argindex)
def _eval_is_extended_real(self):
x = self.args[0]
if len(self.args) == 1:
k = S.Zero
else:
k = self.args[1]
if k.is_zero:
if (x + 1/S.Exp1).is_positive:
return True
elif (x + 1/S.Exp1).is_nonpositive:
return False
elif (k + 1).is_zero:
if x.is_negative and (x + 1/S.Exp1).is_positive:
return True
elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
return False
elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
if x.is_extended_real:
return False
def _eval_is_finite(self):
return self.args[0].is_finite
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
return False
else:
return s.is_algebraic
def _eval_nseries(self, x, n, logx, cdir=0):
if len(self.args) == 1:
from sympy import Order, ceiling, expand_multinomial
arg = self.args[0].nseries(x, n=n, logx=logx)
lt = arg.compute_leading_term(x, logx=logx)
lte = 1
if lt.is_Pow:
lte = lt.exp
if ceiling(n/lte) >= 1:
s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
s = expand_multinomial(s)
else:
s = S.Zero
return s + Order(x**n, x)
return super()._eval_nseries(x, n, logx)
def _eval_is_zero(self):
x = self.args[0]
if len(self.args) == 1:
k = S.Zero
else:
k = self.args[1]
if x.is_zero and k.is_zero:
return True
|
a6db92047b3966bec12db8822c3e97c0b8260aaab4cd0c935852425894e7ed25 | """Hypergeometric and Meijer G-functions"""
from functools import reduce
from sympy.core import S, I, pi, oo, zoo, ilcm, Mod
from sympy.core.function import Function, Derivative, ArgumentIndexError
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.symbol import Dummy
from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan,
sinh, cosh, asinh, acosh, atanh, acoth, Abs)
from sympy.utilities.iterables import default_sort_key
class TupleArg(Tuple):
def limit(self, x, xlim, dir='+'):
""" Compute limit x->xlim.
"""
from sympy.series.limits import limit
return TupleArg(*[limit(f, x, xlim, dir) for f in self.args])
# TODO should __new__ accept **options?
# TODO should constructors should check if parameters are sensible?
def _prep_tuple(v):
"""
Turn an iterable argument *v* into a tuple and unpolarify, since both
hypergeometric and meijer g-functions are unbranched in their parameters.
Examples
========
>>> from sympy.functions.special.hyper import _prep_tuple
>>> _prep_tuple([1, 2, 3])
(1, 2, 3)
>>> _prep_tuple((4, 5))
(4, 5)
>>> _prep_tuple((7, 8, 9))
(7, 8, 9)
"""
from sympy import unpolarify
return TupleArg(*[unpolarify(x) for x in v])
class TupleParametersBase(Function):
""" Base class that takes care of differentiation, when some of
the arguments are actually tuples. """
# This is not deduced automatically since there are Tuples as arguments.
is_commutative = True
def _eval_derivative(self, s):
try:
res = 0
if self.args[0].has(s) or self.args[1].has(s):
for i, p in enumerate(self._diffargs):
m = self._diffargs[i].diff(s)
if m != 0:
res += self.fdiff((1, i))*m
return res + self.fdiff(3)*self.args[2].diff(s)
except (ArgumentIndexError, NotImplementedError):
return Derivative(self, s)
class hyper(TupleParametersBase):
r"""
The generalized hypergeometric function is defined by a series where
the ratios of successive terms are a rational function of the summation
index. When convergent, it is continued analytically to the largest
possible domain.
Explanation
===========
The hypergeometric function depends on two vectors of parameters, called
the numerator parameters $a_p$, and the denominator parameters
$b_q$. It also has an argument $z$. The series definition is
.. math ::
{}_pF_q\left(\begin{matrix} a_1, \cdots, a_p \\ b_1, \cdots, b_q \end{matrix}
\middle| z \right)
= \sum_{n=0}^\infty \frac{(a_1)_n \cdots (a_p)_n}{(b_1)_n \cdots (b_q)_n}
\frac{z^n}{n!},
where $(a)_n = (a)(a+1)\cdots(a+n-1)$ denotes the rising factorial.
If one of the $b_q$ is a non-positive integer then the series is
undefined unless one of the $a_p$ is a larger (i.e., smaller in
magnitude) non-positive integer. If none of the $b_q$ is a
non-positive integer and one of the $a_p$ is a non-positive
integer, then the series reduces to a polynomial. To simplify the
following discussion, we assume that none of the $a_p$ or
$b_q$ is a non-positive integer. For more details, see the
references.
The series converges for all $z$ if $p \le q$, and thus
defines an entire single-valued function in this case. If $p =
q+1$ the series converges for $|z| < 1$, and can be continued
analytically into a half-plane. If $p > q+1$ the series is
divergent for all $z$.
Please note the hypergeometric function constructor currently does *not*
check if the parameters actually yield a well-defined function.
Examples
========
The parameters $a_p$ and $b_q$ can be passed as arbitrary
iterables, for example:
>>> from sympy.functions import hyper
>>> from sympy.abc import x, n, a
>>> hyper((1, 2, 3), [3, 4], x)
hyper((1, 2, 3), (3, 4), x)
There is also pretty printing (it looks better using Unicode):
>>> from sympy import pprint
>>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False)
_
|_ /1, 2, 3 | \
| | | x|
3 2 \ 3, 4 | /
The parameters must always be iterables, even if they are vectors of
length one or zero:
>>> hyper((1, ), [], x)
hyper((1,), (), x)
But of course they may be variables (but if they depend on $x$ then you
should not expect much implemented functionality):
>>> hyper((n, a), (n**2,), x)
hyper((n, a), (n**2,), x)
The hypergeometric function generalizes many named special functions.
The function ``hyperexpand()`` tries to express a hypergeometric function
using named special functions. For example:
>>> from sympy import hyperexpand
>>> hyperexpand(hyper([], [], x))
exp(x)
You can also use ``expand_func()``:
>>> from sympy import expand_func
>>> expand_func(x*hyper([1, 1], [2], -x))
log(x + 1)
More examples:
>>> from sympy import S
>>> hyperexpand(hyper([], [S(1)/2], -x**2/4))
cos(x)
>>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2))
asin(x)
We can also sometimes ``hyperexpand()`` parametric functions:
>>> from sympy.abc import a
>>> hyperexpand(hyper([-a], [], x))
(1 - x)**a
See Also
========
sympy.simplify.hyperexpand
gamma
meijerg
References
==========
.. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations,
Volume 1
.. [2] https://en.wikipedia.org/wiki/Generalized_hypergeometric_function
"""
def __new__(cls, ap, bq, z, **kwargs):
# TODO should we check convergence conditions?
return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z, **kwargs)
@classmethod
def eval(cls, ap, bq, z):
from sympy import unpolarify
if len(ap) <= len(bq) or (len(ap) == len(bq) + 1 and (Abs(z) <= 1) == True):
nz = unpolarify(z)
if z != nz:
return hyper(ap, bq, nz)
def fdiff(self, argindex=3):
if argindex != 3:
raise ArgumentIndexError(self, argindex)
nap = Tuple(*[a + 1 for a in self.ap])
nbq = Tuple(*[b + 1 for b in self.bq])
fac = Mul(*self.ap)/Mul(*self.bq)
return fac*hyper(nap, nbq, self.argument)
def _eval_expand_func(self, **hints):
from sympy import gamma, hyperexpand
if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1:
a, b = self.ap
c = self.bq[0]
return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b)
return hyperexpand(self)
def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs):
from sympy.functions import factorial, RisingFactorial, Piecewise
from sympy import Sum
n = Dummy("n", integer=True)
rfap = Tuple(*[RisingFactorial(a, n) for a in ap])
rfbq = Tuple(*[RisingFactorial(b, n) for b in bq])
coeff = Mul(*rfap) / Mul(*rfbq)
return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)),
self.convergence_statement), (self, True))
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.functions import factorial, RisingFactorial
from sympy import Order, Add
arg = self.args[2]
x0 = arg.limit(x, 0)
ap = self.args[0]
bq = self.args[1]
if x0 != 0:
return super()._eval_nseries(x, n, logx)
terms = []
for i in range(n):
num = 1
den = 1
for a in ap:
num *= RisingFactorial(a, i)
for b in bq:
den *= RisingFactorial(b, i)
terms.append(((num/den) * (arg**i)) / factorial(i))
return (Add(*terms) + Order(x**n,x))
@property
def argument(self):
""" Argument of the hypergeometric function. """
return self.args[2]
@property
def ap(self):
""" Numerator parameters of the hypergeometric function. """
return Tuple(*self.args[0])
@property
def bq(self):
""" Denominator parameters of the hypergeometric function. """
return Tuple(*self.args[1])
@property
def _diffargs(self):
return self.ap + self.bq
@property
def eta(self):
""" A quantity related to the convergence of the series. """
return sum(self.ap) - sum(self.bq)
@property
def radius_of_convergence(self):
"""
Compute the radius of convergence of the defining series.
Explanation
===========
Note that even if this is not ``oo``, the function may still be
evaluated outside of the radius of convergence by analytic
continuation. But if this is zero, then the function is not actually
defined anywhere else.
Examples
========
>>> from sympy.functions import hyper
>>> from sympy.abc import z
>>> hyper((1, 2), [3], z).radius_of_convergence
1
>>> hyper((1, 2, 3), [4], z).radius_of_convergence
0
>>> hyper((1, 2), (3, 4), z).radius_of_convergence
oo
"""
if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq):
aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True]
bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True]
if len(aints) < len(bints):
return S.Zero
popped = False
for b in bints:
cancelled = False
while aints:
a = aints.pop()
if a >= b:
cancelled = True
break
popped = True
if not cancelled:
return S.Zero
if aints or popped:
# There are still non-positive numerator parameters.
# This is a polynomial.
return oo
if len(self.ap) == len(self.bq) + 1:
return S.One
elif len(self.ap) <= len(self.bq):
return oo
else:
return S.Zero
@property
def convergence_statement(self):
""" Return a condition on z under which the series converges. """
from sympy import And, Or, re, Ne, oo
R = self.radius_of_convergence
if R == 0:
return False
if R == oo:
return True
# The special functions and their approximations, page 44
e = self.eta
z = self.argument
c1 = And(re(e) < 0, abs(z) <= 1)
c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1))
c3 = And(re(e) >= 1, abs(z) < 1)
return Or(c1, c2, c3)
def _eval_simplify(self, **kwargs):
from sympy.simplify.hyperexpand import hyperexpand
return hyperexpand(self)
def _sage_(self):
import sage.all as sage
ap = [arg._sage_() for arg in self.args[0]]
bq = [arg._sage_() for arg in self.args[1]]
return sage.hypergeometric(ap, bq, self.argument._sage_())
class meijerg(TupleParametersBase):
r"""
The Meijer G-function is defined by a Mellin-Barnes type integral that
resembles an inverse Mellin transform. It generalizes the hypergeometric
functions.
Explanation
===========
The Meijer G-function depends on four sets of parameters. There are
"*numerator parameters*"
$a_1, \ldots, a_n$ and $a_{n+1}, \ldots, a_p$, and there are
"*denominator parameters*"
$b_1, \ldots, b_m$ and $b_{m+1}, \ldots, b_q$.
Confusingly, it is traditionally denoted as follows (note the position
of $m$, $n$, $p$, $q$, and how they relate to the lengths of the four
parameter vectors):
.. math ::
G_{p,q}^{m,n} \left(\begin{matrix}a_1, \cdots, a_n & a_{n+1}, \cdots, a_p \\
b_1, \cdots, b_m & b_{m+1}, \cdots, b_q
\end{matrix} \middle| z \right).
However, in SymPy the four parameter vectors are always available
separately (see examples), so that there is no need to keep track of the
decorating sub- and super-scripts on the G symbol.
The G function is defined as the following integral:
.. math ::
\frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s)
\prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s)
\prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s,
where $\Gamma(z)$ is the gamma function. There are three possible
contours which we will not describe in detail here (see the references).
If the integral converges along more than one of them, the definitions
agree. The contours all separate the poles of $\Gamma(1-a_j+s)$
from the poles of $\Gamma(b_k-s)$, so in particular the G function
is undefined if $a_j - b_k \in \mathbb{Z}_{>0}$ for some
$j \le n$ and $k \le m$.
The conditions under which one of the contours yields a convergent integral
are complicated and we do not state them here, see the references.
Please note currently the Meijer G-function constructor does *not* check any
convergence conditions.
Examples
========
You can pass the parameters either as four separate vectors:
>>> from sympy.functions import meijerg
>>> from sympy.abc import x, a
>>> from sympy.core.containers import Tuple
>>> from sympy import pprint
>>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False)
__1, 2 /1, 2 a, 4 | \
/__ | | x|
\_|4, 1 \ 5 | /
Or as two nested vectors:
>>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False)
__1, 2 /1, 2 3, 4 | \
/__ | | x|
\_|4, 1 \ 5 | /
As with the hypergeometric function, the parameters may be passed as
arbitrary iterables. Vectors of length zero and one also have to be
passed as iterables. The parameters need not be constants, but if they
depend on the argument then not much implemented functionality should be
expected.
All the subvectors of parameters are available:
>>> from sympy import pprint
>>> g = meijerg([1], [2], [3], [4], x)
>>> pprint(g, use_unicode=False)
__1, 1 /1 2 | \
/__ | | x|
\_|2, 2 \3 4 | /
>>> g.an
(1,)
>>> g.ap
(1, 2)
>>> g.aother
(2,)
>>> g.bm
(3,)
>>> g.bq
(3, 4)
>>> g.bother
(4,)
The Meijer G-function generalizes the hypergeometric functions.
In some cases it can be expressed in terms of hypergeometric functions,
using Slater's theorem. For example:
>>> from sympy import hyperexpand
>>> from sympy.abc import a, b, c
>>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True)
x**c*gamma(-a + c + 1)*hyper((-a + c + 1,),
(-b + c + 1,), -x)/gamma(-b + c + 1)
Thus the Meijer G-function also subsumes many named functions as special
cases. You can use ``expand_func()`` or ``hyperexpand()`` to (try to)
rewrite a Meijer G-function in terms of named special functions. For
example:
>>> from sympy import expand_func, S
>>> expand_func(meijerg([[],[]], [[0],[]], -x))
exp(x)
>>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2))
sin(x)/sqrt(pi)
See Also
========
hyper
sympy.simplify.hyperexpand
References
==========
.. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations,
Volume 1
.. [2] https://en.wikipedia.org/wiki/Meijer_G-function
"""
def __new__(cls, *args, **kwargs):
if len(args) == 5:
args = [(args[0], args[1]), (args[2], args[3]), args[4]]
if len(args) != 3:
raise TypeError("args must be either as, as', bs, bs', z or "
"as, bs, z")
def tr(p):
if len(p) != 2:
raise TypeError("wrong argument")
return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1]))
arg0, arg1 = tr(args[0]), tr(args[1])
if Tuple(arg0, arg1).has(oo, zoo, -oo):
raise ValueError("G-function parameters must be finite")
if any((a - b).is_Integer and a - b > 0
for a in arg0[0] for b in arg1[0]):
raise ValueError("no parameter a1, ..., an may differ from "
"any b1, ..., bm by a positive integer")
# TODO should we check convergence conditions?
return Function.__new__(cls, arg0, arg1, args[2], **kwargs)
def fdiff(self, argindex=3):
if argindex != 3:
return self._diff_wrt_parameter(argindex[1])
if len(self.an) >= 1:
a = list(self.an)
a[0] -= 1
G = meijerg(a, self.aother, self.bm, self.bother, self.argument)
return 1/self.argument * ((self.an[0] - 1)*self + G)
elif len(self.bm) >= 1:
b = list(self.bm)
b[0] += 1
G = meijerg(self.an, self.aother, b, self.bother, self.argument)
return 1/self.argument * (self.bm[0]*self - G)
else:
return S.Zero
def _diff_wrt_parameter(self, idx):
# Differentiation wrt a parameter can only be done in very special
# cases. In particular, if we want to differentiate with respect to
# `a`, all other gamma factors have to reduce to rational functions.
#
# Let MT denote mellin transform. Suppose T(-s) is the gamma factor
# appearing in the definition of G. Then
#
# MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ...
#
# Thus d/da G(z) = log(z)G(z) - ...
# The ... can be evaluated as a G function under the above conditions,
# the formula being most easily derived by using
#
# d Gamma(s + n) Gamma(s + n) / 1 1 1 \
# -- ------------ = ------------ | - + ---- + ... + --------- |
# ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 /
#
# which follows from the difference equation of the digamma function.
# (There is a similar equation for -n instead of +n).
# We first figure out how to pair the parameters.
an = list(self.an)
ap = list(self.aother)
bm = list(self.bm)
bq = list(self.bother)
if idx < len(an):
an.pop(idx)
else:
idx -= len(an)
if idx < len(ap):
ap.pop(idx)
else:
idx -= len(ap)
if idx < len(bm):
bm.pop(idx)
else:
bq.pop(idx - len(bm))
pairs1 = []
pairs2 = []
for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]:
while l1:
x = l1.pop()
found = None
for i, y in enumerate(l2):
if not Mod((x - y).simplify(), 1):
found = i
break
if found is None:
raise NotImplementedError('Derivative not expressible '
'as G-function?')
y = l2[i]
l2.pop(i)
pairs.append((x, y))
# Now build the result.
res = log(self.argument)*self
for a, b in pairs1:
sign = 1
n = a - b
base = b
if n < 0:
sign = -1
n = b - a
base = a
for k in range(n):
res -= sign*meijerg(self.an + (base + k + 1,), self.aother,
self.bm, self.bother + (base + k + 0,),
self.argument)
for a, b in pairs2:
sign = 1
n = b - a
base = a
if n < 0:
sign = -1
n = a - b
base = b
for k in range(n):
res -= sign*meijerg(self.an, self.aother + (base + k + 1,),
self.bm + (base + k + 0,), self.bother,
self.argument)
return res
def get_period(self):
"""
Return a number $P$ such that $G(x*exp(I*P)) == G(x)$.
Examples
========
>>> from sympy.functions.special.hyper import meijerg
>>> from sympy.abc import z
>>> from sympy import pi, S
>>> meijerg([1], [], [], [], z).get_period()
2*pi
>>> meijerg([pi], [], [], [], z).get_period()
oo
>>> meijerg([1, 2], [], [], [], z).get_period()
oo
>>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period()
12*pi
"""
# This follows from slater's theorem.
def compute(l):
# first check that no two differ by an integer
for i, b in enumerate(l):
if not b.is_Rational:
return oo
for j in range(i + 1, len(l)):
if not Mod((b - l[j]).simplify(), 1):
return oo
return reduce(ilcm, (x.q for x in l), 1)
beta = compute(self.bm)
alpha = compute(self.an)
p, q = len(self.ap), len(self.bq)
if p == q:
if beta == oo or alpha == oo:
return oo
return 2*pi*ilcm(alpha, beta)
elif p < q:
return 2*pi*beta
else:
return 2*pi*alpha
def _eval_expand_func(self, **hints):
from sympy import hyperexpand
return hyperexpand(self)
def _eval_evalf(self, prec):
# The default code is insufficient for polar arguments.
# mpmath provides an optional argument "r", which evaluates
# G(z**(1/r)). I am not sure what its intended use is, but we hijack it
# here in the following way: to evaluate at a number z of |argument|
# less than (say) n*pi, we put r=1/n, compute z' = root(z, n)
# (carefully so as not to loose the branch information), and evaluate
# G(z'**(1/r)) = G(z'**n) = G(z).
from sympy.functions import exp_polar, ceiling
from sympy import Expr
import mpmath
znum = self.argument._eval_evalf(prec)
if znum.has(exp_polar):
znum, branch = znum.as_coeff_mul(exp_polar)
if len(branch) != 1:
return
branch = branch[0].args[0]/I
else:
branch = S.Zero
n = ceiling(abs(branch/S.Pi)) + 1
znum = znum**(S.One/n)*exp(I*branch / n)
# Convert all args to mpf or mpc
try:
[z, r, ap, bq] = [arg._to_mpmath(prec)
for arg in [znum, 1/n, self.args[0], self.args[1]]]
except ValueError:
return
with mpmath.workprec(prec):
v = mpmath.meijerg(ap, bq, z, r)
return Expr._from_mpmath(v, prec)
def integrand(self, s):
""" Get the defining integrand D(s). """
from sympy import gamma
return self.argument**s \
* Mul(*(gamma(b - s) for b in self.bm)) \
* Mul(*(gamma(1 - a + s) for a in self.an)) \
/ Mul(*(gamma(1 - b + s) for b in self.bother)) \
/ Mul(*(gamma(a - s) for a in self.aother))
@property
def argument(self):
""" Argument of the Meijer G-function. """
return self.args[2]
@property
def an(self):
""" First set of numerator parameters. """
return Tuple(*self.args[0][0])
@property
def ap(self):
""" Combined numerator parameters. """
return Tuple(*(self.args[0][0] + self.args[0][1]))
@property
def aother(self):
""" Second set of numerator parameters. """
return Tuple(*self.args[0][1])
@property
def bm(self):
""" First set of denominator parameters. """
return Tuple(*self.args[1][0])
@property
def bq(self):
""" Combined denominator parameters. """
return Tuple(*(self.args[1][0] + self.args[1][1]))
@property
def bother(self):
""" Second set of denominator parameters. """
return Tuple(*self.args[1][1])
@property
def _diffargs(self):
return self.ap + self.bq
@property
def nu(self):
""" A quantity related to the convergence region of the integral,
c.f. references. """
return sum(self.bq) - sum(self.ap)
@property
def delta(self):
""" A quantity related to the convergence region of the integral,
c.f. references. """
return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2
@property
def is_number(self):
""" Returns true if expression has numeric data only. """
return not self.free_symbols
class HyperRep(Function):
"""
A base class for "hyper representation functions".
This is used exclusively in ``hyperexpand()``, but fits more logically here.
pFq is branched at 1 if p == q+1. For use with slater-expansion, we want
define an "analytic continuation" to all polar numbers, which is
continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want
a "nice" expression for the various cases.
This base class contains the core logic, concrete derived classes only
supply the actual functions.
"""
@classmethod
def eval(cls, *args):
from sympy import unpolarify
newargs = tuple(map(unpolarify, args[:-1])) + args[-1:]
if args != newargs:
return cls(*newargs)
@classmethod
def _expr_small(cls, x):
""" An expression for F(x) which holds for |x| < 1. """
raise NotImplementedError
@classmethod
def _expr_small_minus(cls, x):
""" An expression for F(-x) which holds for |x| < 1. """
raise NotImplementedError
@classmethod
def _expr_big(cls, x, n):
""" An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """
raise NotImplementedError
@classmethod
def _expr_big_minus(cls, x, n):
""" An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """
raise NotImplementedError
def _eval_rewrite_as_nonrep(self, *args, **kwargs):
from sympy import Piecewise
x, n = self.args[-1].extract_branch_factor(allow_half=True)
minus = False
newargs = self.args[:-1] + (x,)
if not n.is_Integer:
minus = True
n -= S.Half
newerargs = newargs + (n,)
if minus:
small = self._expr_small_minus(*newargs)
big = self._expr_big_minus(*newerargs)
else:
small = self._expr_small(*newargs)
big = self._expr_big(*newerargs)
if big == small:
return small
return Piecewise((big, abs(x) > 1), (small, True))
def _eval_rewrite_as_nonrepsmall(self, *args, **kwargs):
x, n = self.args[-1].extract_branch_factor(allow_half=True)
args = self.args[:-1] + (x,)
if not n.is_Integer:
return self._expr_small_minus(*args)
return self._expr_small(*args)
class HyperRep_power1(HyperRep):
""" Return a representative for hyper([-a], [], z) == (1 - z)**a. """
@classmethod
def _expr_small(cls, a, x):
return (1 - x)**a
@classmethod
def _expr_small_minus(cls, a, x):
return (1 + x)**a
@classmethod
def _expr_big(cls, a, x, n):
if a.is_integer:
return cls._expr_small(a, x)
return (x - 1)**a*exp((2*n - 1)*pi*I*a)
@classmethod
def _expr_big_minus(cls, a, x, n):
if a.is_integer:
return cls._expr_small_minus(a, x)
return (1 + x)**a*exp(2*n*pi*I*a)
class HyperRep_power2(HyperRep):
""" Return a representative for hyper([a, a - 1/2], [2*a], z). """
@classmethod
def _expr_small(cls, a, x):
return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a)
@classmethod
def _expr_small_minus(cls, a, x):
return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a)
@classmethod
def _expr_big(cls, a, x, n):
sgn = -1
if n.is_odd:
sgn = 1
n -= 1
return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \
*exp(-2*n*pi*I*a)
@classmethod
def _expr_big_minus(cls, a, x, n):
sgn = 1
if n.is_odd:
sgn = -1
return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n)
class HyperRep_log1(HyperRep):
""" Represent -z*hyper([1, 1], [2], z) == log(1 - z). """
@classmethod
def _expr_small(cls, x):
return log(1 - x)
@classmethod
def _expr_small_minus(cls, x):
return log(1 + x)
@classmethod
def _expr_big(cls, x, n):
return log(x - 1) + (2*n - 1)*pi*I
@classmethod
def _expr_big_minus(cls, x, n):
return log(1 + x) + 2*n*pi*I
class HyperRep_atanh(HyperRep):
""" Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """
@classmethod
def _expr_small(cls, x):
return atanh(sqrt(x))/sqrt(x)
def _expr_small_minus(cls, x):
return atan(sqrt(x))/sqrt(x)
def _expr_big(cls, x, n):
if n.is_even:
return (acoth(sqrt(x)) + I*pi/2)/sqrt(x)
else:
return (acoth(sqrt(x)) - I*pi/2)/sqrt(x)
def _expr_big_minus(cls, x, n):
if n.is_even:
return atan(sqrt(x))/sqrt(x)
else:
return (atan(sqrt(x)) - pi)/sqrt(x)
class HyperRep_asin1(HyperRep):
""" Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """
@classmethod
def _expr_small(cls, z):
return asin(sqrt(z))/sqrt(z)
@classmethod
def _expr_small_minus(cls, z):
return asinh(sqrt(z))/sqrt(z)
@classmethod
def _expr_big(cls, z, n):
return S.NegativeOne**n*((S.Half - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z))
@classmethod
def _expr_big_minus(cls, z, n):
return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z))
class HyperRep_asin2(HyperRep):
""" Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """
# TODO this can be nicer
@classmethod
def _expr_small(cls, z):
return HyperRep_asin1._expr_small(z) \
/HyperRep_power1._expr_small(S.Half, z)
@classmethod
def _expr_small_minus(cls, z):
return HyperRep_asin1._expr_small_minus(z) \
/HyperRep_power1._expr_small_minus(S.Half, z)
@classmethod
def _expr_big(cls, z, n):
return HyperRep_asin1._expr_big(z, n) \
/HyperRep_power1._expr_big(S.Half, z, n)
@classmethod
def _expr_big_minus(cls, z, n):
return HyperRep_asin1._expr_big_minus(z, n) \
/HyperRep_power1._expr_big_minus(S.Half, z, n)
class HyperRep_sqrts1(HyperRep):
""" Return a representative for hyper([-a, 1/2 - a], [1/2], z). """
@classmethod
def _expr_small(cls, a, z):
return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2
@classmethod
def _expr_small_minus(cls, a, z):
return (1 + z)**a*cos(2*a*atan(sqrt(z)))
@classmethod
def _expr_big(cls, a, z, n):
if n.is_even:
return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) +
(sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2
else:
n -= 1
return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) +
(sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2
@classmethod
def _expr_big_minus(cls, a, z, n):
if n.is_even:
return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)))
else:
return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a)
class HyperRep_sqrts2(HyperRep):
""" Return a representative for
sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a]
== -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)"""
@classmethod
def _expr_small(cls, a, z):
return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2
@classmethod
def _expr_small_minus(cls, a, z):
return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z)))
@classmethod
def _expr_big(cls, a, z, n):
if n.is_even:
return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) -
(sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))
else:
n -= 1
return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) -
(sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))
def _expr_big_minus(cls, a, z, n):
if n.is_even:
return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z)))
else:
return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \
*sin(2*a*atan(sqrt(z)) - 2*pi*a)
class HyperRep_log2(HyperRep):
""" Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """
@classmethod
def _expr_small(cls, z):
return log(S.Half + sqrt(1 - z)/2)
@classmethod
def _expr_small_minus(cls, z):
return log(S.Half + sqrt(1 + z)/2)
@classmethod
def _expr_big(cls, z, n):
if n.is_even:
return (n - S.Half)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z))
else:
return (n - S.Half)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z))
def _expr_big_minus(cls, z, n):
if n.is_even:
return pi*I*n + log(S.Half + sqrt(1 + z)/2)
else:
return pi*I*n + log(sqrt(1 + z)/2 - S.Half)
class HyperRep_cosasin(HyperRep):
""" Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """
# Note there are many alternative expressions, e.g. as powers of a sum of
# square roots.
@classmethod
def _expr_small(cls, a, z):
return cos(2*a*asin(sqrt(z)))
@classmethod
def _expr_small_minus(cls, a, z):
return cosh(2*a*asinh(sqrt(z)))
@classmethod
def _expr_big(cls, a, z, n):
return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1))
@classmethod
def _expr_big_minus(cls, a, z, n):
return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n)
class HyperRep_sinasin(HyperRep):
""" Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z)
== sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """
@classmethod
def _expr_small(cls, a, z):
return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z)))
@classmethod
def _expr_small_minus(cls, a, z):
return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z)))
@classmethod
def _expr_big(cls, a, z, n):
return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1))
@classmethod
def _expr_big_minus(cls, a, z, n):
return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n)
class appellf1(Function):
r"""
This is the Appell hypergeometric function of two variables as:
.. math ::
F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty}
\frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}}
\frac{x^m y^n}{m! n!}.
Examples
========
>>> from sympy.functions.special.hyper import appellf1
>>> from sympy import symbols
>>> x, y, a, b1, b2, c = symbols('x y a b1 b2 c')
>>> appellf1(2., 1., 6., 4., 5., 6.)
0.0063339426292673
>>> appellf1(12., 12., 6., 4., 0.5, 0.12)
172870711.659936
>>> appellf1(40, 2, 6, 4, 15, 60)
appellf1(40, 2, 6, 4, 15, 60)
>>> appellf1(20., 12., 10., 3., 0.5, 0.12)
15605338197184.4
>>> appellf1(40, 2, 6, 4, x, y)
appellf1(40, 2, 6, 4, x, y)
>>> appellf1(a, b1, b2, c, x, y)
appellf1(a, b1, b2, c, x, y)
References
==========
.. [1] https://en.wikipedia.org/wiki/Appell_series
.. [2] http://functions.wolfram.com/HypergeometricFunctions/AppellF1/
"""
@classmethod
def eval(cls, a, b1, b2, c, x, y):
if default_sort_key(b1) > default_sort_key(b2):
b1, b2 = b2, b1
x, y = y, x
return cls(a, b1, b2, c, x, y)
elif b1 == b2 and default_sort_key(x) > default_sort_key(y):
x, y = y, x
return cls(a, b1, b2, c, x, y)
if x == 0 and y == 0:
return S.One
def fdiff(self, argindex=5):
a, b1, b2, c, x, y = self.args
if argindex == 5:
return (a*b1/c)*appellf1(a + 1, b1 + 1, b2, c + 1, x, y)
elif argindex == 6:
return (a*b2/c)*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)
elif argindex in (1, 2, 3, 4):
return Derivative(self, self.args[argindex-1])
else:
raise ArgumentIndexError(self, argindex)
|
4b945409f3e5f7f21471b69d09b810da890233d78d0688222af4ea96f1feeaff | from sympy import (
symbols, log, ln, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
LambertW, sqrt, Rational, expand_log, S, sign,
adjoint, conjugate, transpose, O, refine,
sin, cos, sinh, cosh, tanh, exp_polar, re, simplify,
AccumBounds, MatrixSymbol, Pow, gcd, Sum, Product)
from sympy.functions.elementary.exponential import match_real_imag
from sympy.abc import x, y, z
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import raises, XFAIL
def test_exp_values():
k = Symbol('k', integer=True)
assert exp(nan) is nan
assert exp(oo) is oo
assert exp(-oo) == 0
assert exp(0) == 1
assert exp(1) == E
assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
assert exp(pi*I/2) == I
assert exp(pi*I) == -1
assert exp(pi*I*Rational(3, 2)) == -I
assert exp(2*pi*I) == 1
assert refine(exp(pi*I*2*k)) == 1
assert refine(exp(pi*I*2*(k + S.Half))) == -1
assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
assert exp(log(x)) == x
assert exp(2*log(x)) == x**2
assert exp(pi*log(x)) == x**pi
assert exp(17*log(x) + E*log(y)) == x**17 * y**E
assert exp(x*log(x)) != x**x
assert exp(sin(x)*log(x)) != x
assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
assert exp(-oo, evaluate=False).is_finite is True
assert exp(oo, evaluate=False).is_finite is False
def test_exp_period():
assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
n = Symbol('n', integer=True)
e = Symbol('e', even=True)
assert exp(e*I*pi) == 1
assert exp((e + 1)*I*pi) == -1
assert exp((1 + 4*n)*I*pi/2) == I
assert exp((-1 + 4*n)*I*pi/2) == -I
def test_exp_log():
x = Symbol("x", real=True)
assert log(exp(x)) == x
assert exp(log(x)) == x
assert log(x).inverse() == exp
assert exp(x).inverse() == log
y = Symbol("y", polar=True)
assert log(exp_polar(z)) == z
assert exp(log(y)) == y
def test_exp_expand():
e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
assert e.expand() == 2
assert exp(x + y) != exp(x)*exp(y)
assert exp(x + y).expand() == exp(x)*exp(y)
def test_exp__as_base_exp():
assert exp(x).as_base_exp() == (E, x)
assert exp(2*x).as_base_exp() == (E, 2*x)
assert exp(x*y).as_base_exp() == (E, x*y)
assert exp(-x).as_base_exp() == (E, -x)
# Pow( *expr.as_base_exp() ) == expr invariant should hold
assert E**x == exp(x)
assert E**(2*x) == exp(2*x)
assert E**(x*y) == exp(x*y)
assert exp(x).base is S.Exp1
assert exp(x).exp == x
def test_exp_infinity():
assert exp(I*y) != nan
assert refine(exp(I*oo)) is nan
assert refine(exp(-I*oo)) is nan
assert exp(y*I*oo) != nan
assert exp(zoo) is nan
x = Symbol('x', extended_real=True, finite=False)
assert exp(x).is_complex is None
def test_exp_subs():
x = Symbol('x')
e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
assert e.subs(x**3, y**3) == e
assert e.subs(x**2, 5) == e
assert (x**3).subs(x**2, y) != y**Rational(3, 2)
assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
assert exp(x).subs(E, y) == y**x
x = symbols('x', real=True)
assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
x = symbols('x', positive=True)
assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
# differentiate between E and exp
assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
assert exp(3).subs(E, sin) == sin(3)
def test_exp_adjoint():
assert adjoint(exp(x)) == exp(adjoint(x))
def test_exp_conjugate():
assert conjugate(exp(x)) == exp(conjugate(x))
def test_exp_transpose():
assert transpose(exp(x)) == exp(transpose(x))
def test_exp_rewrite():
from sympy.concrete.summations import Sum
assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
assert exp(x*log(y)).rewrite(Pow) == y**x
assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
n = Symbol('n', integer=True)
assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*Rational(2, 5)
assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
== 4/(3 - sqrt(3)*I))
def test_exp_leading_term():
assert exp(x).as_leading_term(x) == 1
assert exp(2 + x).as_leading_term(x) == exp(2)
assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
# The following tests are commented, since now SymPy returns the
# original function when the leading term in the series expansion does
# not exist.
# raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
# raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
# raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
def test_exp_taylor_term():
x = symbols('x')
assert exp(x).taylor_term(1, x) == x
assert exp(x).taylor_term(3, x) == x**3/6
assert exp(x).taylor_term(4, x) == x**4/24
assert exp(x).taylor_term(-1, x) is S.Zero
def test_exp_MatrixSymbol():
A = MatrixSymbol("A", 2, 2)
assert exp(A).has(exp)
def test_exp_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
def test_log_values():
assert log(nan) is nan
assert log(oo) is oo
assert log(-oo) is oo
assert log(zoo) is zoo
assert log(-zoo) is zoo
assert log(0) is zoo
assert log(1) == 0
assert log(-1) == I*pi
assert log(E) == 1
assert log(-E).expand() == 1 + I*pi
assert unchanged(log, pi)
assert log(-pi).expand() == log(pi) + I*pi
assert unchanged(log, 17)
assert log(-17) == log(17) + I*pi
assert log(I) == I*pi/2
assert log(-I) == -I*pi/2
assert log(17*I) == I*pi/2 + log(17)
assert log(-17*I).expand() == -I*pi/2 + log(17)
assert log(oo*I) is oo
assert log(-oo*I) is oo
assert log(0, 2) is zoo
assert log(0, 5) is zoo
assert exp(-log(3))**(-1) == 3
assert log(S.Half) == -log(2)
assert log(2*3).func is log
assert log(2*3**2).func is log
def test_match_real_imag():
x, y = symbols('x,y', real=True)
i = Symbol('i', imaginary=True)
assert match_real_imag(S.One) == (1, 0)
assert match_real_imag(I) == (0, 1)
assert match_real_imag(3 - 5*I) == (3, -5)
assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
assert match_real_imag(x + y*I) == (x, y)
assert match_real_imag(x*I + y*I) == (0, x + y)
assert match_real_imag((x + y)*I) == (0, x + y)
assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
assert match_real_imag(1 - 2*i) == (None, None)
assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
def test_log_exact():
# check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
for n in range(-23, 24):
if gcd(n, 24) != 1:
assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
for n in range(-9, 10):
assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
# bail quickly if no obvious simplification is possible:
assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
# beware of non-real coefficients
assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
def test_log_base():
assert log(1, 2) == 0
assert log(2, 2) == 1
assert log(3, 2) == log(3)/log(2)
assert log(6, 2) == 1 + log(3)/log(2)
assert log(6, 3) == 1 + log(2)/log(3)
assert log(2**3, 2) == 3
assert log(3**3, 3) == 3
assert log(5, 1) is zoo
assert log(1, 1) is nan
assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
assert log(Rational(2, 3), Rational(2, 5)) == \
log(Rational(2, 3))/log(Rational(2, 5))
# issue 17148
assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
def test_log_symbolic():
assert log(x, exp(1)) == log(x)
assert log(exp(x)) != x
assert log(x, exp(1)) == log(x)
assert log(x*y) != log(x) + log(y)
assert log(x/y).expand() != log(x) - log(y)
assert log(x/y).expand(force=True) == log(x) - log(y)
assert log(x**y).expand() != y*log(x)
assert log(x**y).expand(force=True) == y*log(x)
assert log(x, 2) == log(x)/log(2)
assert log(E, 2) == 1/log(2)
p, q = symbols('p,q', positive=True)
r = Symbol('r', real=True)
assert log(p**2) != 2*log(p)
assert log(p**2).expand() == 2*log(p)
assert log(x**2).expand() != 2*log(x)
assert log(p**q) != q*log(p)
assert log(exp(p)) == p
assert log(p*q) != log(p) + log(q)
assert log(p*q).expand() == log(p) + log(q)
assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
assert log(-exp(p)) != p + I*pi
assert log(-exp(x)).expand() != x + I*pi
assert log(-exp(r)).expand() == r + I*pi
assert log(x**y) != y*log(x)
assert (log(x**-5)**-1).expand() != -1/log(x)/5
assert (log(p**-5)**-1).expand() == -1/log(p)/5
assert log(-x).func is log and log(-x).args[0] == -x
assert log(-p).func is log and log(-p).args[0] == -p
def test_log_exp():
assert log(exp(4*I*pi)) == 0 # exp evaluates
assert log(exp(-5*I*pi)) == I*pi # exp evaluates
assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
assert log(exp(-5*I)) == -5*I + 2*I*pi
def test_exp_assumptions():
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
for e in exp, exp_polar:
assert e(x).is_real is None
assert e(x).is_imaginary is None
assert e(i).is_real is None
assert e(i).is_imaginary is None
assert e(r).is_real is True
assert e(r).is_imaginary is False
assert e(re(x)).is_extended_real is True
assert e(re(x)).is_imaginary is False
assert exp(0, evaluate=False).is_algebraic
a = Symbol('a', algebraic=True)
an = Symbol('an', algebraic=True, nonzero=True)
r = Symbol('r', rational=True)
rn = Symbol('rn', rational=True, nonzero=True)
assert exp(a).is_algebraic is None
assert exp(an).is_algebraic is False
assert exp(pi*r).is_algebraic is None
assert exp(pi*rn).is_algebraic is False
assert exp(0, evaluate=False).is_algebraic is True
assert exp(I*pi/3, evaluate=False).is_algebraic is True
assert exp(I*pi*r, evaluate=False).is_algebraic is True
def test_exp_AccumBounds():
assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
def test_log_assumptions():
p = symbols('p', positive=True)
n = symbols('n', negative=True)
z = symbols('z', zero=True)
x = symbols('x', infinite=True, extended_positive=True)
assert log(z).is_positive is False
assert log(x).is_extended_positive is True
assert log(2) > 0
assert log(1, evaluate=False).is_zero
assert log(1 + z).is_zero
assert log(p).is_zero is None
assert log(n).is_zero is False
assert log(0.5).is_negative is True
assert log(exp(p) + 1).is_positive
assert log(1, evaluate=False).is_algebraic
assert log(42, evaluate=False).is_algebraic is False
assert log(1 + z).is_rational
def test_log_hashing():
assert x != log(log(x))
assert hash(x) != hash(log(log(x)))
assert log(x) != log(log(log(x)))
e = 1/log(log(x) + log(log(x)))
assert e.base.func is log
e = 1/log(log(x) + log(log(log(x))))
assert e.base.func is log
e = log(log(x))
assert e.func is log
assert not x.func is log
assert hash(log(log(x))) != hash(x)
assert e != x
def test_log_sign():
assert sign(log(2)) == 1
def test_log_expand_complex():
assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
def test_log_apply_evalf():
value = (log(3)/log(2) - 1).evalf()
assert value.epsilon_eq(Float("0.58496250072115618145373"))
def test_log_nseries():
assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4)
assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4)
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3)
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3)
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3)
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3)
def test_log_expand():
w = Symbol("w", positive=True)
e = log(w**(log(5)/log(3)))
assert e.expand() == log(5)/log(3) * log(w)
x, y, z = symbols('x,y,z', positive=True)
assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
log((log(y) + log(z))*log(x)) + log(2)]
assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
assert log(x**log(x**2)).expand() == 2*log(x)**2
x, y = symbols('x,y')
assert log(x*y).expand(force=True) == log(x) + log(y)
assert log(x**y).expand(force=True) == y*log(x)
assert log(exp(x)).expand(force=True) == x
# there's generally no need to expand out logs since this requires
# factoring and if simplification is sought, it's cheaper to put
# logs together than it is to take them apart.
assert log(2*3**2).expand() != 2*log(3) + log(2)
@XFAIL
def test_log_expand_fail():
x, y, z = symbols('x,y,z', positive=True)
assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
x) + y*log(y + z) + z*log(x) + z*log(y + z)
def test_log_simplify():
x = Symbol("x", positive=True)
assert log(x**2).expand() == 2*log(x)
assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
z = Symbol('z')
assert log(sqrt(z)).expand() == log(z)/2
assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
assert log(z**(-1)).expand() != -log(z)
assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
def test_log_AccumBounds():
assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
def test_lambertw():
k = Symbol('k')
assert LambertW(x, 0) == LambertW(x)
assert LambertW(x, 0, evaluate=False) != LambertW(x)
assert LambertW(0) == 0
assert LambertW(E) == 1
assert LambertW(-1/E) == -1
assert LambertW(-log(2)/2) == -log(2)
assert LambertW(oo) is oo
assert LambertW(0, 1) is -oo
assert LambertW(0, 42) is -oo
assert LambertW(-pi/2, -1) == -I*pi/2
assert LambertW(-1/E, -1) == -1
assert LambertW(-2*exp(-2), -1) == -2
assert LambertW(2*log(2)) == log(2)
assert LambertW(-pi/2) == I*pi/2
assert LambertW(exp(1 + E)) == E
assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
Float("0.701338383413663009202120278965", 30), 1e-29)
assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
assert LambertW(-1).is_real is False # issue 5215
assert LambertW(2, evaluate=False).is_real
p = Symbol('p', positive=True)
assert LambertW(p, evaluate=False).is_real
assert LambertW(p - 1, evaluate=False).is_real is None
assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
assert LambertW(S.Half, -1, evaluate=False).is_real is False
assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
assert LambertW(-10, -1, evaluate=False).is_real is False
assert LambertW(-2, 2, evaluate=False).is_real is False
assert LambertW(0, evaluate=False).is_algebraic
na = Symbol('na', nonzero=True, algebraic=True)
assert LambertW(na).is_algebraic is False
def test_issue_5673():
e = LambertW(-1)
assert e.is_comparable is False
assert e.is_positive is not True
e2 = 1 - 1/(1 - exp(-1000))
assert e2.is_positive is not True
e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
assert e3.is_nonzero is not True
def test_log_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: log(x).fdiff(2))
def test_log_taylor_term():
x = symbols('x')
assert log(x).taylor_term(0, x) == x
assert log(x).taylor_term(1, x) == -x**2/2
assert log(x).taylor_term(4, x) == x**5/5
assert log(x).taylor_term(-1, x) is S.Zero
def test_exp_expand_NC():
A, B, C = symbols('A,B,C', commutative=False)
assert exp(A + B).expand() == exp(A + B)
assert exp(A + B + C).expand() == exp(A + B + C)
assert exp(x + y).expand() == exp(x)*exp(y)
assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
def test_as_numer_denom():
n = symbols('n', negative=True)
assert exp(x).as_numer_denom() == (exp(x), 1)
assert exp(-x).as_numer_denom() == (1, exp(x))
assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
assert exp(-2).as_numer_denom() == (1, exp(2))
assert exp(n).as_numer_denom() == (1, exp(-n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
def test_polar():
x, y = symbols('x y', polar=True)
assert abs(exp_polar(I*4)) == 1
assert abs(exp_polar(0)) == 1
assert abs(exp_polar(2 + 3*I)) == exp(2)
assert exp_polar(I*10).n() == exp_polar(I*10)
assert log(exp_polar(z)) == z
assert log(x*y).expand() == log(x) + log(y)
assert log(x**z).expand() == z*log(x)
assert exp_polar(3).exp == 3
# Compare exp(1.0*pi*I).
assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
assert exp_polar(0).is_rational is True # issue 8008
def test_exp_summation():
w = symbols("w")
m, n, i, j = symbols("m n i j")
expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
def test_log_product():
from sympy.abc import n, m
from sympy.concrete import Product
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
z = symbols('z', real=True)
w = symbols('w')
expr = log(Product(x**i, (i, 1, n)))
assert simplify(expr) == expr
assert expr.expand() == Sum(i*log(x), (i, 1, n))
expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
assert simplify(expr) == expr
assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
expr = log(Product(-2, (n, 0, 4)))
assert simplify(expr) == expr
assert expr.expand() == expr
assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
expr = log(Product(exp(z*i), (i, 0, n)))
assert expr.expand() == Sum(z*i, (i, 0, n))
expr = log(Product(exp(w*i), (i, 0, n)))
assert expr.expand() == expr
assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
@XFAIL
def test_log_product_simplify_to_sum():
from sympy.abc import n, m
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
from sympy.concrete import Product, Sum
assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
def test_issue_8866():
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
y = Symbol('y', positive=True)
l1 = log(exp(y), exp(10))
b1 = log(exp(y), exp(5))
l2 = log(exp(y), exp(10), evaluate=False)
b2 = log(exp(y), exp(5), evaluate=False)
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
def test_log_expand_factor():
assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3)
assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2
assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3)
assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1
assert expand_log(log(12), factor=True) == log(3) + 2*log(2)
assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1
assert expand_log(log(45)/log(5) + log(20), factor=False) == \
1 + 2*log(3)/log(5) + log(20)
assert expand_log(log(45)/log(5) + log(26), factor=True) == \
log(2) + log(13) + (log(5) + 2*log(3))/log(5)
def test_issue_9116():
n = Symbol('n', positive=True, integer=True)
assert ln(n).is_nonnegative is True
assert log(n).is_nonnegative is True
|
37a4d3beb968f47f48b7b1e6b0a62c48902b0638865044a15581a8e325ab5c1d | from sympy import (
adjoint, And, Basic, conjugate, diff, expand, Eq, Function, I, ITE,
Integral, integrate, Interval, KroneckerDelta, lambdify, log, Max, Min,
oo, Or, pi, Piecewise, piecewise_fold, Rational, solve, symbols, transpose,
cos, sin, exp, Abs, Ne, Not, Symbol, S, sqrt, Sum, Tuple, zoo, Float,
DiracDelta, Heaviside, Add, Mul, factorial, Ge, Contains)
from sympy.core.expr import unchanged
from sympy.functions.elementary.piecewise import Undefined, ExprCondPair
from sympy.printing import srepr
from sympy.testing.pytest import raises, slow
from sympy.simplify import simplify
a, b, c, d, x, y = symbols('a:d, x, y')
z = symbols('z', nonzero=True)
def test_piecewise1():
# Test canonicalization
assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True), (1, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
Piecewise((x, x < 1))
assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
Piecewise((x, Or(x < 1, x < 2)), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
assert Piecewise((x, True)) == x
# Explicitly constructed empty Piecewise not accepted
raises(TypeError, lambda: Piecewise())
# False condition is never retained
assert Piecewise((2*x, x < 0), (x, False)) == \
Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
Piecewise((2*x, x < 0))
assert Piecewise((x, False)) == Undefined
raises(TypeError, lambda: Piecewise(x))
assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
raises(TypeError, lambda: Piecewise((x, 2)))
raises(TypeError, lambda: Piecewise((x, x**2)))
raises(TypeError, lambda: Piecewise(([1], True)))
assert Piecewise(((1, 2), True)) == Tuple(1, 2)
cond = (Piecewise((1, x < 0), (2, True)) < y)
assert Piecewise((1, cond)
) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
) == Piecewise((1, x > 0), (2, x > -1))
# test for supporting Contains in Piecewise
pwise = Piecewise(
(1, And(x <= 6, x > 1, Contains(x, S.Integers))),
(0, True))
assert pwise.subs(x, pi) == 0
assert pwise.subs(x, 2) == 1
assert pwise.subs(x, 7) == 0
# Test subs
p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
assert p.subs(x, x**2) == p_x2
assert p.subs(x, -5) == -1
assert p.subs(x, -1) == 1
assert p.subs(x, 1) == log(1)
# More subs tests
p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
assert p2.subs(x, 2) == 1
assert p2.subs(x, 4) == -1
assert p2.subs(x, 10) == 0
assert p3.subs(x, 0.0) == 1
assert p4.subs(x, 0.0) == 1
f, g, h = symbols('f,g,h', cls=Function)
pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
assert pg.subs(g, f) == pf
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
Piecewise((1, Eq(exp(z), cos(z))), (0, True))
p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
p6 = Piecewise((x, x > 0))
n = symbols('n', negative=True)
assert p6.subs(x, n) == Undefined
# Test evalf
assert p.evalf() == p
assert p.evalf(subs={x: -2}) == -1
assert p.evalf(subs={x: -1}) == 1
assert p.evalf(subs={x: 1}) == log(1)
assert p6.evalf(subs={x: -5}) == Undefined
# Test doit
f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
assert f_int.doit() == Piecewise( (S.Half, x < 1) )
# Test differentiation
f = x
fp = x*p
dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
fp_dx = x*dp + p
assert diff(p, x) == dp
assert diff(f*p, x) == fp_dx
# Test simple arithmetic
assert x*p == fp
assert x*p + p == p + x*p
assert p + f == f + p
assert p + dp == dp + p
assert p - dp == -(dp - p)
# Test power
dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
assert dp**2 == dp2
# Test _eval_interval
f1 = x*y + 2
f2 = x*y**2 + 3
peval = Piecewise((f1, x < 0), (f2, x > 0))
peval_interval = f1.subs(
x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
assert peval._eval_interval(x, 0, 0) == 0
assert peval._eval_interval(x, -1, 1) == peval_interval
peval2 = Piecewise((f1, x < 0), (f2, True))
assert peval2._eval_interval(x, 0, 0) == 0
assert peval2._eval_interval(x, 1, -1) == -peval_interval
assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
assert peval2._eval_interval(x, -1, 1) == peval_interval
assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
# Test integration
assert p.integrate() == Piecewise(
(-x, x < -1),
(x**3/3 + Rational(4, 3), x < 0),
(x*log(x) - x + Rational(4, 3), True))
p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
assert integrate(p, (x, -2, 2)) == Rational(5, 6)
assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
assert integrate(p, (x, -oo, oo)) == 2
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert integrate(p, (x, -2, 2)) == Undefined
# Test commutativity
assert isinstance(p, Piecewise) and p.is_commutative is True
def test_piecewise_free_symbols():
f = Piecewise((x, a < 0), (y, True))
assert f.free_symbols == {x, y, a}
def test_piecewise_integrate1():
x, y = symbols('x y', real=True, finite=True)
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert integrate(f, (x, -2, 2)) == Rational(14, 3)
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(43, 6)
assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
assert integrate(g, (x, -2, 2)) == Rational(28, 3)
assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
def test_piecewise_integrate1b():
g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
assert integrate(g, (x, -1, 1)) == 0
g = Piecewise((1, x - y < 0), (0, True))
assert integrate(g, (y, -oo, 0)) == -Min(0, x)
assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
assert integrate(g, (y, 0, -oo)) == Min(0, x)
assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
assert integrate(g, (y, -oo, oo)) == -x + oo
g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
for yy in (-1, S.Half, 2):
assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
assert gy1 == Piecewise(
(-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
(-y + 1, True))
assert g1y == Piecewise(
(Min(1, Max(0, y))**2/2 - S.Half, y < 1),
(y - 1, True))
@slow
def test_piecewise_integrate1ca():
y = symbols('y', real=True)
g = Piecewise(
(1 - x, Interval(0, 1).contains(x)),
(1 + x, Interval(-1, 0).contains(x)),
(0, True)
)
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
# XXX Make test pass without simplify
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2).simplify()
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2).simplify()
assert piecewise_fold(gy1.rewrite(Piecewise)) == \
Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)) == \
Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
# g1y and gy1 should simplify if the condition that y < 1
# is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
# XXX Make test pass without simplify
assert gy1.simplify() == Piecewise(
(
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
Min(1, Max(0, y))**2 + S.Half, y < 1),
(0, True)
)
assert g1y.simplify() == Piecewise(
(
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
Min(1, Max(0, y))**2 - S.Half, y < 1),
(0, True))
@slow
def test_piecewise_integrate1cb():
y = symbols('y', real=True)
g = Piecewise(
(0, Or(x <= -1, x >= 1)),
(1 - x, x > 0),
(1 + x, True)
)
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
assert piecewise_fold(gy1.rewrite(Piecewise)) == \
Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)) == \
Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
# g1y and gy1 should simplify if the condition that y < 1
# is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
assert gy1 == Piecewise(
(
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
Min(1, Max(0, y))**2 + S.Half, y < 1),
(0, True)
)
assert g1y == Piecewise(
(
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
Min(1, Max(0, y))**2 - S.Half, y < 1),
(0, True))
def test_piecewise_integrate2():
from itertools import permutations
lim = Tuple(x, c, d)
p = Piecewise((1, x < a), (2, x > b), (3, True))
q = p.integrate(lim)
assert q == Piecewise(
(-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
(-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
for v in permutations((1, 2, 3, 4)):
r = dict(zip((a, b, c, d), v))
assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
def test_meijer_bypass():
# totally bypass meijerg machinery when dealing
# with Piecewise in integrate
assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
def test_piecewise_integrate3_inequality_conditions():
from sympy.utilities.iterables import cartes
lim = (x, 0, 5)
# set below includes two pts below range, 2 pts in range,
# 2 pts above range, and the boundaries
N = (-2, -1, 0, 1, 2, 5, 6, 7)
p = Piecewise((1, x > a), (2, x > b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
p = Piecewise((1, x > a), (2, x < b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
# delete old tests that involved c1 and c2 since those
# reduce to the above except that a value of 0 was used
# for two expressions whereas the above uses 3 different
# values
@slow
def test_piecewise_integrate4_symbolic_conditions():
a = Symbol('a', real=True, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, x < a), (0, x > b), (1, True))
p2 = Piecewise((0, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0, True))
p4 = Piecewise((0, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
lim = Tuple(x, y, oo)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a:3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
ans = Piecewise(
(0, x <= Min(a, b)),
(x - Min(a, b), x <= b),
(b - Min(a, b), True))
for i in (p0, p1, p2, p4):
assert i.integrate(x) == ans
assert p3.integrate(x) == Piecewise(
(0, x < a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
assert p5.integrate(x) == Piecewise(
(0, x <= a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
p1 = Piecewise((0, x < a), (0.5, x > b), (1, True))
p2 = Piecewise((0.5, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0.5, True))
p4 = Piecewise((0.5, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
def test_piecewise_integrate5_independent_conditions():
p = Piecewise((0, Eq(y, 0)), (x*y, True))
assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
def test_piecewise_simplify():
p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
((-1)**x*(-1), True))
assert p.simplify() == \
Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
# simplify when there are Eq in conditions
assert Piecewise(
(a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
) == Piecewise(
(0, And(Eq(a, 0), Eq(b, 0))), (1, True))
assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
+ a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
) == Piecewise(
(2*x, And(Eq(a, 0), Eq(y, 0))),
(2, And(Eq(a, 1), Eq(y, 0))),
(0, True))
args = (2, And(Eq(x, 2), Ge(y ,0))), (x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
args = (1, Eq(x, 0)), (sin(x)/x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
).simplify() == x
# check that x or f(x) are recognized as being Symbol-like for lhs
args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
ans = x + sin(x) + 1
f = Function('f')
assert Piecewise(*args).simplify() == ans
assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
# issue 18634
d = Symbol("d", integer=True)
n = Symbol("n", integer=True)
t = Symbol("t", real=True, positive=True)
expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
assert expr.simplify() == -d + 2*n
def test_piecewise_solve():
abs2 = Piecewise((-x, x <= 0), (x, x > 0))
f = abs2.subs(x, x - 2)
assert solve(f, x) == [2]
assert solve(f - 1, x) == [1, 3]
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert solve(f, x) == [2]
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2),
(-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
assert solve(g, x) == [5]
# if no symbol is given the piecewise detection must still work
assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
f = Piecewise(((x - 2)**2, x >= 0), (0, True))
raises(NotImplementedError, lambda: solve(f, x))
def nona(ans):
return list(filter(lambda x: x is not S.NaN, ans))
p = Piecewise((x**2 - 4, x < y), (x - 2, True))
ans = solve(p, x)
assert nona([i.subs(y, -2) for i in ans]) == [2]
assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
assert ans == [
Piecewise((-2, y > -2), (S.NaN, True)),
Piecewise((2, y <= 2), (S.NaN, True)),
Piecewise((2, y > 2), (S.NaN, True))]
# issue 6060
absxm3 = Piecewise(
(x - 3, 0 <= x - 3),
(3 - x, 0 > x - 3)
)
assert solve(absxm3 - y, x) == [
Piecewise((-y + 3, -y < 0), (S.NaN, True)),
Piecewise((y + 3, y >= 0), (S.NaN, True))]
p = Symbol('p', positive=True)
assert solve(absxm3 - p, x) == [-p + 3, p + 3]
# issue 6989
f = Function('f')
assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
[Piecewise((-1, x > 0), (0, True))]
# issue 8587
f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
assert solve(f - 1) == [1/sqrt(2)]
def test_piecewise_fold():
p = Piecewise((x, x < 1), (1, 1 <= x))
assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
assert piecewise_fold(Piecewise((1, x < 0), (2, True))
+ Piecewise((10, x < 0), (-10, True))) == \
Piecewise((11, x < 0), (-8, True))
p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
p = 4*p1 + 2*p2
assert integrate(
piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
assert piecewise_fold(
Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
)) == Piecewise((1, y <= 0), (-2, y >= 0))
assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
assert piecewise_fold(Mul(a, b, evaluate=False)
) == piecewise_fold(Mul(b, a, evaluate=False))
def test_piecewise_fold_piecewise_in_cond():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
assert p2.subs(x, -pi/2) == 0
assert p2.subs(x, 1) == 0
assert p2.subs(x, -pi/4) == 1
p4 = Piecewise((0, Eq(p1, 0)), (1,True))
ans = piecewise_fold(p4)
for i in range(-1, 1):
assert ans.subs(x, i) == p4.subs(x, i)
r1 = 1 < Piecewise((1, x < 1), (3, True))
ans = piecewise_fold(r1)
for i in range(2):
assert ans.subs(x, i) == r1.subs(x, i)
p5 = Piecewise((1, x < 0), (3, True))
p6 = Piecewise((1, x < 1), (3, True))
p7 = Piecewise((1, p5 < p6), (0, True))
ans = piecewise_fold(p7)
for i in range(-1, 2):
assert ans.subs(x, i) == p7.subs(x, i)
def test_piecewise_fold_piecewise_in_cond_2():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
p3 = Piecewise(
(0, (x >= 0) | Eq(cos(x), 0)),
(1/cos(x), x < 0),
(zoo, True)) # redundant b/c all x are already covered
assert(piecewise_fold(p2) == p3)
def test_piecewise_fold_expand():
p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
p2 = piecewise_fold(expand((1 - x)*p1))
assert p2 == Piecewise((1 - x, (x >= 0) & (x < 1)), (0, True))
assert p2 == expand(piecewise_fold((1 - x)*p1))
def test_piecewise_duplicate():
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert p == Piecewise(*p.args)
def test_doit():
p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
assert p2.doit() == p1
assert p2.doit(deep=False) == p2
# issue 17165
p1 = Sum(y**x, (x, -1, oo)).doit()
assert p1.doit() == p1
def test_piecewise_interval():
p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
assert p1.subs(x, -0.5) == 0
assert p1.subs(x, 0.5) == 0.5
assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
assert integrate(p1, x) == Piecewise(
(0, x <= 0),
(x**2/2, x <= 1),
(S.Half, True))
def test_piecewise_collapse():
assert Piecewise((x, True)) == x
a = x < 1
assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
b = x < 5
def canonical(i):
if isinstance(i, Piecewise):
return Piecewise(*i.args)
return i
for args in [
((1, a), (Piecewise((2, a), (3, b)), b)),
((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
for i in (0, 2, 10):
assert canonical(
Piecewise(*args, evaluate=False).subs(x, i)
) == canonical(Piecewise(*args).subs(x, i))
r1, r2, r3, r4 = symbols('r1:5')
a = x < r1
b = x < r2
c = x < r3
d = x < r4
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, a), (3, b), (5, c))
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c), (6, True)), c), (5, d)
) == Piecewise((1, a), (Piecewise(
(3, b), (4, c)), c), (5, d))
assert Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b)), b), (5, c))
assert Piecewise((1, c), (2, ~c), (3, S.true)
) == Piecewise((1, c), (2, S.true))
assert Piecewise((1, c), (2, And(~c, b)), (3,True)
) == Piecewise((1, c), (2, b), (3, True))
assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
def test_piecewise_lambdify():
p = Piecewise(
(x**2, x < 0),
(x, Interval(0, 1, False, True).contains(x)),
(2 - x, x >= 1),
(0, True)
)
f = lambdify(x, p)
assert f(-2.0) == 4.0
assert f(0.0) == 0.0
assert f(0.5) == 0.5
assert f(2.0) == 0.0
def test_piecewise_series():
from sympy import sin, cos, O
p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
assert p1.nseries(x, n=2) == p2
def test_piecewise_as_leading_term():
p1 = Piecewise((1/x, x > 1), (0, True))
p2 = Piecewise((x, x > 1), (0, True))
p3 = Piecewise((1/x, x > 1), (x, True))
p4 = Piecewise((x, x > 1), (1/x, True))
p5 = Piecewise((1/x, x > 1), (x, True))
p6 = Piecewise((1/x, x < 1), (x, True))
p7 = Piecewise((x, x < 1), (1/x, True))
p8 = Piecewise((x, x > 1), (1/x, True))
assert p1.as_leading_term(x) == 0
assert p2.as_leading_term(x) == 0
assert p3.as_leading_term(x) == x
assert p4.as_leading_term(x) == 1/x
assert p5.as_leading_term(x) == x
assert p6.as_leading_term(x) == 1/x
assert p7.as_leading_term(x) == x
assert p8.as_leading_term(x) == 1/x
def test_piecewise_complex():
p1 = Piecewise((2, x < 0), (1, 0 <= x))
p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
p3 = Piecewise((I*x, x > 1), (1 + I, True))
p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
assert conjugate(p1) == p1
assert conjugate(p2) == piecewise_fold(-p2)
assert conjugate(p3) == p4
assert p1.is_imaginary is False
assert p1.is_real is True
assert p2.is_imaginary is True
assert p2.is_real is False
assert p3.is_imaginary is None
assert p3.is_real is None
assert p1.as_real_imag() == (p1, 0)
assert p2.as_real_imag() == (0, -I*p2)
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
p = Piecewise((A*B**2, x > 0), (A**2*B, True))
assert p.adjoint() == \
Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
assert p.conjugate() == \
Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
assert p.transpose() == \
Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
def test_piecewise_evaluate():
assert Piecewise((x, True)) == x
assert Piecewise((x, True), evaluate=True) == x
p = Piecewise((x, True), evaluate=False)
assert p != x
assert p.is_Piecewise
assert all(isinstance(i, Basic) for i in p.args)
assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
(1, Eq(1, x)),)
def test_as_expr_set_pairs():
assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
[(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
[((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
def test_S_srepr_is_identity():
p = Piecewise((10, Eq(x, 0)), (12, True))
q = S(srepr(p))
assert p == q
def test_issue_12587():
# sort holes into intervals
p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
assert p.integrate((x, -5, 5)) == 23
p = Piecewise((1, x > 1), (2, x < y), (3, True))
lim = x, -3, 3
ans = p.integrate(lim)
for i in range(-1, 3):
assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
def test_issue_11045():
assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
# handle And with Or arguments
assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# hidden false
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# targetcond is Eq
assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
).integrate((x, 0, 4)) == 6
# And has Relational needing to be solved
assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# Or has Relational needing to be solved
assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
).integrate((x, 0, 3)) == 2
# ignore hidden false (handled in canonicalization)
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# watch for hidden True Piecewise
assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
).integrate((x, 0, 3)) == 6
# overlapping conditions of targetcond are recognized and ignored;
# the condition x > 3 will be pre-empted by the first condition
assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
).integrate((x, 0, 4)) == 6
# convert Ne to Or
assert Piecewise((1, Ne(x, 0)), (2, True)
).integrate((x, -1, 1)) == 2
# no default but well defined
assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
).integrate((x, 1, 4)) == 5
p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
nan = Undefined
i = p.integrate((x, 1, y))
assert i == Piecewise(
(y - 1, y < 1),
(Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
y <= Min(4, y)),
(nan, True))
assert p.integrate((x, 1, -1)) == i.subs(y, -1)
assert p.integrate((x, 1, 4)) == 5
assert p.integrate((x, 1, 5)) is nan
# handle Not
p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
assert p.integrate((x, 0, 3)) == 4
# handle updating of int_expr when there is overlap
p = Piecewise(
(1, And(5 > x, x > 1)),
(2, Or(x < 3, x > 7)),
(4, x < 8))
assert p.integrate((x, 0, 10)) == 20
# And with Eq arg handling
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
).integrate((x, 0, 3)) is S.NaN
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
).integrate((x, 0, 3)) == 7
assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
).integrate((x, -1, 1)) == 4
# middle condition doesn't matter: it's a zero width interval
assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
).integrate((x, 0, 3)) == 7
def test_holes():
nan = Undefined
assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
(x, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
(nan, x < 1), (x - 1, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
# this also tests that the integrate method is used on non-Piecwise
# arguments in _eval_integral
A, B = symbols("A B")
a, b = symbols('a b', real=True)
assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
).integrate(x) == Piecewise(
(B*x, (a > 2)),
(Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
(Piecewise((B*x, x < 1), (nan, True)), True))
def test_issue_11922():
def f(x):
return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
autocorr = lambda k: (
f(x) * f(x + k)).integrate((x, -1, 1))
assert autocorr(1.9) > 0
k = symbols('k')
good_autocorr = lambda k: (
(1 - x**2) * f(x + k)).integrate((x, -1, 1))
a = good_autocorr(k)
assert a.subs(k, 3) == 0
k = symbols('k', positive=True)
a = good_autocorr(k)
assert a.subs(k, 3) == 0
assert Piecewise((0, x < 1), (10, (x >= 1))
).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
def test_issue_5227():
f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
(-0.0160799238820171*x + 1.33215984776403, x < 2),
(Piecewise((0.3, x > 123), (0.7, True)) +
Piecewise((0.4, x > 2), (0.6, True)), x <=
123), (-0.00817409766454352*x + 2.10541401273885, x <
380.571428571429), (0, True))
i = integrate(f, (x, -oo, oo))
assert i == Integral(f, (x, -oo, oo)).doit()
assert str(i) == '1.00195081676351'
assert Piecewise((1, x - y < 0), (0, True)
).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
def test_issue_10137():
a = Symbol('a', real=True, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
ip3 = integrate(p3, x)
assert ip3 == Piecewise(
(0, x <= 0),
(x, x <= Max(0, a)),
(Max(0, a), True))
ip4 = integrate(p4, x)
assert ip4 == ip3
assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
def test_stackoverflow_43852159():
f = lambda x: Piecewise((1 , (x >= -1) & (x <= 1)) , (0, True))
Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
cx = Conv(x)
assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
assert cx.subs(x, 3) == 0
assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
(1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
(0, True))
def test_issue_12557():
'''
# 3200 seconds to compute the fourier part of issue
import sympy as sym
x,y,z,t = sym.symbols('x y z t')
k = sym.symbols("k", integer=True)
fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
(x, -sym.pi, sym.pi))
assert fourier == FourierSeries(
sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
-k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
(Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
-k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
- pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
2*pi*_n**2*k**2 + pi*k**4) +
(-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
'''
x = symbols("x", real=True)
k = symbols('k', integer=True, finite=True)
abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
assert integrate(abs2(x), (x, -pi, pi)) == pi**2
func = cos(k*x)*sqrt(x**2)
assert integrate(func, (x, -pi, pi)) == Piecewise(
(2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
def test_issue_6900():
from itertools import permutations
t0, t1, T, t = symbols('t0, t1 T t')
f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
g = f.integrate(t)
assert g == Piecewise(
(0, t <= t0),
(t*x - t0*x, t <= Max(t0, t1)),
(-t0*x + x*Max(t0, t1), True))
for i in permutations(range(2)):
reps = dict(zip((t0,t1), i))
for tt in range(-1,3):
assert (g.xreplace(reps).subs(t,tt) ==
f.xreplace(reps).integrate(t).subs(t,tt))
lim = Tuple(t, t0, T)
g = f.integrate(lim)
ans = Piecewise(
(-t0*x + x*Min(T, Max(t0, t1)), T > t0),
(0, True))
for i in permutations(range(3)):
reps = dict(zip((t0,t1,T), i))
tru = f.xreplace(reps).integrate(lim.xreplace(reps))
assert tru == ans.xreplace(reps)
assert g == ans
def test_issue_10122():
assert solve(abs(x) + abs(x - 1) - 1 > 0, x
) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
def test_issue_4313():
u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
e = (u - u.subs(x, y))**2/(x - y)**2
M = Max(0, a)
assert integrate(e, x).expand() == Piecewise(
(Piecewise(
(0, x <= 0),
(-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
2*y*log(x - y)/a**2 - y/a**2, x <= M),
(-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
M)/a**2 - y/a**2 + M/a**2, True)),
((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
(Piecewise(
(-1/(x - y), x <= 0),
(-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
y/a**2, x <= M),
(-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
a**2*M) - y**2/(-a**2*y + a**2*M) +
2*log(-y)/a - 2*log(-y + M)/a + 2/a -
2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
y/a**2 + M/a**2, True)),
a <= y),
(Piecewise(
(-y**2/(a**2*x - a**2*y), x <= 0),
(x/a**2 + y/a**2, x <= M),
(a**2/(-a**2*y + a**2*M) -
a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
True))
def test__intervals():
assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == []
assert Piecewise(
(1, x > x + 1),
(Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
(1, True))._intervals(x) == [(-oo, oo, 1, 1)]
assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == [
(-oo, oo, 1, 0)]
assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
)._intervals(x) == [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]
# the following tests that duplicates are removed and that non-Eq
# generated zero-width intervals are removed
assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
)._intervals(x) == [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]
def test_containment():
a, b, c, d, e = [1, 2, 3, 4, 5]
p = (Piecewise((d, x > 1), (e, True))*
Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
assert p.integrate(x).diff(x) == Piecewise(
(c*e, x <= 0),
(a*e, x <= 1),
(a*d, x < 2), # this is what we want to get right
(b*d, x < 4),
(c*d, True))
def test_piecewise_with_DiracDelta():
d1 = DiracDelta(x - 1)
assert integrate(d1, (x, -oo, oo)) == 1
assert integrate(d1, (x, 0, 2)) == 1
assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
(Heaviside(x - 1), x < 2), (1, True))
# TODO raise error if function is discontinuous at limit of
# integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
# (d1, Eq(x ,1)
def test_issue_10258():
assert Piecewise((0, x < 1), (1, True)).is_zero is None
assert Piecewise((-1, x < 1), (1, True)).is_zero is False
a = Symbol('a', zero=True)
assert Piecewise((0, x < 1), (a, True)).is_zero
assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
a = Symbol('a')
assert Piecewise((0, x < 1), (a, True)).is_zero is None
assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
assert Piecewise((1, x < 1), (2, True)).is_nonzero
assert Piecewise((0, x < 1), (oo, True)).is_finite is None
assert Piecewise((0, x < 1), (1, True)).is_finite
b = Basic()
assert Piecewise((b, x < 1)).is_finite is None
# 10258
c = Piecewise((1, x < 0), (2, True)) < 3
assert c != True
assert piecewise_fold(c) == True
def test_issue_10087():
a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
m = a*b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
m = a + b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
def test_issue_8919():
c = symbols('c:5')
x = symbols("x")
f1 = Piecewise((c[1], x < 1), (c[2], True))
f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
assert integrate(f1*f2, (x, 0, 2)
) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
f1 = Piecewise((0, x < 1), (2, True))
f2 = Piecewise((3, x < 2), (0, True))
assert integrate(f1*f2, (x, 0, 3)) == 6
y = symbols("y", positive=True)
a, b, c, x, z = symbols("a,b,c,x,z", real=True)
I = Integral(Piecewise(
(0, (x >= y) | (x < 0) | (b > c)),
(a, True)), (x, 0, z))
ans = I.doit()
assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
for cond in (True, False):
for yy in range(1, 3):
for zz in range(-yy, 0, yy):
reps = [(b > c, cond), (y, yy), (z, zz)]
assert ans.subs(reps) == I.subs(reps).doit()
def test_unevaluated_integrals():
f = Function('f')
p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
assert p.integrate(x) == Integral(p, x)
assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
# test it by replacing f(x) with x%2 which will not
# affect the answer: the integrand is essentially 2 over
# the domain of integration
assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10
# this is a test of using _solve_inequality when
# solve_univariate_inequality fails
assert p.integrate(y) == Piecewise(
(y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
(2*y, (x >= -oo) & (x < 10)), (0, True))
def test_conditions_as_alternate_booleans():
a, b, c = symbols('a:c')
assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
def test_Piecewise_rewrite_as_ITE():
a, b, c, d = symbols('a:d')
def _ITE(*args):
return Piecewise(*args).rewrite(ITE)
assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < 2), (c, True)
) == ITE(x < 1, a, ITE(x < 2, b, c))
assert _ITE((a, x < 1), (b, y < 2), (c, True)
) == ITE(x < 1, a, ITE(y < 2, b, c))
assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
) == ITE(x < 1, a, ITE(y < 1, c, b))
assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
) == ITE(x < 0, a, b)
raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
# if `a` in the following were replaced with y then the coverage
# is complete but something other than as_set would need to be
# used to detect this
raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
def test_issue_14052():
assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
def test_issue_14240():
assert piecewise_fold(
Piecewise((1, a), (2, b), (4, True)) +
Piecewise((8, a), (16, True))
) == Piecewise((9, a), (18, b), (20, True))
assert piecewise_fold(
Piecewise((2, a), (3, b), (5, True)) *
Piecewise((7, a), (11, True))
) == Piecewise((14, a), (33, b), (55, True))
# these will hang if naive folding is used
assert piecewise_fold(Add(*[
Piecewise((i, a), (0, True)) for i in range(40)])
) == Piecewise((780, a), (0, True))
assert piecewise_fold(Mul(*[
Piecewise((i, a), (0, True)) for i in range(1, 41)])
) == Piecewise((factorial(40), a), (0, True))
def test_issue_14787():
x = Symbol('x')
f = Piecewise((x, x < 1), ((S(58) / 7), True))
assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
def test_issue_8458():
x, y = symbols('x y')
# Original issue
p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
assert p1.simplify() == sin(x)
# Slightly larger variant
p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p2.simplify() == sin(x)
# Test for problem highlighted during review
p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
def test_issue_16417():
from sympy import im, re, Gt
z = Symbol('z')
assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
x = Symbol('x')
assert unchanged(Piecewise, (S.Pi, re(x) < 0),
(0, Or(re(x) > 0, Ne(im(x), 0))),
(S.NaN, True))
r = Symbol('r', real=True)
p = Piecewise((S.Pi, re(r) < 0),
(0, Or(re(r) > 0, Ne(im(r), 0))),
(S.NaN, True))
assert p == Piecewise((S.Pi, r < 0),
(0, r > 0),
(S.NaN, True), evaluate=False)
# Does not work since imaginary != 0...
#i = Symbol('i', imaginary=True)
#p = Piecewise((S.Pi, re(i) < 0),
# (0, Or(re(i) > 0, Ne(im(i), 0))),
# (S.NaN, True))
#assert p == Piecewise((0, Ne(im(i), 0)),
# (S.NaN, True), evaluate=False)
i = I*r
p = Piecewise((S.Pi, re(i) < 0),
(0, Or(re(i) > 0, Ne(im(i), 0))),
(S.NaN, True))
assert p == Piecewise((0, Ne(im(i), 0)),
(S.NaN, True), evaluate=False)
assert p == Piecewise((0, Ne(r, 0)),
(S.NaN, True), evaluate=False)
def test_eval_rewrite_as_KroneckerDelta():
x, y, z, n, t, m = symbols('x y z n t m')
K = KroneckerDelta
f = lambda p: expand(p.rewrite(K))
p1 = Piecewise((0, Eq(x, y)), (1, True))
assert f(p1) == 1 - K(x, y)
p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
p3 = Piecewise((1, Ne(x, y)), (0, True))
assert f(p3) == 1 - K(x, y)
p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
assert f(p4) == 4 - 3*K(3, x)
p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
assert f(p9) == 5 * K(1, y) * K(4, x) + 1
p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
assert f(p14) == 2 * K(0, x) * K(1, y) + 1
p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
*Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
(1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
p19 = Piecewise((0, x > 2), (1, True))
assert f(p19) == p19
p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
assert f(p20) == p20
p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
assert f(p21) == p21
p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
@slow
def test_identical_conds_issue():
from sympy.stats import Uniform, density
u1 = Uniform('u1', 0, 1)
u2 = Uniform('u2', 0, 1)
# Result is quite big, so not really important here (and should ideally be
# simpler). Should not give an exception though.
density(u1 + u2)
def test_issue_7370():
f = Piecewise((1, x <= 2400))
v = integrate(f, (x, 0, Float("252.4", 30)))
assert str(v) == '252.400000000000000000000000000'
def test_issue_16715():
raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
def test_issue_20360():
t, tau = symbols("t tau", real=True)
n = symbols("n", integer=True)
lam = pi * (n - S.Half)
eq = integrate(exp(lam * tau), (tau, 0, t))
assert simplify(eq) == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
|
36eecad3a49e08182b20284577d1916b91ff92de91b1bae2f08ee58f96efa7c6 | from sympy.core.add import Add
from sympy.core.assumptions import check_assumptions
from sympy.core.containers import Tuple
from sympy.core.compatibility import as_int, is_sequence, ordered
from sympy.core.exprtools import factor_terms
from sympy.core.function import _mexpand
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.numbers import igcdex, ilcm, igcd
from sympy.core.power import integer_nthroot, isqrt
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.core.sympify import _sympify
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.ntheory.factor_ import (
divisors, factorint, multiplicity, perfect_power)
from sympy.ntheory.generate import nextprime
from sympy.ntheory.primetest import is_square, isprime
from sympy.ntheory.residue_ntheory import sqrt_mod
from sympy.polys.polyerrors import GeneratorsNeeded
from sympy.polys.polytools import Poly, factor_list
from sympy.simplify.simplify import signsimp
from sympy.solvers.solveset import solveset_real
from sympy.utilities import default_sort_key, numbered_symbols
from sympy.utilities.misc import filldedent
# these are imported with 'from sympy.solvers.diophantine import *
__all__ = ['diophantine', 'classify_diop']
class DiophantineSolutionSet(set):
"""
Container for a set of solutions to a particular diophantine equation.
The base representation is a set of tuples representing each of the solutions.
Parameters
==========
symbols : list
List of free symbols in the original equation.
parameters: list (optional)
List of parameters to be used in the solution.
Examples
========
Adding solutions:
>>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet
>>> from sympy.abc import x, y, t, u
>>> s1 = DiophantineSolutionSet([x, y], [t, u])
>>> s1
set()
>>> s1.add((2, 3))
>>> s1.add((-1, u))
>>> s1
{(-1, u), (2, 3)}
>>> s2 = DiophantineSolutionSet([x, y], [t, u])
>>> s2.add((3, 4))
>>> s1.update(*s2)
>>> s1
{(-1, u), (2, 3), (3, 4)}
Conversion of solutions into dicts:
>>> list(s1.dict_iterator())
[{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}]
Substituting values:
>>> s3 = DiophantineSolutionSet([x, y], [t, u])
>>> s3.add((t**2, t + u))
>>> s3
{(t**2, t + u)}
>>> s3.subs({t: 2, u: 3})
{(4, 5)}
>>> s3.subs(t, -1)
{(1, u - 1)}
>>> s3.subs(t, 3)
{(9, u + 3)}
Evaluation at specific values. Positional arguments are given in the same order as the parameters:
>>> s3(-2, 3)
{(4, 1)}
>>> s3(5)
{(25, u + 5)}
>>> s3(None, 2)
{(t**2, t + 2)}
"""
def __init__(self, symbols_seq, parameters=None):
super().__init__()
if not is_sequence(symbols_seq):
raise ValueError("Symbols must be given as a sequence.")
self.symbols = tuple(symbols_seq)
if parameters is None:
self.parameters = symbols('%s1:%i' % ('t', len(self.symbols) + 1), integer=True)
else:
self.parameters = tuple(parameters)
def add(self, solution):
if len(solution) != len(self.symbols):
raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution)))
super().add(Tuple(*solution))
def update(self, *solutions):
for solution in solutions:
self.add(solution)
def dict_iterator(self):
for solution in ordered(self):
yield dict(zip(self.symbols, solution))
def subs(self, *args, **kwargs):
result = DiophantineSolutionSet(self.symbols, self.parameters)
for solution in self:
result.add(solution.subs(*args, **kwargs))
return result
def __call__(self, *args):
if len(args) > len(self.parameters):
raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args)))
return self.subs(zip(self.parameters, args))
class DiophantineEquationType:
"""
Internal representation of a particular diophantine equation type.
Parameters
==========
equation :
The diophantine equation that is being solved.
free_symbols : list (optional)
The symbols being solved for.
Attributes
==========
total_degree :
The maximum of the degrees of all terms in the equation
homogeneous :
Does the equation contain a term of degree 0
homogeneous_order :
Does the equation contain any coefficient that is in the symbols being solved for
dimension :
The number of symbols being solved for
"""
name = None # type: str
def __init__(self, equation, free_symbols=None):
self.equation = _sympify(equation).expand(force=True)
if free_symbols is not None:
self.free_symbols = free_symbols
else:
self.free_symbols = list(self.equation.free_symbols)
if not self.free_symbols:
raise ValueError('equation should have 1 or more free symbols')
self.free_symbols.sort(key=default_sort_key)
self.coeff = self.equation.as_coefficients_dict()
if not all(_is_int(c) for c in self.coeff.values()):
raise TypeError("Coefficients should be Integers")
self.total_degree = Poly(self.equation).total_degree()
self.homogeneous = 1 not in self.coeff
self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols))
self.dimension = len(self.free_symbols)
def matches(self):
"""
Determine whether the given equation can be matched to the particular equation type.
"""
return False
class Univariate(DiophantineEquationType):
name = 'univariate'
def matches(self):
return self.dimension == 1
class Linear(DiophantineEquationType):
name = 'linear'
def matches(self):
return self.total_degree == 1
class BinaryQuadratic(DiophantineEquationType):
name = 'binary_quadratic'
def matches(self):
return self.total_degree == 2 and self.dimension == 2
class InhomogeneousTernaryQuadratic(DiophantineEquationType):
name = 'inhomogeneous_ternary_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
return not self.homogeneous_order
class HomogeneousTernaryQuadraticNormal(DiophantineEquationType):
name = 'homogeneous_ternary_quadratic_normal'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
if not self.homogeneous_order:
return False
nonzero = [k for k in self.coeff if self.coeff[k]]
return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)
class HomogeneousTernaryQuadratic(DiophantineEquationType):
name = 'homogeneous_ternary_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
if not self.homogeneous_order:
return False
nonzero = [k for k in self.coeff if self.coeff[k]]
return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols))
class InhomogeneousGeneralQuadratic(DiophantineEquationType):
name = 'inhomogeneous_general_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return True
else:
# there may be Pow keys like x**2 or Mul keys like x*y
if any(k.is_Mul for k in self.coeff): # cross terms
return not self.homogeneous
return False
class HomogeneousGeneralQuadratic(DiophantineEquationType):
name = 'homogeneous_general_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
else:
# there may be Pow keys like x**2 or Mul keys like x*y
if any(k.is_Mul for k in self.coeff): # cross terms
return self.homogeneous
return False
class GeneralSumOfSquares(DiophantineEquationType):
name = 'general_sum_of_squares'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
if any(k.is_Mul for k in self.coeff):
return False
return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
class GeneralPythagorean(DiophantineEquationType):
name = 'general_pythagorean'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
if any(k.is_Mul for k in self.coeff):
return False
if all(self.coeff[k] == 1 for k in self.coeff if k != 1):
return False
if not all(is_square(abs(self.coeff[k])) for k in self.coeff):
return False
# all but one has the same sign
# e.g. 4*x**2 + y**2 - 4*z**2
return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2
class CubicThue(DiophantineEquationType):
name = 'cubic_thue'
def matches(self):
return self.total_degree == 3 and self.dimension == 2
class GeneralSumOfEvenPowers(DiophantineEquationType):
name = 'general_sum_of_even_powers'
def matches(self):
if not self.total_degree > 3:
return False
if self.total_degree % 2 != 0:
return False
if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1):
return False
return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
# these types are known (but not necessarily handled)
# note that order is important here (in the current solver state)
all_diop_classes = [
Linear,
Univariate,
BinaryQuadratic,
InhomogeneousTernaryQuadratic,
HomogeneousTernaryQuadraticNormal,
HomogeneousTernaryQuadratic,
InhomogeneousGeneralQuadratic,
HomogeneousGeneralQuadratic,
GeneralSumOfSquares,
GeneralPythagorean,
CubicThue,
GeneralSumOfEvenPowers,
]
diop_known = {diop_class.name for diop_class in all_diop_classes}
def _is_int(i):
try:
as_int(i)
return True
except ValueError:
pass
def _sorted_tuple(*i):
return tuple(sorted(i))
def _remove_gcd(*x):
try:
g = igcd(*x)
except ValueError:
fx = list(filter(None, x))
if len(fx) < 2:
return x
g = igcd(*[i.as_content_primitive()[0] for i in fx])
except TypeError:
raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)')
if g == 1:
return x
return tuple([i//g for i in x])
def _rational_pq(a, b):
# return `(numer, denom)` for a/b; sign in numer and gcd removed
return _remove_gcd(sign(b)*a, abs(b))
def _nint_or_floor(p, q):
# return nearest int to p/q; in case of tie return floor(p/q)
w, r = divmod(p, q)
if abs(r) <= abs(q)//2:
return w
return w + 1
def _odd(i):
return i % 2 != 0
def _even(i):
return i % 2 == 0
def diophantine(eq, param=symbols("t", integer=True), syms=None,
permute=False):
"""
Simplify the solution procedure of diophantine equation ``eq`` by
converting it into a product of terms which should equal zero.
Explanation
===========
For example, when solving, `x^2 - y^2 = 0` this is treated as
`(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved
independently and combined. Each term is solved by calling
``diop_solve()``. (Although it is possible to call ``diop_solve()``
directly, one must be careful to pass an equation in the correct
form and to interpret the output correctly; ``diophantine()`` is
the public-facing function to use in general.)
Output of ``diophantine()`` is a set of tuples. The elements of the
tuple are the solutions for each variable in the equation and
are arranged according to the alphabetic ordering of the variables.
e.g. For an equation with two variables, `a` and `b`, the first
element of the tuple is the solution for `a` and the second for `b`.
Usage
=====
``diophantine(eq, t, syms)``: Solve the diophantine
equation ``eq``.
``t`` is the optional parameter to be used by ``diop_solve()``.
``syms`` is an optional list of symbols which determines the
order of the elements in the returned tuple.
By default, only the base solution is returned. If ``permute`` is set to
True then permutations of the base solution and/or permutations of the
signs of the values will be returned when applicable.
Examples
========
>>> from sympy.solvers.diophantine import diophantine
>>> from sympy.abc import a, b
>>> eq = a**4 + b**4 - (2**4 + 3**4)
>>> diophantine(eq)
{(2, 3)}
>>> diophantine(eq, permute=True)
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, z
>>> diophantine(x**2 - y**2)
{(t_0, -t_0), (t_0, t_0)}
>>> diophantine(x*(2*x + 3*y - z))
{(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)}
>>> diophantine(x**2 + 3*x*y + 4*x)
{(0, n1), (3*t_0 - 4, -t_0)}
See Also
========
diop_solve()
sympy.utilities.iterables.permute_signs
sympy.utilities.iterables.signed_permutations
"""
from sympy.utilities.iterables import (
subsets, permute_signs, signed_permutations)
eq = _sympify(eq)
if isinstance(eq, Eq):
eq = eq.lhs - eq.rhs
try:
var = list(eq.expand(force=True).free_symbols)
var.sort(key=default_sort_key)
if syms:
if not is_sequence(syms):
raise TypeError(
'syms should be given as a sequence, e.g. a list')
syms = [i for i in syms if i in var]
if syms != var:
dict_sym_index = dict(zip(syms, range(len(syms))))
return {tuple([t[dict_sym_index[i]] for i in var])
for t in diophantine(eq, param, permute=permute)}
n, d = eq.as_numer_denom()
if n.is_number:
return set()
if not d.is_number:
dsol = diophantine(d)
good = diophantine(n) - dsol
return {s for s in good if _mexpand(d.subs(zip(var, s)))}
else:
eq = n
eq = factor_terms(eq)
assert not eq.is_number
eq = eq.as_independent(*var, as_Add=False)[1]
p = Poly(eq)
assert not any(g.is_number for g in p.gens)
eq = p.as_expr()
assert eq.is_polynomial()
except (GeneratorsNeeded, AssertionError):
raise TypeError(filldedent('''
Equation should be a polynomial with Rational coefficients.'''))
# permute only sign
do_permute_signs = False
# permute sign and values
do_permute_signs_var = False
# permute few signs
permute_few_signs = False
try:
# if we know that factoring should not be attempted, skip
# the factoring step
v, c, t = classify_diop(eq)
# check for permute sign
if permute:
len_var = len(v)
permute_signs_for = [
GeneralSumOfSquares.name,
GeneralSumOfEvenPowers.name]
permute_signs_check = [
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name,
BinaryQuadratic.name]
if t in permute_signs_for:
do_permute_signs_var = True
elif t in permute_signs_check:
# if all the variables in eq have even powers
# then do_permute_sign = True
if len_var == 3:
var_mul = list(subsets(v, 2))
# here var_mul is like [(x, y), (x, z), (y, z)]
xy_coeff = True
x_coeff = True
var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul)
# if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then
# `xy_coeff` => True and do_permute_sign => False.
# Means no permuted solution.
for v1_mul_v2 in var1_mul_var2:
try:
coeff = c[v1_mul_v2]
except KeyError:
coeff = 0
xy_coeff = bool(xy_coeff) and bool(coeff)
var_mul = list(subsets(v, 1))
# here var_mul is like [(x,), (y, )]
for v1 in var_mul:
try:
coeff = c[v1[0]]
except KeyError:
coeff = 0
x_coeff = bool(x_coeff) and bool(coeff)
if not any([xy_coeff, x_coeff]):
# means only x**2, y**2, z**2, const is present
do_permute_signs = True
elif not x_coeff:
permute_few_signs = True
elif len_var == 2:
var_mul = list(subsets(v, 2))
# here var_mul is like [(x, y)]
xy_coeff = True
x_coeff = True
var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul)
for v1_mul_v2 in var1_mul_var2:
try:
coeff = c[v1_mul_v2]
except KeyError:
coeff = 0
xy_coeff = bool(xy_coeff) and bool(coeff)
var_mul = list(subsets(v, 1))
# here var_mul is like [(x,), (y, )]
for v1 in var_mul:
try:
coeff = c[v1[0]]
except KeyError:
coeff = 0
x_coeff = bool(x_coeff) and bool(coeff)
if not any([xy_coeff, x_coeff]):
# means only x**2, y**2 and const is present
# so we can get more soln by permuting this soln.
do_permute_signs = True
elif not x_coeff:
# when coeff(x), coeff(y) is not present then signs of
# x, y can be permuted such that their sign are same
# as sign of x*y.
# e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val)
# 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val)
permute_few_signs = True
if t == 'general_sum_of_squares':
# trying to factor such expressions will sometimes hang
terms = [(eq, 1)]
else:
raise TypeError
except (TypeError, NotImplementedError):
fl = factor_list(eq)
if fl[0].is_Rational and fl[0] != 1:
return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)
terms = fl[1]
sols = set()
for term in terms:
base, _ = term
var_t, _, eq_type = classify_diop(base, _dict=False)
_, base = signsimp(base, evaluate=False).as_coeff_Mul()
solution = diop_solve(base, param)
if eq_type in [
Linear.name,
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name,
GeneralPythagorean.name]:
sols.add(merge_solution(var, var_t, solution))
elif eq_type in [
BinaryQuadratic.name,
GeneralSumOfSquares.name,
GeneralSumOfEvenPowers.name,
Univariate.name]:
for sol in solution:
sols.add(merge_solution(var, var_t, sol))
else:
raise NotImplementedError('unhandled type: %s' % eq_type)
# remove null merge results
if () in sols:
sols.remove(())
null = tuple([0]*len(var))
# if there is no solution, return trivial solution
if not sols and eq.subs(zip(var, null)).is_zero:
sols.add(null)
final_soln = set()
for sol in sols:
if all(_is_int(s) for s in sol):
if do_permute_signs:
permuted_sign = set(permute_signs(sol))
final_soln.update(permuted_sign)
elif permute_few_signs:
lst = list(permute_signs(sol))
lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst))
permuted_sign = set(lst)
final_soln.update(permuted_sign)
elif do_permute_signs_var:
permuted_sign_var = set(signed_permutations(sol))
final_soln.update(permuted_sign_var)
else:
final_soln.add(sol)
else:
final_soln.add(sol)
return final_soln
def merge_solution(var, var_t, solution):
"""
This is used to construct the full solution from the solutions of sub
equations.
Explanation
===========
For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`,
solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are
found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But
we should introduce a value for z when we output the solution for the
original equation. This function converts `(t, t)` into `(t, t, n_{1})`
where `n_{1}` is an integer parameter.
"""
sol = []
if None in solution:
return ()
solution = iter(solution)
params = numbered_symbols("n", integer=True, start=1)
for v in var:
if v in var_t:
sol.append(next(solution))
else:
sol.append(next(params))
for val, symb in zip(sol, var):
if check_assumptions(val, **symb.assumptions0) is False:
return tuple()
return tuple(sol)
def diop_solve(eq, param=symbols("t", integer=True)):
"""
Solves the diophantine equation ``eq``.
Explanation
===========
Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses
``classify_diop()`` to determine the type of the equation and calls
the appropriate solver function.
Use of ``diophantine()`` is recommended over other helper functions.
``diop_solve()`` can return either a set or a tuple depending on the
nature of the equation.
Usage
=====
``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t``
as a parameter if needed.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_solve
>>> from sympy.abc import x, y, z, w
>>> diop_solve(2*x + 3*y - 5)
(3*t_0 - 5, 5 - 2*t_0)
>>> diop_solve(4*x + 3*y - 4*z + 5)
(t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
>>> diop_solve(x + 3*y - 4*z + w - 6)
(t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)
>>> diop_solve(x**2 + y**2 - 5)
{(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}
See Also
========
diophantine()
"""
var, coeff, eq_type = classify_diop(eq, _dict=False)
if eq_type == Linear.name:
return diop_linear(eq, param)
elif eq_type == BinaryQuadratic.name:
return diop_quadratic(eq, param)
elif eq_type == HomogeneousTernaryQuadratic.name:
return diop_ternary_quadratic(eq, parameterize=True)
elif eq_type == HomogeneousTernaryQuadraticNormal.name:
return diop_ternary_quadratic_normal(eq, parameterize=True)
elif eq_type == GeneralPythagorean.name:
return diop_general_pythagorean(eq, param)
elif eq_type == Univariate.name:
return diop_univariate(eq)
elif eq_type == GeneralSumOfSquares.name:
return diop_general_sum_of_squares(eq, limit=S.Infinity)
elif eq_type == GeneralSumOfEvenPowers.name:
return diop_general_sum_of_even_powers(eq, limit=S.Infinity)
if eq_type is not None and eq_type not in diop_known:
raise ValueError(filldedent('''
Alhough this type of equation was identified, it is not yet
handled. It should, however, be listed in `diop_known` at the
top of this file. Developers should see comments at the end of
`classify_diop`.
''')) # pragma: no cover
else:
raise NotImplementedError(
'No solver has been written for %s.' % eq_type)
def classify_diop(eq, _dict=True):
# docstring supplied externally
matched = False
diop_type = None
for diop_class in all_diop_classes:
diop_type = diop_class(eq)
if diop_type.matches():
matched = True
break
if matched:
return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name
# new diop type instructions
# --------------------------
# if this error raises and the equation *can* be classified,
# * it should be identified in the if-block above
# * the type should be added to the diop_known
# if a solver can be written for it,
# * a dedicated handler should be written (e.g. diop_linear)
# * it should be passed to that handler in diop_solve
raise NotImplementedError(filldedent('''
This equation is not yet recognized or else has not been
simplified sufficiently to put it in a form recognized by
diop_classify().'''))
classify_diop.func_doc = ( # type: ignore
'''
Helper routine used by diop_solve() to find information about ``eq``.
Explanation
===========
Returns a tuple containing the type of the diophantine equation
along with the variables (free symbols) and their coefficients.
Variables are returned as a list and coefficients are returned
as a dict with the key being the respective term and the constant
term is keyed to 1. The type is one of the following:
* %s
Usage
=====
``classify_diop(eq)``: Return variables, coefficients and type of the
``eq``.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``_dict`` is for internal use: when True (default) a dict is returned,
otherwise a defaultdict which supplies 0 for missing keys is returned.
Examples
========
>>> from sympy.solvers.diophantine import classify_diop
>>> from sympy.abc import x, y, z, w, t
>>> classify_diop(4*x + 6*y - 4)
([x, y], {1: -4, x: 4, y: 6}, 'linear')
>>> classify_diop(x + 3*y -4*z + 5)
([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
>>> classify_diop(x**2 + y**2 - x*y + x + 5)
([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
''' % ('\n * '.join(sorted(diop_known))))
def diop_linear(eq, param=symbols("t", integer=True)):
"""
Solves linear diophantine equations.
A linear diophantine equation is an equation of the form `a_{1}x_{1} +
a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
Usage
=====
``diop_linear(eq)``: Returns a tuple containing solutions to the
diophantine equation ``eq``. Values in the tuple is arranged in the same
order as the sorted variables.
Details
=======
``eq`` is a linear diophantine equation which is assumed to be zero.
``param`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_linear
>>> from sympy.abc import x, y, z
>>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0
(3*t_0 - 5, 2*t_0 - 5)
Here x = -3*t_0 - 5 and y = -2*t_0 - 5
>>> diop_linear(2*x - 3*y - 4*z -3)
(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)
See Also
========
diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(),
diop_general_sum_of_squares()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Linear.name:
result = _diop_linear(var, coeff, param)
if param is None:
result = result(*[0]*len(result.parameters))
if len(result) > 0:
return list(result)[0]
else:
return tuple([None] * len(result.parameters))
def _diop_linear(var, coeff, param):
"""
Solves diophantine equations of the form:
a_0*x_0 + a_1*x_1 + ... + a_n*x_n == c
Note that no solution exists if gcd(a_0, ..., a_n) doesn't divide c.
"""
if 1 in coeff:
# negate coeff[] because input is of the form: ax + by + c == 0
# but is used as: ax + by == -c
c = -coeff[1]
else:
c = 0
# Some solutions will have multiple free variables in their solutions.
if param is None:
params = [symbols('t')]*len(var)
else:
temp = str(param) + "_%i"
params = [symbols(temp % i, integer=True) for i in range(len(var))]
result = DiophantineSolutionSet(var, params)
if len(var) == 1:
q, r = divmod(c, coeff[var[0]])
if not r:
result.add((q,))
return result
else:
return result
'''
base_solution_linear() can solve diophantine equations of the form:
a*x + b*y == c
We break down multivariate linear diophantine equations into a
series of bivariate linear diophantine equations which can then
be solved individually by base_solution_linear().
Consider the following:
a_0*x_0 + a_1*x_1 + a_2*x_2 == c
which can be re-written as:
a_0*x_0 + g_0*y_0 == c
where
g_0 == gcd(a_1, a_2)
and
y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0
This leaves us with two binary linear diophantine equations.
For the first equation:
a == a_0
b == g_0
c == c
For the second:
a == a_1/g_0
b == a_2/g_0
c == the solution we find for y_0 in the first equation.
The arrays A and B are the arrays of integers used for
'a' and 'b' in each of the n-1 bivariate equations we solve.
'''
A = [coeff[v] for v in var]
B = []
if len(var) > 2:
B.append(igcd(A[-2], A[-1]))
A[-2] = A[-2] // B[0]
A[-1] = A[-1] // B[0]
for i in range(len(A) - 3, 0, -1):
gcd = igcd(B[0], A[i])
B[0] = B[0] // gcd
A[i] = A[i] // gcd
B.insert(0, gcd)
B.append(A[-1])
'''
Consider the trivariate linear equation:
4*x_0 + 6*x_1 + 3*x_2 == 2
This can be re-written as:
4*x_0 + 3*y_0 == 2
where
y_0 == 2*x_1 + x_2
(Note that gcd(3, 6) == 3)
The complete integral solution to this equation is:
x_0 == 2 + 3*t_0
y_0 == -2 - 4*t_0
where 't_0' is any integer.
Now that we have a solution for 'x_0', find 'x_1' and 'x_2':
2*x_1 + x_2 == -2 - 4*t_0
We can then solve for '-2' and '-4' independently,
and combine the results:
2*x_1a + x_2a == -2
x_1a == 0 + t_0
x_2a == -2 - 2*t_0
2*x_1b + x_2b == -4*t_0
x_1b == 0*t_0 + t_1
x_2b == -4*t_0 - 2*t_1
==>
x_1 == t_0 + t_1
x_2 == -2 - 6*t_0 - 2*t_1
where 't_0' and 't_1' are any integers.
Note that:
4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2
for any integral values of 't_0', 't_1'; as required.
This method is generalised for many variables, below.
'''
solutions = []
for i in range(len(B)):
tot_x, tot_y = [], []
for j, arg in enumerate(Add.make_args(c)):
if arg.is_Integer:
# example: 5 -> k = 5
k, p = arg, S.One
pnew = params[0]
else: # arg is a Mul or Symbol
# example: 3*t_1 -> k = 3
# example: t_0 -> k = 1
k, p = arg.as_coeff_Mul()
pnew = params[params.index(p) + 1]
sol = sol_x, sol_y = base_solution_linear(k, A[i], B[i], pnew)
if p is S.One:
if None in sol:
return result
else:
# convert a + b*pnew -> a*p + b*pnew
if isinstance(sol_x, Add):
sol_x = sol_x.args[0]*p + sol_x.args[1]
if isinstance(sol_y, Add):
sol_y = sol_y.args[0]*p + sol_y.args[1]
tot_x.append(sol_x)
tot_y.append(sol_y)
solutions.append(Add(*tot_x))
c = Add(*tot_y)
solutions.append(c)
if param is None:
# just keep the additive constant (i.e. replace t with 0)
solutions = [i.as_coeff_Add()[0] for i in solutions]
result.add(solutions)
return result
def base_solution_linear(c, a, b, t=None):
"""
Return the base solution for the linear equation, `ax + by = c`.
Explanation
===========
Used by ``diop_linear()`` to find the base solution of a linear
Diophantine equation. If ``t`` is given then the parametrized solution is
returned.
Usage
=====
``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
in `ax + by = c` and ``t`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import base_solution_linear
>>> from sympy.abc import t
>>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
(-5, 5)
>>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
(0, 0)
>>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
(3*t - 5, 5 - 2*t)
>>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
(7*t, -5*t)
"""
a, b, c = _remove_gcd(a, b, c)
if c == 0:
if t is not None:
if b < 0:
t = -t
return (b*t , -a*t)
else:
return (0, 0)
else:
x0, y0, d = igcdex(abs(a), abs(b))
x0 *= sign(a)
y0 *= sign(b)
if divisible(c, d):
if t is not None:
if b < 0:
t = -t
return (c*x0 + b*t, c*y0 - a*t)
else:
return (c*x0, c*y0)
else:
return (None, None)
def diop_univariate(eq):
"""
Solves a univariate diophantine equations.
Explanation
===========
A univariate diophantine equation is an equation of the form
`a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x` is an integer variable.
Usage
=====
``diop_univariate(eq)``: Returns a set containing solutions to the
diophantine equation ``eq``.
Details
=======
``eq`` is a univariate diophantine equation which is assumed to be zero.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_univariate
>>> from sympy.abc import x
>>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0
{(2,), (3,)}
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Univariate.name:
return {(int(i),) for i in solveset_real(
eq, var[0]).intersect(S.Integers)}
def divisible(a, b):
"""
Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
"""
return not a % b
def diop_quadratic(eq, param=symbols("t", integer=True)):
"""
Solves quadratic diophantine equations.
i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
set containing the tuples `(x, y)` which contains the solutions. If there
are no solutions then `(None, None)` is returned.
Usage
=====
``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine
equation. ``param`` is used to indicate the parameter to be used in the
solution.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``param`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, t
>>> from sympy.solvers.diophantine.diophantine import diop_quadratic
>>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
{(-1, -1)}
References
==========
.. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
Available: http://www.alpertron.com.ar/METHODS.HTM
.. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: http://www.jpr2718.org/ax2p.pdf
See Also
========
diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(),
diop_general_pythagorean()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return set(_diop_quadratic(var, coeff, param))
def _diop_quadratic(var, coeff, t):
u = Symbol('u', integer=True)
x, y = var
A = coeff[x**2]
B = coeff[x*y]
C = coeff[y**2]
D = coeff[x]
E = coeff[y]
F = coeff[S.One]
A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)]
# (1) Simple-Hyperbolic case: A = C = 0, B != 0
# In this case equation can be converted to (Bx + E)(By + D) = DE - BF
# We consider two cases; DE - BF = 0 and DE - BF != 0
# More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb
result = DiophantineSolutionSet(var, [t, u])
discr = B**2 - 4*A*C
if A == 0 and C == 0 and B != 0:
if D*E - B*F == 0:
q, r = divmod(E, B)
if not r:
result.add((-q, t))
q, r = divmod(D, B)
if not r:
result.add((t, -q))
else:
div = divisors(D*E - B*F)
div = div + [-term for term in div]
for d in div:
x0, r = divmod(d - E, B)
if not r:
q, r = divmod(D*E - B*F, d)
if not r:
y0, r = divmod(q - D, B)
if not r:
result.add((x0, y0))
# (2) Parabolic case: B**2 - 4*A*C = 0
# There are two subcases to be considered in this case.
# sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
# More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol
elif discr == 0:
if A == 0:
s = _diop_quadratic([y, x], coeff, t)
for soln in s:
result.add((soln[1], soln[0]))
else:
g = sign(A)*igcd(A, C)
a = A // g
c = C // g
e = sign(B/A)
sqa = isqrt(a)
sqc = isqrt(c)
_c = e*sqc*D - sqa*E
if not _c:
z = symbols("z", real=True)
eq = sqa*g*z**2 + D*z + sqa*F
roots = solveset_real(eq, z).intersect(S.Integers)
for root in roots:
ans = diop_solve(sqa*x + e*sqc*y - root)
result.add((ans[0], ans[1]))
elif _is_int(c):
solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t\
- (e*sqc*g*u**2 + E*u + e*sqc*F) // _c
solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \
+ (sqa*g*u**2 + D*u + sqa*F) // _c
for z0 in range(0, abs(_c)):
# Check if the coefficients of y and x obtained are integers or not
if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and
divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):
result.add((solve_x(z0), solve_y(z0)))
# (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper
# by John P. Robertson.
# http://www.jpr2718.org/ax2p.pdf
elif is_square(discr):
if A != 0:
r = sqrt(discr)
u, v = symbols("u, v", integer=True)
eq = _mexpand(
4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) +
2*A*4*A*E*(u - v) + 4*A*r*4*A*F)
solution = diop_solve(eq, t)
for s0, t0 in solution:
num = B*t0 + r*s0 + r*t0 - B*s0
x_0 = S(num)/(4*A*r)
y_0 = S(s0 - t0)/(2*r)
if isinstance(s0, Symbol) or isinstance(t0, Symbol):
if check_param(x_0, y_0, 4*A*r, t) != (None, None):
ans = check_param(x_0, y_0, 4*A*r, t)
result.add((ans[0], ans[1]))
elif x_0.is_Integer and y_0.is_Integer:
if is_solution_quad(var, coeff, x_0, y_0):
result.add((x_0, y_0))
else:
s = _diop_quadratic(var[::-1], coeff, t) # Interchange x and y
while s:
result.add(s.pop()[::-1]) # and solution <--------+
# (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0
else:
P, Q = _transformation_to_DN(var, coeff)
D, N = _find_DN(var, coeff)
solns_pell = diop_DN(D, N)
if D < 0:
for x0, y0 in solns_pell:
for x in [-x0, x0]:
for y in [-y0, y0]:
s = P*Matrix([x, y]) + Q
try:
result.add([as_int(_) for _ in s])
except ValueError:
pass
else:
# In this case equation can be transformed into a Pell equation
solns_pell = set(solns_pell)
for X, Y in list(solns_pell):
solns_pell.add((-X, -Y))
a = diop_DN(D, 1)
T = a[0][0]
U = a[0][1]
if all(_is_int(_) for _ in P[:4] + Q[:2]):
for r, s in solns_pell:
_a = (r + s*sqrt(D))*(T + U*sqrt(D))**t
_b = (r - s*sqrt(D))*(T - U*sqrt(D))**t
x_n = _mexpand(S(_a + _b)/2)
y_n = _mexpand(S(_a - _b)/(2*sqrt(D)))
s = P*Matrix([x_n, y_n]) + Q
result.add(s)
else:
L = ilcm(*[_.q for _ in P[:4] + Q[:2]])
k = 1
T_k = T
U_k = U
while (T_k - 1) % L != 0 or U_k % L != 0:
T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
k += 1
for X, Y in solns_pell:
for i in range(k):
if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q):
_a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t
_b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t
Xt = S(_a + _b)/2
Yt = S(_a - _b)/(2*sqrt(D))
s = P*Matrix([Xt, Yt]) + Q
result.add(s)
X, Y = X*T + D*U*Y, X*U + Y*T
return result
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()])
return _mexpand(eq) == 0
def diop_DN(D, N, t=symbols("t", integer=True)):
"""
Solves the equation `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the case `D > 0, D` is not a perfect square,
which is the same as the generalized Pell equation. The LMM
algorithm [1]_ is used to solve this equation.
Returns one solution tuple, (`x, y)` for each class of the solutions.
Other solutions of the class can be constructed according to the
values of ``D`` and ``N``.
Usage
=====
``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and
``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_DN
>>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
[(3, 1), (393, 109), (36, 10)]
The output can be interpreted as follows: There are three fundamental
solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
that `x = 3` and `y = 1`.
>>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
[(49299, 1570)]
See Also
========
find_DN(), diop_bf_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
http://www.jpr2718.org/pell.pdf
"""
if D < 0:
if N == 0:
return [(0, 0)]
elif N < 0:
return []
elif N > 0:
sol = []
for d in divisors(square_factor(N)):
sols = cornacchia(1, -D, N // d**2)
if sols:
for x, y in sols:
sol.append((d*x, d*y))
if D == -1:
sol.append((d*y, d*x))
return sol
elif D == 0:
if N < 0:
return []
if N == 0:
return [(0, t)]
sN, _exact = integer_nthroot(N, 2)
if _exact:
return [(sN, t)]
else:
return []
else: # D > 0
sD, _exact = integer_nthroot(D, 2)
if _exact:
if N == 0:
return [(sD*t, t)]
else:
sol = []
for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1):
try:
sq, _exact = integer_nthroot(D*y**2 + N, 2)
except ValueError:
_exact = False
if _exact:
sol.append((sq, y))
return sol
elif 1 < N**2 < D:
# It is much faster to call `_special_diop_DN`.
return _special_diop_DN(D, N)
else:
if N == 0:
return [(0, 0)]
elif abs(N) == 1:
pqa = PQa(0, 1, D)
j = 0
G = []
B = []
for i in pqa:
a = i[2]
G.append(i[5])
B.append(i[4])
if j != 0 and a == 2*sD:
break
j = j + 1
if _odd(j):
if N == -1:
x = G[j - 1]
y = B[j - 1]
else:
count = j
while count < 2*j - 1:
i = next(pqa)
G.append(i[5])
B.append(i[4])
count += 1
x = G[count]
y = B[count]
else:
if N == 1:
x = G[j - 1]
y = B[j - 1]
else:
return []
return [(x, y)]
else:
fs = []
sol = []
div = divisors(N)
for d in div:
if divisible(N, d**2):
fs.append(d)
for f in fs:
m = N // f**2
zs = sqrt_mod(D, abs(m), all_roots=True)
zs = [i for i in zs if i <= abs(m) // 2 ]
if abs(m) != 2:
zs = zs + [-i for i in zs if i] # omit dupl 0
for z in zs:
pqa = PQa(z, abs(m), D)
j = 0
G = []
B = []
for i in pqa:
G.append(i[5])
B.append(i[4])
if j != 0 and abs(i[1]) == 1:
r = G[j-1]
s = B[j-1]
if r**2 - D*s**2 == m:
sol.append((f*r, f*s))
elif diop_DN(D, -1) != []:
a = diop_DN(D, -1)
sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0])))
break
j = j + 1
if j == length(z, abs(m), D):
break
return sol
def _special_diop_DN(D, N):
"""
Solves the equation `x^2 - Dy^2 = N` for the special case where
`1 < N**2 < D` and `D` is not a perfect square.
It is better to call `diop_DN` rather than this function, as
the former checks the condition `1 < N**2 < D`, and calls the latter only
if appropriate.
Usage
=====
WARNING: Internal method. Do not call directly!
``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import _special_diop_DN
>>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3
[(7, 2), (137, 38)]
The output can be interpreted as follows: There are two fundamental
solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and
(137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means
that `x = 7` and `y = 2`.
>>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20
[(445, 9), (17625560, 356454), (698095554475, 14118073569)]
See Also
========
diop_DN()
References
==========
.. [1] Section 4.4.4 of the following book:
Quadratic Diophantine Equations, T. Andreescu and D. Andrica,
Springer, 2015.
"""
# The following assertion was removed for efficiency, with the understanding
# that this method is not called directly. The parent method, `diop_DN`
# is responsible for performing the appropriate checks.
#
# assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1])
sqrt_D = sqrt(D)
F = [(N, 1)]
f = 2
while True:
f2 = f**2
if f2 > abs(N):
break
n, r = divmod(N, f2)
if r == 0:
F.append((n, f))
f += 1
P = 0
Q = 1
G0, G1 = 0, 1
B0, B1 = 1, 0
solutions = []
i = 0
while True:
a = floor((P + sqrt_D) / Q)
P = a*Q - P
Q = (D - P**2) // Q
G2 = a*G1 + G0
B2 = a*B1 + B0
for n, f in F:
if G2**2 - D*B2**2 == n:
solutions.append((f*G2, f*B2))
i += 1
if Q == 1 and i % 2 == 0:
break
G0, G1 = G1, G2
B0, B1 = B1, B2
return solutions
def cornacchia(a, b, m):
r"""
Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.
Explanation
===========
Uses the algorithm due to Cornacchia. The method only finds primitive
solutions, i.e. ones with `\gcd(x, y) = 1`. So this method can't be used to
find the solutions of `x^2 + y^2 = 20` since the only solution to former is
`(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the
solutions with `x \leq y` are found. For more details, see the References.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import cornacchia
>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
{(2, 3), (4, 1)}
>>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
{(4, 3)}
References
===========
.. [1] A. Nitaj, "L'algorithme de Cornacchia"
.. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's
method, [online], Available:
http://www.numbertheory.org/php/cornacchia.html
See Also
========
sympy.utilities.iterables.signed_permutations
"""
sols = set()
a1 = igcdex(a, m)[0]
v = sqrt_mod(-b*a1, m, all_roots=True)
if not v:
return None
for t in v:
if t < m // 2:
continue
u, r = t, m
while True:
u, r = r, u % r
if a*r**2 < m:
break
m1 = m - a*r**2
if m1 % b == 0:
m1 = m1 // b
s, _exact = integer_nthroot(m1, 2)
if _exact:
if a == b and r < s:
r, s = s, r
sols.add((int(r), int(s)))
return sols
def PQa(P_0, Q_0, D):
r"""
Returns useful information needed to solve the Pell equation.
Explanation
===========
There are six sequences of integers defined related to the continued
fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`},
{`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns
these values as a 6-tuple in the same order as mentioned above. Refer [1]_
for more detailed information.
Usage
=====
``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding
to `P_{0}`, `Q_{0}` and `D` in the continued fraction
`\\frac{P_{0} + \sqrt{D}}{Q_{0}}`.
Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import PQa
>>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
>>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
(13, 4, 3, 3, 1, -1)
>>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
(-1, 1, 1, 4, 1, 3)
References
==========
.. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P.
Robertson, July 31, 2004, Pages 4 - 8. http://www.jpr2718.org/pell.pdf
"""
A_i_2 = B_i_1 = 0
A_i_1 = B_i_2 = 1
G_i_2 = -P_0
G_i_1 = Q_0
P_i = P_0
Q_i = Q_0
while True:
a_i = floor((P_i + sqrt(D))/Q_i)
A_i = a_i*A_i_1 + A_i_2
B_i = a_i*B_i_1 + B_i_2
G_i = a_i*G_i_1 + G_i_2
yield P_i, Q_i, a_i, A_i, B_i, G_i
A_i_1, A_i_2 = A_i, A_i_1
B_i_1, B_i_2 = B_i, B_i_1
G_i_1, G_i_2 = G_i, G_i_1
P_i = a_i*Q_i - P_i
Q_i = (D - P_i**2)/Q_i
def diop_bf_DN(D, N, t=symbols("t", integer=True)):
r"""
Uses brute force to solve the equation, `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the generalized Pell equation which is the case when
`D > 0, D` is not a perfect square. For more information on the case refer
[1]_. Let `(t, u)` be the minimal positive solution of the equation
`x^2 - Dy^2 = 1`. Then this method requires
`\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small.
Usage
=====
``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in
`x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_bf_DN
>>> diop_bf_DN(13, -4)
[(3, 1), (-3, 1), (36, 10)]
>>> diop_bf_DN(986, 1)
[(49299, 1570)]
See Also
========
diop_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 15. http://www.jpr2718.org/pell.pdf
"""
D = as_int(D)
N = as_int(N)
sol = []
a = diop_DN(D, 1)
u = a[0][0]
if abs(N) == 1:
return diop_DN(D, N)
elif N > 1:
L1 = 0
L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1
elif N < -1:
L1, _exact = integer_nthroot(-int(N/D), 2)
if not _exact:
L1 += 1
L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1
else: # N = 0
if D < 0:
return [(0, 0)]
elif D == 0:
return [(0, t)]
else:
sD, _exact = integer_nthroot(D, 2)
if _exact:
return [(sD*t, t), (-sD*t, t)]
else:
return [(0, 0)]
for y in range(L1, L2):
try:
x, _exact = integer_nthroot(N + D*y**2, 2)
except ValueError:
_exact = False
if _exact:
sol.append((x, y))
if not equivalent(x, y, -x, y, D, N):
sol.append((-x, y))
return sol
def equivalent(u, v, r, s, D, N):
"""
Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N`
belongs to the same equivalence class and False otherwise.
Explanation
===========
Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same
equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by
`N`. See reference [1]_. No test is performed to test whether `(u, v)` and
`(r, s)` are actually solutions to the equation. User should take care of
this.
Usage
=====
``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions
of the equation `x^2 - Dy^2 = N` and all parameters involved are integers.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import equivalent
>>> equivalent(18, 5, -18, -5, 13, -1)
True
>>> equivalent(3, 1, -18, 393, 109, -4)
False
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 12. http://www.jpr2718.org/pell.pdf
"""
return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N)
def length(P, Q, D):
r"""
Returns the (length of aperiodic part + length of periodic part) of
continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`.
It is important to remember that this does NOT return the length of the
periodic part but the sum of the lengths of the two parts as mentioned
above.
Usage
=====
``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to
the continued fraction `\\frac{P + \sqrt{D}}{Q}`.
Details
=======
``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction,
`\\frac{P + \sqrt{D}}{Q}`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import length
>>> length(-2 , 4, 5) # (-2 + sqrt(5))/4
3
>>> length(-5, 4, 17) # (-5 + sqrt(17))/4
4
See Also
========
sympy.ntheory.continued_fraction.continued_fraction_periodic
"""
from sympy.ntheory.continued_fraction import continued_fraction_periodic
v = continued_fraction_periodic(P, Q, D)
if type(v[-1]) is list:
rpt = len(v[-1])
nonrpt = len(v) - 1
else:
rpt = 0
nonrpt = len(v)
return rpt + nonrpt
def transformation_to_DN(eq):
"""
This function transforms general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`
to more easy to deal with `X^2 - DY^2 = N` form.
Explanation
===========
This is used to solve the general quadratic equation by transforming it to
the latter form. Refer [1]_ for more detailed information on the
transformation. This function returns a tuple (A, B) where A is a 2 X 2
matrix and B is a 2 X 1 matrix such that,
Transpose([x y]) = A * Transpose([X Y]) + B
Usage
=====
``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be
transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import transformation_to_DN
>>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
>>> A
Matrix([
[1/26, 3/26],
[ 0, 1/13]])
>>> B
Matrix([
[-6/13],
[-4/13]])
A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B.
Substituting these values for `x` and `y` and a bit of simplifying work
will give an equation of the form `x^2 - Dy^2 = N`.
>>> from sympy.abc import X, Y
>>> from sympy import Matrix, simplify
>>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
>>> u
X/26 + 3*Y/26 - 6/13
>>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
>>> v
Y/13 - 4/13
Next we will substitute these formulas for `x` and `y` and do
``simplify()``.
>>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v))))
>>> eq
X**2/676 - Y**2/52 + 17/13
By multiplying the denominator appropriately, we can get a Pell equation
in the standard form.
>>> eq * 676
X**2 - 13*Y**2 + 884
If only the final equation is needed, ``find_DN()`` can be used.
See Also
========
find_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _transformation_to_DN(var, coeff)
def _transformation_to_DN(var, coeff):
x, y = var
a = coeff[x**2]
b = coeff[x*y]
c = coeff[y**2]
d = coeff[x]
e = coeff[y]
f = coeff[1]
a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)]
X, Y = symbols("X, Y", integer=True)
if b:
B, C = _rational_pq(2*a, b)
A, T = _rational_pq(a, B**2)
# eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B
coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0
else:
if d:
B, C = _rational_pq(2*a, d)
A, T = _rational_pq(a, B**2)
# eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2
coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0])
else:
if e:
B, C = _rational_pq(2*c, e)
A, T = _rational_pq(c, B**2)
# eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2
coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B])
else:
# TODO: pre-simplification: Not necessary but may simplify
# the equation.
return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0])
def find_DN(eq):
"""
This function returns a tuple, `(D, N)` of the simplified form,
`x^2 - Dy^2 = N`, corresponding to the general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`.
Solving the general quadratic is then equivalent to solving the equation
`X^2 - DY^2 = N` and transforming the solutions by using the transformation
matrices returned by ``transformation_to_DN()``.
Usage
=====
``find_DN(eq)``: where ``eq`` is the quadratic to be transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import find_DN
>>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
(13, -884)
Interpretation of the output is that we get `X^2 -13Y^2 = -884` after
transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned
by ``transformation_to_DN()``.
See Also
========
transformation_to_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _find_DN(var, coeff)
def _find_DN(var, coeff):
x, y = var
X, Y = symbols("X, Y", integer=True)
A, B = _transformation_to_DN(var, coeff)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1]
simplified = _mexpand(eq.subs(zip((x, y), (u, v))))
coeff = simplified.as_coefficients_dict()
return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2]
def check_param(x, y, a, t):
"""
If there is a number modulo ``a`` such that ``x`` and ``y`` are both
integers, then return a parametric representation for ``x`` and ``y``
else return (None, None).
Here ``x`` and ``y`` are functions of ``t``.
"""
from sympy.simplify.simplify import clear_coefficients
if x.is_number and not x.is_Integer:
return (None, None)
if y.is_number and not y.is_Integer:
return (None, None)
m, n = symbols("m, n", integer=True)
c, p = (m*x + n*y).as_content_primitive()
if a % c.q:
return (None, None)
# clear_coefficients(mx + b, R)[1] -> (R - b)/m
eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1]
junk, eq = eq.as_content_primitive()
return diop_solve(eq, t)
def diop_ternary_quadratic(eq, parameterize=False):
"""
Solves the general quadratic ternary form,
`ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Returns a tuple `(x, y, z)` which is a base solution for the above
equation. If there are no solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution
to ``eq``.
Details
=======
``eq`` should be an homogeneous expression of degree two in three variables
and it is assumed to be zero.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic
>>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
(28, 45, 105)
>>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
(9, 1, 5)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
sol = _diop_ternary_quadratic(var, coeff)
if len(sol) > 0:
x_0, y_0, z_0 = list(sol)[0]
else:
x_0, y_0, z_0 = None, None, None
if parameterize:
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
return x_0, y_0, z_0
def _diop_ternary_quadratic(_var, coeff):
x, y, z = _var
var = [x, y, z]
# Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the
# coefficients A, B, C are non-zero.
# There are infinitely many solutions for the equation.
# Ex: (0, 0, t), (0, t, 0), (t, 0, 0)
# Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather
# unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by
# using methods for binary quadratic diophantine equations. Let's select the
# solution which minimizes |x| + |z|
result = DiophantineSolutionSet(var)
def unpack_sol(sol):
if len(sol) > 0:
return list(sol)[0]
return None, None, None
if not any(coeff[i**2] for i in var):
if coeff[x*z]:
sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z)
s = sols.pop()
min_sum = abs(s[0]) + abs(s[1])
for r in sols:
m = abs(r[0]) + abs(r[1])
if m < min_sum:
s = r
min_sum = m
result.add(_remove_gcd(s[0], -coeff[x*z], s[1]))
return result
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
if x_0 is not None:
result.add((x_0, y_0, z_0))
return result
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
if coeff[x*y] or coeff[x*z]:
# Apply the transformation x --> X - (B*y + C*z)/(2*A)
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff))
if x_0 is None:
return result
p, q = _rational_pq(B*y_0 + C*z_0, 2*A)
x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q
elif coeff[z*y] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
A = coeff[x**2]
E = coeff[y*z]
b, a = _rational_pq(-E, A)
x_0, y_0, z_0 = b, a, b
else:
# Ax**2 + E*y*z + F*z**2 = 0
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
# Ax**2 + D*y**2 + F*z**2 = 0, C may be zero
x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff))
if x_0 is None:
return result
result.add(_remove_gcd(x_0, y_0, z_0))
return result
def transformation_to_normal(eq):
"""
Returns the transformation Matrix that converts a general ternary
quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`)
to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is
not used in solving ternary quadratics; it is only implemented for
the sake of completeness.
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
return _transformation_to_normal(var, coeff)
def _transformation_to_normal(var, coeff):
_var = list(var) # copy
x, y, z = var
if not any(coeff[i**2] for i in var):
# https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065
a = coeff[x*y]
b = coeff[y*z]
c = coeff[x*z]
swap = False
if not a: # b can't be 0 or else there aren't 3 vars
swap = True
a, b = b, a
T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1)))
if swap:
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
# Apply the transformation x --> X - (B*Y + C*Z)/(2*A)
if coeff[x*y] != 0 or coeff[x*z] != 0:
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
T_0 = _transformation_to_normal(_var, _coeff)
return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0
elif coeff[y*z] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
# Apply transformation y -> Y + Z ans z -> Y - Z
return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1])
else:
# Ax**2 + E*y*z + F*z**2 = 0
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
else:
return Matrix.eye(3)
def parametrize_ternary_quadratic(eq):
"""
Returns the parametrized general solution for the ternary quadratic
equation ``eq`` which has the form
`ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Examples
========
>>> from sympy import Tuple, ordered
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic
The parametrized solution may be returned with three parameters:
>>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2)
(p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)
There might also be only two parameters:
>>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2)
(2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2)
Notes
=====
Consider ``p`` and ``q`` in the previous 2-parameter
solution and observe that more than one solution can be represented
by a given pair of parameters. If `p` and ``q`` are not coprime, this is
trivially true since the common factor will also be a common factor of the
solution values. But it may also be true even when ``p`` and
``q`` are coprime:
>>> sol = Tuple(*_)
>>> p, q = ordered(sol.free_symbols)
>>> sol.subs([(p, 3), (q, 2)])
(6, 12, 12)
>>> sol.subs([(q, 1), (p, 1)])
(-1, 2, 2)
>>> sol.subs([(q, 0), (p, 1)])
(2, -4, 4)
>>> sol.subs([(q, 1), (p, 0)])
(-3, -6, 6)
Except for sign and a common factor, these are equivalent to
the solution of (1, 2, 2).
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University
Press, Cambridge, 1998.
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0]
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
def _parametrize_ternary_quadratic(solution, _var, coeff):
# called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0
assert 1 not in coeff
x_0, y_0, z_0 = solution
v = list(_var) # copy
if x_0 is None:
return (None, None, None)
if solution.count(0) >= 2:
# if there are 2 zeros the equation reduces
# to k*X**2 == 0 where X is x, y, or z so X must
# be zero, too. So there is only the trivial
# solution.
return (None, None, None)
if x_0 == 0:
v[0], v[1] = v[1], v[0]
y_p, x_p, z_p = _parametrize_ternary_quadratic(
(y_0, x_0, z_0), v, coeff)
return x_p, y_p, z_p
x, y, z = v
r, p, q = symbols("r, p, q", integer=True)
eq = sum(k*v for k, v in coeff.items())
eq_1 = _mexpand(eq.subs(zip(
(x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q))))
A, B = eq_1.as_independent(r, as_Add=True)
x = A*x_0
y = (A*y_0 - _mexpand(B/r*p))
z = (A*z_0 - _mexpand(B/r*q))
return _remove_gcd(x, y, z)
def diop_ternary_quadratic_normal(eq, parameterize=False):
"""
Solves the quadratic ternary diophantine equation,
`ax^2 + by^2 + cz^2 = 0`.
Explanation
===========
Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the
equation will be a quadratic binary or univariate equation. If solvable,
returns a tuple `(x, y, z)` that satisfies the given equation. If the
equation does not have integer solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form
`ax^2 + by^2 + cz^2 = 0`.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal
>>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2)
(4, 9, 1)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == HomogeneousTernaryQuadraticNormal.name:
sol = _diop_ternary_quadratic_normal(var, coeff)
if len(sol) > 0:
x_0, y_0, z_0 = list(sol)[0]
else:
x_0, y_0, z_0 = None, None, None
if parameterize:
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
return x_0, y_0, z_0
def _diop_ternary_quadratic_normal(var, coeff):
x, y, z = var
a = coeff[x**2]
b = coeff[y**2]
c = coeff[z**2]
try:
assert len([k for k in coeff if coeff[k]]) == 3
assert all(coeff[i**2] for i in var)
except AssertionError:
raise ValueError(filldedent('''
coeff dict is not consistent with assumption of this routine:
coefficients should be those of an expression in the form
a*x**2 + b*y**2 + c*z**2 where a*b*c != 0.'''))
(sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \
sqf_normal(a, b, c, steps=True)
A = -a_2*c_2
B = -b_2*c_2
result = DiophantineSolutionSet(var)
# If following two conditions are satisfied then there are no solutions
if A < 0 and B < 0:
return result
if (
sqrt_mod(-b_2*c_2, a_2) is None or
sqrt_mod(-c_2*a_2, b_2) is None or
sqrt_mod(-a_2*b_2, c_2) is None):
return result
z_0, x_0, y_0 = descent(A, B)
z_0, q = _rational_pq(z_0, abs(c_2))
x_0 *= q
y_0 *= q
x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0)
# Holzer reduction
if sign(a) == sign(b):
x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2))
elif sign(a) == sign(c):
x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2))
else:
y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2))
x_0 = reconstruct(b_1, c_1, x_0)
y_0 = reconstruct(a_1, c_1, y_0)
z_0 = reconstruct(a_1, b_1, z_0)
sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c)
x_0 = abs(x_0*sq_lcm//sqf_of_a)
y_0 = abs(y_0*sq_lcm//sqf_of_b)
z_0 = abs(z_0*sq_lcm//sqf_of_c)
result.add(_remove_gcd(x_0, y_0, z_0))
return result
def sqf_normal(a, b, c, steps=False):
"""
Return `a', b', c'`, the coefficients of the square-free normal
form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise
prime. If `steps` is True then also return three tuples:
`sq`, `sqf`, and `(a', b', c')` where `sq` contains the square
factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`;
`sqf` contains the values of `a`, `b` and `c` after removing
both the `gcd(a, b, c)` and the square factors.
The solutions for `ax^2 + by^2 + cz^2 = 0` can be
recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sqf_normal
>>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11)
(11, 1, 5)
>>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True)
((3, 1, 7), (5, 55, 11), (11, 1, 5))
References
==========
.. [1] Legendre's Theorem, Legrange's Descent,
http://public.csusm.edu/aitken_html/notes/legendre.pdf
See Also
========
reconstruct()
"""
ABC = _remove_gcd(a, b, c)
sq = tuple(square_factor(i) for i in ABC)
sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)])
pc = igcd(A, B)
A /= pc
B /= pc
pa = igcd(B, C)
B /= pa
C /= pa
pb = igcd(A, C)
A /= pb
B /= pb
A *= pa
B *= pb
C *= pc
if steps:
return (sq, sqf, (A, B, C))
else:
return A, B, C
def square_factor(a):
r"""
Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square
free. `a` can be given as an integer or a dictionary of factors.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import square_factor
>>> square_factor(24)
2
>>> square_factor(-36*3)
6
>>> square_factor(1)
1
>>> square_factor({3: 2, 2: 1, -1: 1}) # -18
3
See Also
========
sympy.ntheory.factor_.core
"""
f = a if isinstance(a, dict) else factorint(a)
return Mul(*[p**(e//2) for p, e in f.items()])
def reconstruct(A, B, z):
"""
Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2`
from the `z` value of a solution of the square-free normal form of the
equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square
free and `gcd(a', b', c') == 1`.
"""
f = factorint(igcd(A, B))
for p, e in f.items():
if e != 1:
raise ValueError('a and b should be square-free')
z *= p
return z
def ldescent(A, B):
"""
Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
Lagrange's method; return None if there is no such solution.
.
Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a
tuple `(w_0, x_0, y_0)` which is a solution to the above equation.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import ldescent
>>> ldescent(1, 1) # w^2 = x^2 + y^2
(1, 1, 0)
>>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2
(2, -1, 0)
This means that `x = -1, y = 0` and `w = 2` is a solution to the equation
`w^2 = 4x^2 - 7y^2`
>>> ldescent(5, -1) # w^2 = 5x^2 - y^2
(2, 1, -1)
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University
Press, Cambridge, 1998.
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
[online], Available:
http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf
"""
if abs(A) > abs(B):
w, y, x = ldescent(B, A)
return w, x, y
if A == 1:
return (1, 1, 0)
if B == 1:
return (1, 0, 1)
if B == -1: # and A == -1
return
r = sqrt_mod(A, B)
Q = (r**2 - A) // B
if Q == 0:
B_0 = 1
d = 0
else:
div = divisors(Q)
B_0 = None
for i in div:
sQ, _exact = integer_nthroot(abs(Q) // i, 2)
if _exact:
B_0, d = sign(Q)*i, sQ
break
if B_0 is not None:
W, X, Y = ldescent(A, B_0)
return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d))
def descent(A, B):
"""
Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2`
using Lagrange's descent method with lattice-reduction. `A` and `B`
are assumed to be valid for such a solution to exist.
This is faster than the normal Lagrange's descent algorithm because
the Gaussian reduction is used.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import descent
>>> descent(3, 1) # x**2 = 3*y**2 + z**2
(1, 0, 1)
`(x, y, z) = (1, 0, 1)` is a solution to the above equation.
>>> descent(41, -113)
(-16, -3, 1)
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
if abs(A) > abs(B):
x, y, z = descent(B, A)
return x, z, y
if B == 1:
return (1, 0, 1)
if A == 1:
return (1, 1, 0)
if B == -A:
return (0, 1, 1)
if B == A:
x, z, y = descent(-1, A)
return (A*y, z, x)
w = sqrt_mod(A, B)
x_0, z_0 = gaussian_reduce(w, A, B)
t = (x_0**2 - A*z_0**2) // B
t_2 = square_factor(t)
t_1 = t // t_2**2
x_1, z_1, y_1 = descent(A, t_1)
return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1)
def gaussian_reduce(w, a, b):
r"""
Returns a reduced solution `(x, z)` to the congruence
`X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal.
Details
=======
Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)`
References
==========
.. [1] Gaussian lattice Reduction [online]. Available:
http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
u = (0, 1)
v = (1, 0)
if dot(u, v, w, a, b) < 0:
v = (-v[0], -v[1])
if norm(u, w, a, b) < norm(v, w, a, b):
u, v = v, u
while norm(u, w, a, b) > norm(v, w, a, b):
k = dot(u, v, w, a, b) // dot(v, v, w, a, b)
u, v = v, (u[0]- k*v[0], u[1]- k*v[1])
u, v = v, u
if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b):
c = v
else:
c = (u[0] - v[0], u[1] - v[1])
return c[0]*w + b*c[1], c[0]
def dot(u, v, w, a, b):
r"""
Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and
`v = (v_{1}, v_{2})` which is defined in order to reduce solution of
the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`.
"""
u_1, u_2 = u
v_1, v_2 = v
return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1
def norm(u, w, a, b):
r"""
Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product
defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}`
where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`.
"""
u_1, u_2 = u
return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b))
def holzer(x, y, z, a, b, c):
r"""
Simplify the solution `(x, y, z)` of the equation
`ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to
a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`.
The algorithm is an interpretation of Mordell's reduction as described
on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in
reference [2]_.
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
.. [2] Diophantine Equations, L. J. Mordell, page 48.
"""
if _odd(c):
k = 2*c
else:
k = c//2
small = a*b*c
step = 0
while True:
t1, t2, t3 = a*x**2, b*y**2, c*z**2
# check that it's a solution
if t1 + t2 != t3:
if step == 0:
raise ValueError('bad starting solution')
break
x_0, y_0, z_0 = x, y, z
if max(t1, t2, t3) <= small:
# Holzer condition
break
uv = u, v = base_solution_linear(k, y_0, -x_0)
if None in uv:
break
p, q = -(a*u*x_0 + b*v*y_0), c*z_0
r = Rational(p, q)
if _even(c):
w = _nint_or_floor(p, q)
assert abs(w - r) <= S.Half
else:
w = p//q # floor
if _odd(a*u + b*v + c*w):
w += 1
assert abs(w - r) <= S.One
A = (a*u**2 + b*v**2 + c*w**2)
B = (a*u*x_0 + b*v*y_0 + c*w*z_0)
x = Rational(x_0*A - 2*u*B, k)
y = Rational(y_0*A - 2*v*B, k)
z = Rational(z_0*A - 2*w*B, k)
assert all(i.is_Integer for i in (x, y, z))
step += 1
return tuple([int(i) for i in (x_0, y_0, z_0)])
def diop_general_pythagorean(eq, param=symbols("m", integer=True)):
"""
Solves the general pythagorean equation,
`a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
Returns a tuple which contains a parametrized solution to the equation,
sorted in the same order as the input variables.
Usage
=====
``diop_general_pythagorean(eq, param)``: where ``eq`` is a general
pythagorean equation which is assumed to be zero and ``param`` is the base
parameter used to construct other parameters by subscripting.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2)
(m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2)
>>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2)
(10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralPythagorean.name:
return list(_diop_general_pythagorean(var, coeff, param))[0]
def _diop_general_pythagorean(var, coeff, t):
if sign(coeff[var[0]**2]) + sign(coeff[var[1]**2]) + sign(coeff[var[2]**2]) < 0:
for key in coeff.keys():
coeff[key] = -coeff[key]
n = len(var)
index = 0
for i, v in enumerate(var):
if sign(coeff[v**2]) == -1:
index = i
m = symbols('%s1:%i' % (t, n), integer=True)
ith = sum(m_i**2 for m_i in m)
L = [ith - 2*m[n - 2]**2]
L.extend([2*m[i]*m[n-2] for i in range(n - 2)])
sol = L[:index] + [ith] + L[index:]
lcm = 1
for i, v in enumerate(var):
if i == index or (index > 0 and i == 0) or (index == 0 and i == 1):
lcm = ilcm(lcm, sqrt(abs(coeff[v**2])))
else:
s = sqrt(coeff[v**2])
lcm = ilcm(lcm, s if _odd(s) else s//2)
for i, v in enumerate(var):
sol[i] = (lcm*sol[i]) / sqrt(abs(coeff[v**2]))
result = DiophantineSolutionSet(var)
result.add(sol)
return result
def diop_general_sum_of_squares(eq, limit=1):
r"""
Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Details
=======
When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
no solutions. Refer [1]_ for more details.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345)
{(15, 22, 22, 24, 24)}
Reference
=========
.. [1] Representing an integer as a sum of three squares, [online],
Available:
http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfSquares.name:
return set(_diop_general_sum_of_squares(var, -int(coeff[1]), limit))
def _diop_general_sum_of_squares(var, k, limit=1):
# solves Eq(sum(i**2 for i in var), k)
n = len(var)
if n < 3:
raise ValueError('n must be greater than 2')
result = DiophantineSolutionSet(var)
if k < 0 or limit < 1:
return result
sign = [-1 if x.is_nonpositive else 1 for x in var]
negs = sign.count(-1) != 0
took = 0
for t in sum_of_squares(k, n, zeros=True):
if negs:
result.add([sign[i]*j for i, j in enumerate(t)])
else:
result.add(t)
took += 1
if took == limit:
break
return result
def diop_general_sum_of_even_powers(eq, limit=1):
"""
Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
where `e` is an even, integer power.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers
>>> from sympy.abc import a, b
>>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4))
{(2, 3)}
See Also
========
power_representation
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfEvenPowers.name:
for k in coeff.keys():
if k.is_Pow and coeff[k]:
p = k.exp
return set(_diop_general_sum_of_even_powers(var, p, -coeff[1], limit))
def _diop_general_sum_of_even_powers(var, p, n, limit=1):
# solves Eq(sum(i**2 for i in var), n)
k = len(var)
result = DiophantineSolutionSet(var)
if n < 0 or limit < 1:
return result
sign = [-1 if x.is_nonpositive else 1 for x in var]
negs = sign.count(-1) != 0
took = 0
for t in power_representation(n, p, k):
if negs:
result.add([sign[i]*j for i, j in enumerate(t)])
else:
result.add(t)
took += 1
if took == limit:
break
return result
## Functions below this comment can be more suitably grouped under
## an Additive number theory module rather than the Diophantine
## equation module.
def partition(n, k=None, zeros=False):
"""
Returns a generator that can be used to generate partitions of an integer
`n`.
Explanation
===========
A partition of `n` is a set of positive integers which add up to `n`. For
example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned
as a tuple. If ``k`` equals None, then all possible partitions are returned
irrespective of their size, otherwise only the partitions of size ``k`` are
returned. If the ``zero`` parameter is set to True then a suitable
number of zeros are added at the end of every partition of size less than
``k``.
``zero`` parameter is considered only if ``k`` is not None. When the
partitions are over, the last `next()` call throws the ``StopIteration``
exception, so this function should always be used inside a try - except
block.
Details
=======
``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size
of the partition which is also positive integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import partition
>>> f = partition(5)
>>> next(f)
(1, 1, 1, 1, 1)
>>> next(f)
(1, 1, 1, 2)
>>> g = partition(5, 3)
>>> next(g)
(1, 1, 3)
>>> next(g)
(1, 2, 2)
>>> g = partition(5, 3, zeros=True)
>>> next(g)
(0, 0, 5)
"""
from sympy.utilities.iterables import ordered_partitions
if not zeros or k is None:
for i in ordered_partitions(n, k):
yield tuple(i)
else:
for m in range(1, k + 1):
for i in ordered_partitions(n, m):
i = tuple(i)
yield (0,)*(k - len(i)) + i
def prime_as_sum_of_two_squares(p):
"""
Represent a prime `p` as a unique sum of two squares; this can
only be done if the prime is congruent to 1 mod 4.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares
>>> prime_as_sum_of_two_squares(7) # can't be done
>>> prime_as_sum_of_two_squares(5)
(1, 2)
Reference
=========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if not p % 4 == 1:
return
if p % 8 == 5:
b = 2
else:
b = 3
while pow(b, (p - 1) // 2, p) == 1:
b = nextprime(b)
b = pow(b, (p - 1) // 4, p)
a = p
while b**2 > p:
a, b = b, a % b
return (int(a % b), int(b)) # convert from long
def sum_of_three_squares(n):
r"""
Returns a 3-tuple `(a, b, c)` such that `a^2 + b^2 + c^2 = n` and
`a, b, c \geq 0`.
Returns None if `n = 4^a(8m + 7)` for some `a, m \in Z`. See
[1]_ for more details.
Usage
=====
``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares
>>> sum_of_three_squares(44542)
(18, 37, 207)
References
==========
.. [1] Representing a number as a sum of three squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0),
85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15),
526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36),
2986: (21, 32, 39), 9634: (56, 57, 57)}
v = 0
if n == 0:
return (0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
return
if n in special.keys():
x, y, z = special[n]
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
s, _exact = integer_nthroot(n, 2)
if _exact:
return (2**v*s, 0, 0)
x = None
if n % 8 == 3:
s = s if _odd(s) else s - 1
for x in range(s, -1, -2):
N = (n - x**2) // 2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z))
return
if n % 8 == 2 or n % 8 == 6:
s = s if _odd(s) else s - 1
else:
s = s - 1 if _odd(s) else s
for x in range(s, -1, -2):
N = n - x**2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
def sum_of_four_squares(n):
r"""
Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`.
Here `a, b, c, d \geq 0`.
Usage
=====
``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares
>>> sum_of_four_squares(3456)
(8, 8, 32, 48)
>>> sum_of_four_squares(1294585930293)
(0, 1234, 2161, 1137796)
References
==========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if n == 0:
return (0, 0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
d = 2
n = n - 4
elif n % 8 == 6 or n % 8 == 2:
d = 1
n = n - 1
else:
d = 0
x, y, z = sum_of_three_squares(n)
return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z)
def power_representation(n, p, k, zeros=False):
r"""
Returns a generator for finding k-tuples of integers,
`(n_{1}, n_{2}, . . . n_{k})`, such that
`n = n_{1}^p + n_{2}^p + . . . n_{k}^p`.
Usage
=====
``power_representation(n, p, k, zeros)``: Represent non-negative number
``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the
solutions is allowed to contain zeros.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import power_representation
Represent 1729 as a sum of two cubes:
>>> f = power_representation(1729, 3, 2)
>>> next(f)
(9, 10)
>>> next(f)
(1, 12)
If the flag `zeros` is True, the solution may contain tuples with
zeros; any such solutions will be generated after the solutions
without zeros:
>>> list(power_representation(125, 2, 3, zeros=True))
[(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)]
For even `p` the `permute_sign` function can be used to get all
signed values:
>>> from sympy.utilities.iterables import permute_signs
>>> list(permute_signs((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12)]
All possible signed permutations can also be obtained:
>>> from sympy.utilities.iterables import signed_permutations
>>> list(signed_permutations((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)]
"""
n, p, k = [as_int(i) for i in (n, p, k)]
if n < 0:
if p % 2:
for t in power_representation(-n, p, k, zeros):
yield tuple(-i for i in t)
return
if p < 1 or k < 1:
raise ValueError(filldedent('''
Expecting positive integers for `(p, k)`, but got `(%s, %s)`'''
% (p, k)))
if n == 0:
if zeros:
yield (0,)*k
return
if k == 1:
if p == 1:
yield (n,)
else:
be = perfect_power(n)
if be:
b, e = be
d, r = divmod(e, p)
if not r:
yield (b**d,)
return
if p == 1:
for t in partition(n, k, zeros=zeros):
yield t
return
if p == 2:
feasible = _can_do_sum_of_squares(n, k)
if not feasible:
return
if not zeros and n > 33 and k >= 5 and k <= n and n - k in (
13, 10, 7, 5, 4, 2, 1):
'''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online].
Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf'''
return
if feasible is not True: # it's prime and k == 2
yield prime_as_sum_of_two_squares(n)
return
if k == 2 and p > 2:
be = perfect_power(n)
if be and be[1] % p == 0:
return # Fermat: a**n + b**n = c**n has no solution for n > 2
if n >= k:
a = integer_nthroot(n - (k - 1), p)[0]
for t in pow_rep_recursive(a, k, n, [], p):
yield tuple(reversed(t))
if zeros:
a = integer_nthroot(n, p)[0]
for i in range(1, k):
for t in pow_rep_recursive(a, i, n, [], p):
yield tuple(reversed(t + (0,) * (k - i)))
sum_of_powers = power_representation
def pow_rep_recursive(n_i, k, n_remaining, terms, p):
if k == 0 and n_remaining == 0:
yield tuple(terms)
else:
if n_i >= 1 and k > 0:
yield from pow_rep_recursive(n_i - 1, k, n_remaining, terms, p)
residual = n_remaining - pow(n_i, p)
if residual >= 0:
yield from pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p)
def sum_of_squares(n, k, zeros=False):
"""Return a generator that yields the k-tuples of nonnegative
values, the squares of which sum to n. If zeros is False (default)
then the solution will not contain zeros. The nonnegative
elements of a tuple are sorted.
* If k == 1 and n is square, (n,) is returned.
* If k == 2 then n can only be written as a sum of squares if
every prime in the factorization of n that has the form
4*k + 3 has an even multiplicity. If n is prime then
it can only be written as a sum of two squares if it is
in the form 4*k + 1.
* if k == 3 then n can be written as a sum of squares if it does
not have the form 4**m*(8*k + 7).
* all integers can be written as the sum of 4 squares.
* if k > 4 then n can be partitioned and each partition can
be written as a sum of 4 squares; if n is not evenly divisible
by 4 then n can be written as a sum of squares only if the
an additional partition can be written as sum of squares.
For example, if k = 6 then n is partitioned into two parts,
the first being written as a sum of 4 squares and the second
being written as a sum of 2 squares -- which can only be
done if the condition above for k = 2 can be met, so this will
automatically reject certain partitions of n.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_squares
>>> list(sum_of_squares(25, 2))
[(3, 4)]
>>> list(sum_of_squares(25, 2, True))
[(3, 4), (0, 5)]
>>> list(sum_of_squares(25, 4))
[(1, 2, 2, 4)]
See Also
========
sympy.utilities.iterables.signed_permutations
"""
yield from power_representation(n, 2, k, zeros)
def _can_do_sum_of_squares(n, k):
"""Return True if n can be written as the sum of k squares,
False if it can't, or 1 if ``k == 2`` and ``n`` is prime (in which
case it *can* be written as a sum of two squares). A False
is returned only if it can't be written as ``k``-squares, even
if 0s are allowed.
"""
if k < 1:
return False
if n < 0:
return False
if n == 0:
return True
if k == 1:
return is_square(n)
if k == 2:
if n in (1, 2):
return True
if isprime(n):
if n % 4 == 1:
return 1 # signal that it was prime
return False
else:
f = factorint(n)
for p, m in f.items():
# we can proceed iff no prime factor in the form 4*k + 3
# has an odd multiplicity
if (p % 4 == 3) and m % 2:
return False
return True
if k == 3:
if (n//4**multiplicity(4, n)) % 8 == 7:
return False
# every number can be written as a sum of 4 squares; for k > 4 partitions
# can be 0
return True
|
a9214d601fcc5394857626b662d080729ca7592d50d19023bfb7adbffafafac7 | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~sympy.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
- :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals
are the actual infinitesimals of a first order ODE.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order differential equation that can be solved with algebraic
rearrangement and integration.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~sympy.integrals.integrals.Integral` class.
:py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
(if the match function is more than just a few lines, like
:py:meth:`~sympy.solvers.ode.ode._undetermined_coefficients_match`, it should go
outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
:py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
:py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in SymPy, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main SymPy documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the doc directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:obj:`~.Integral` instead of
:py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :obj:`~sympy.functions.elementary.exponential.log` terms, so
:py:meth:`~sympy.solvers.ode.ode.odesimp` calls
:py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to SymPy, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
won't be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from collections import defaultdict
from itertools import islice
from sympy.functions import hyper
from sympy.core import Add, S, Mul, Pow, oo, Rational
from sympy.core.compatibility import ordered, iterable
from sympy.core.containers import Tuple
from sympy.core.exprtools import factor_terms
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
expand, expand_mul, Subs, _mexpand)
from sympy.core.multidimensional import vectorize
from sympy.core.numbers import NaN, zoo, Number
from sympy.core.relational import Equality, Eq
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
from sympy.core.sympify import sympify
from sympy.logic.boolalg import (BooleanAtom, BooleanTrue,
BooleanFalse)
from sympy.functions import cos, cosh, exp, im, log, re, sin, sinh, sqrt, \
atan2, conjugate, cbrt, besselj, bessely, airyai, airybi
from sympy.functions.combinatorial.factorials import factorial
from sympy.integrals.integrals import Integral, integrate
from sympy.matrices import wronskian
from sympy.polys import (Poly, RootOf, rootof, terms_gcd,
PolynomialError, lcm, roots, gcd)
from sympy.polys.polytools import cancel, degree, div
from sympy.series import Order
from sympy.series.series import series
from sympy.simplify import (collect, logcombine, powsimp, # type: ignore
separatevars, simplify, trigsimp, posify, cse)
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import collect_const
from sympy.solvers import checksol, solve
from sympy.solvers.pde import pdsolve
from sympy.utilities import numbered_symbols, default_sort_key, sift
from sympy.utilities.iterables import uniq
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
from .subscheck import sub_func_doit
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of SymPy.
#:
#: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
"factorable",
"nth_algebraic",
"separable",
"1st_exact",
"1st_linear",
"Bernoulli",
"Riccati_special_minus2",
"1st_homogeneous_coeff_best",
"1st_homogeneous_coeff_subs_indep_div_dep",
"1st_homogeneous_coeff_subs_dep_div_indep",
"almost_linear",
"linear_coefficients",
"separable_reduced",
"1st_power_series",
"lie_group",
"nth_linear_constant_coeff_homogeneous",
"nth_linear_euler_eq_homogeneous",
"nth_linear_constant_coeff_undetermined_coefficients",
"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
"nth_linear_constant_coeff_variation_of_parameters",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
"Liouville",
"2nd_linear_airy",
"2nd_linear_bessel",
"2nd_hypergeometric",
"2nd_hypergeometric_Integral",
"nth_order_reducible",
"2nd_power_series_ordinary",
"2nd_power_series_regular",
"nth_algebraic_Integral",
"separable_Integral",
"1st_exact_Integral",
"1st_linear_Integral",
"Bernoulli_Integral",
"1st_homogeneous_coeff_subs_indep_div_dep_Integral",
"1st_homogeneous_coeff_subs_dep_div_indep_Integral",
"almost_linear_Integral",
"linear_coefficients_Integral",
"separable_reduced_Integral",
"nth_linear_constant_coeff_variation_of_parameters_Integral",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
"Liouville_Integral",
)
lie_heuristics = (
"abaco1_simple",
"abaco1_product",
"abaco2_similar",
"abaco2_unique_unknown",
"abaco2_unique_general",
"linear",
"function_sum",
"bivariate",
"chi"
)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
ncs = iter_numbered_constants(eq, start, prefix)
Cs = [next(ncs) for i in range(num)]
return (Cs[0] if num == 1 else tuple(Cs))
def iter_numbered_constants(eq, start=1, prefix='C'):
"""
Returns an iterator of constants that do not occur
in eq already.
"""
if isinstance(eq, (Expr, Eq)):
eq = [eq]
elif not iterable(eq):
raise ValueError("Expected Expr or iterable but got %s" % eq)
atom_set = set().union(*[i.free_symbols for i in eq])
func_set = set().union(*[i.atoms(Function) for i in eq])
if func_set:
atom_set |= {Symbol(str(f.func)) for f in func_set}
return numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
def dsolve(eq, func=None, hint="default", simplify=True,
ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
For single ordinary differential equation
=========================================
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~sympy.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it couldn't be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
heuristics.
``ics`` is the set of initial/boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
x3}`` and so on. For power series solutions, if no initial
conditions are specified ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~sympy.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~sympy.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- You can declare the derivative of an unknown function this way:
>>> from sympy import Function, Derivative
>>> from sympy.abc import x # x is the independent variable
>>> f = Function("f")(x) # f is a function of x
>>> # f_ will be the derivative of f with respect to x
>>> f_ = Derivative(f, x)
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.dsolve` always returns an
:py:class:`~sympy.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
For system of ordinary differential equations
=============================================
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it couldn't be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> t = symbols('t')
>>> x, y = symbols('x, y', cls=Function)
>>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
>>> dsolve(eq)
[Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)),
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) +
exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))]
>>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
>>> dsolve(eq)
{Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}
"""
if iterable(eq):
from sympy.solvers.ode.systems import dsolve_system
# This may have to be changed in future
# when we have weakly and strongly
# connected components. This have to
# changed to show the systems that haven't
# been solved.
try:
sol = dsolve_system(eq, funcs=func, ics=ics, doit=True)
return sol[0] if len(sol) == 1 else sol
except NotImplementedError:
pass
match = classify_sysode(eq, func)
eq = match['eq']
order = match['order']
func = match['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# keep highest order term coefficient positive
for i in range(len(eq)):
for func_ in func:
if isinstance(func_, list):
pass
else:
if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative:
eq[i] = -eq[i]
match['eq'] = eq
if len(set(order.values()))!=1:
raise ValueError("It solves only those systems of equations whose orders are equal")
match['order'] = list(order.values())[0]
def recur_len(l):
return sum(recur_len(item) if isinstance(item,list) else 1 for item in l)
if recur_len(func) != len(eq):
raise ValueError("dsolve() and classify_sysode() work with "
"number of functions being equal to number of equations")
if match['type_of_equation'] is None:
raise NotImplementedError
else:
if match['is_linear'] == True:
solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match]
sols = solvefunc(match)
if ics:
constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols
solved_constants = solve_ics(sols, func, constants, ics)
return [sol.subs(solved_constants) for sol in sols]
return sols
else:
given_hint = hint # hint given by the user
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func,
hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
x0=x0, n=n, **kwargs)
eq = hints.pop('eq', eq)
all_ = hints.pop('all', False)
if all_:
retdict = {}
failed_hints = {}
gethints = classify_ode(eq, dict=True)
orderedhints = gethints['ordered_hints']
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints:
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
retdict.update(failed_hints)
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify, ics=ics)
def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
differential equations. This minimizes the computation in calling
:py:meth:`~sympy.solvers.deutils._desolve` multiple times.
"""
r = match
func = r['func']
order = r['order']
match = r[hint]
if isinstance(match, SingleODESolver):
solvefunc = match
elif hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
free = eq.free_symbols
cons = lambda s: s.free_symbols.difference(free)
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
if isinstance(solvefunc, SingleODESolver):
sols = solvefunc.get_general_solution()
else:
sols = solvefunc(eq, func, order, match)
if iterable(sols):
rv = [odesimp(eq, s, func, hint) for s in sols]
else:
rv = odesimp(eq, sols, func, hint)
else:
# We still want to integrate (you can disable it separately with the hint)
if isinstance(solvefunc, SingleODESolver):
exprs = solvefunc.get_general_solution(simplify=False)
else:
match['simplify'] = False # Some hints can take advantage of this option
exprs = solvefunc(eq, func, order, match)
if isinstance(exprs, list):
rv = [_handle_Integral(expr, func, hint) for expr in exprs]
else:
rv = _handle_Integral(exprs, func, hint)
if isinstance(rv, list):
rv = _remove_redundant_solutions(eq, rv, order, func.args[0])
if len(rv) == 1:
rv = rv[0]
if ics and not 'power_series' in hint:
if isinstance(rv, (Expr, Eq)):
solved_constants = solve_ics([rv], [r['func']], cons(rv), ics)
rv = rv.subs(solved_constants)
else:
rv1 = []
for s in rv:
try:
solved_constants = solve_ics([s], [r['func']], cons(s), ics)
except ValueError:
continue
rv1.append(s.subs(solved_constants))
if len(rv1) == 1:
return rv1[0]
rv = rv1
return rv
def solve_ics(sols, funcs, constants, ics):
"""
Solve for the constants given initial conditions
``sols`` is a list of solutions.
``funcs`` is a list of functions.
``constants`` is a list of constants.
``ics`` is the set of initial/boundary conditions for the differential
equation. It should be given in the form of ``{f(x0): x1,
f(x).diff(x).subs(x, x2): x3}`` and so on.
Returns a dictionary mapping constants to values.
``solution.subs(constants)`` will replace the constants in ``solution``.
Example
=======
>>> # From dsolve(f(x).diff(x) - f(x), f(x))
>>> from sympy import symbols, Eq, exp, Function
>>> from sympy.solvers.ode.ode import solve_ics
>>> f = Function('f')
>>> x, C1 = symbols('x C1')
>>> sols = [Eq(f(x), C1*exp(x))]
>>> funcs = [f(x)]
>>> constants = [C1]
>>> ics = {f(0): 2}
>>> solved_constants = solve_ics(sols, funcs, constants, ics)
>>> solved_constants
{C1: 2}
>>> sols[0].subs(solved_constants)
Eq(f(x), 2*exp(x))
"""
# Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x,
# x0)): value (currently checked by classify_ode). To solve, replace x
# with x0, f(x0) with value, then solve for constants. For f^(n)(x0),
# differentiate the solution n times, so that f^(n)(x) appears.
x = funcs[0].args[0]
diff_sols = []
subs_sols = []
diff_variables = set()
for funcarg, value in ics.items():
if isinstance(funcarg, AppliedUndef):
x0 = funcarg.args[0]
matching_func = [f for f in funcs if f.func == funcarg.func][0]
S = sols
elif isinstance(funcarg, (Subs, Derivative)):
if isinstance(funcarg, Subs):
# Make sure it stays a subs. Otherwise subs below will produce
# a different looking term.
funcarg = funcarg.doit()
if isinstance(funcarg, Subs):
deriv = funcarg.expr
x0 = funcarg.point[0]
variables = funcarg.expr.variables
matching_func = deriv
elif isinstance(funcarg, Derivative):
deriv = funcarg
x0 = funcarg.variables[0]
variables = (x,)*len(funcarg.variables)
matching_func = deriv.subs(x0, x)
if variables not in diff_variables:
for sol in sols:
if sol.has(deriv.expr.func):
diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables)))
diff_variables.add(variables)
S = diff_sols
else:
raise NotImplementedError("Unrecognized initial condition")
for sol in S:
if sol.has(matching_func):
sol2 = sol
sol2 = sol2.subs(x, x0)
sol2 = sol2.subs(funcarg, value)
# This check is necessary because of issue #15724
if not isinstance(sol2, BooleanAtom) or not subs_sols:
subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)]
subs_sols.append(sol2)
# TODO: Use solveset here
try:
solved_constants = solve(subs_sols, constants, dict=True)
except NotImplementedError:
solved_constants = []
# XXX: We can't differentiate between the solution not existing because of
# invalid initial conditions, and not existing because solve is not smart
# enough. If we could use solveset, this might be improvable, but for now,
# we use NotImplementedError in this case.
if not solved_constants:
raise ValueError("Couldn't solve for initial conditions")
if solved_constants == True:
raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.")
if len(solved_constants) > 1:
raise NotImplementedError("Initial conditions produced too many solutions for constants")
return solved_constants[0]
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~sympy.solvers.ode.allhints` or the
:py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:func:`~sympy.integrals.integrals.integrate` is not used in
solving the ODE for those method. For example, `n`\th order linear
homogeneous ODEs with constant coefficients do not require integration
to solve, so there is no
``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can
easily evaluate any unevaluated
:py:class:`~sympy.integrals.integrals.Integral`\s in an expression by
doing ``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means the the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> from sympy import Function, classify_ode, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('nth_algebraic',
'separable',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral',
'1st_linear_Integral', 'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
>>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4)
('nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
ics = sympify(ics)
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_ode() only "
"work with functions of one variable, not %s" % func)
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
# Some methods want the unprocessed equation
eq_orig = eq
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
terms = n
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {"order": order}
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
k = Wild('k', exclude=[df])
n = Wild('n', exclude=[x, f(x), df])
c1 = Wild('c1', exclude=[x])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint
boundary = {} # Used to extract initial conditions
C1 = Symbol("C1")
# Preprocessing to get the initial conditions out
if ics is not None:
for funcarg in ics:
# Separating derivatives
if isinstance(funcarg, (Subs, Derivative)):
# f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x,
# y) is a Derivative
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
elif isinstance(funcarg, Derivative):
deriv = funcarg
# No information on this. Just assume it was x
old = x
new = funcarg.variables[0]
if (isinstance(deriv, Derivative) and isinstance(deriv.args[0],
AppliedUndef) and deriv.args[0].func == f and
len(deriv.args[0].args) == 1 and old == x and not
new.has(x) and all(i == deriv.variables[0] for i in
deriv.variables) and not ics[funcarg].has(f)):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Derivatives")
# Separating functions
elif isinstance(funcarg, AppliedUndef):
if (funcarg.func == f and len(funcarg.args) == 1 and
not funcarg.args[0].has(x) and not ics[funcarg].has(f)):
boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Function")
else:
raise ValueError("Enter boundary conditions of the form ics={f(point}: value, f(x).diff(x, order).subs(x, point): value}")
# Any ODE that can be solved with a combination of algebra and
# integrals e.g.:
# d^3/dx^3(x y) = F(x)
ode = SingleODEProblem(eq_orig, func, x, prep=prep)
solvers = {
NthAlgebraic: ('nth_algebraic',),
FirstLinear: ('1st_linear',),
AlmostLinear: ('almost_linear',),
Bernoulli: ('Bernoulli',),
Factorable: ('factorable',),
RiccatiSpecial: ('Riccati_special_minus2',),
}
for solvercls in solvers:
solver = solvercls(ode)
if solver.matches():
for hints in solvers[solvercls]:
matching_hints[hints] = solver
if solvercls.has_integral:
matching_hints[hints + "_Integral"] = solver
eq = expand(eq)
# Precondition to try remove f(x) from highest order derivative
reduced_eq = None
if eq.is_Add:
deriv_coef = eq.coeff(f(x).diff(x, order))
if deriv_coef not in (1, 0):
r = deriv_coef.match(a*f(x)**c1)
if r and r[c1]:
den = f(x)**r[c1]
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
# NON-REDUCED FORM OF EQUATION matches
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs(f(x), y)
r[e] = r[e].subs(f(x), y)
# FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
# TODO: Hint first order series should match only if d/e is analytic.
# For now, only d/e and (d/e).diff(arg) is checked for existence at
# at a given point.
# This is currently done internally in ode_1st_power_series.
point = boundary.get('f0', 0)
value = boundary.get('f0val', C1)
check = cancel(r[d]/r[e])
check1 = check.subs({x: point, y: value})
if not check1.has(oo) and not check1.has(zoo) and \
not check1.has(NaN) and not check1.has(-oo):
check2 = (check1.diff(x)).subs({x: point, y: value})
if not check2.has(oo) and not check2.has(zoo) and \
not check2.has(NaN) and not check2.has(-oo):
rseries = r.copy()
rseries.update({'terms': terms, 'f0': point, 'f0val': value})
matching_hints["1st_power_series"] = rseries
r3.update(r)
## Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where
# dP/dy == dQ/dx
try:
if r[d] != 0:
numerator = simplify(r[d].diff(y) - r[e].diff(x))
# The following few conditions try to convert a non-exact
# differential equation into an exact one.
# References : Differential equations with applications
# and historical notes - George E. Simmons
if numerator:
# If (dP/dy - dQ/dx) / Q = f(x)
# then exp(integral(f(x))*equation becomes exact
factor = simplify(numerator/r[e])
variables = factor.free_symbols
if len(variables) == 1 and x == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
# If (dP/dy - dQ/dx) / -P = f(y)
# then exp(integral(f(y))*equation becomes exact
factor = simplify(-numerator/r[d])
variables = factor.free_symbols
if len(variables) == 1 and y == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
except NotImplementedError:
# Differentiating the coefficients might fail because of things
# like f(2*x).diff(x). See issue 4624 and issue 4719.
pass
# Any first order ODE can be ideally solved by the Lie Group
# method
matching_hints["lie_group"] = r3
# This match is used for several cases below; we now collect on
# f(x) so the matching works.
r = collect(reduced_eq, df, exact=True).match(d + e*df)
if r:
# Using r[d] and r[e] without any modification for hints
# linear-coefficients and separable-reduced.
num, den = r[d], r[e] # ODE = d/e + df
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = num.subs(f(x), y)
r[e] = den.subs(f(x), y)
## Separable Case: y' == P(y)*Q(x)
r[d] = separatevars(r[d])
r[e] = separatevars(r[e])
# m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y'
m1 = separatevars(r[d], dict=True, symbols=(x, y))
m2 = separatevars(r[e], dict=True, symbols=(x, y))
if m1 and m2:
r1 = {'m1': m1, 'm2': m2, 'y': y}
matching_hints["separable"] = r1
matching_hints["separable_Integral"] = r1
## First order equation with homogeneous coefficients:
# dy/dx == F(y/x) or dy/dx == F(x/y)
ordera = homogeneous_order(r[d], x, y)
if ordera is not None:
orderb = homogeneous_order(r[e], x, y)
if ordera == orderb:
# u1=y/x and u2=x/y
u1 = Dummy('u1')
u2 = Dummy('u2')
s = "1st_homogeneous_coeff_subs"
s1 = s + "_dep_div_indep"
s2 = s + "_indep_div_dep"
if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0:
matching_hints[s1] = r
matching_hints[s1 + "_Integral"] = r
if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0:
matching_hints[s2] = r
matching_hints[s2 + "_Integral"] = r
if s1 in matching_hints and s2 in matching_hints:
matching_hints["1st_homogeneous_coeff_best"] = r
## Linear coefficients of the form
# y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0
# that can be reduced to homogeneous form.
F = num/den
params = _linear_coeff_match(F, func)
if params:
xarg, yarg = params
u = Dummy('u')
t = Dummy('t')
# Dummy substitution for df and f(x).
dummy_eq = reduced_eq.subs(((df, t), (f(x), u)))
reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x)))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d)
if r2:
orderd = homogeneous_order(r2[d], x, f(x))
if orderd is not None:
ordere = homogeneous_order(r2[e], x, f(x))
if orderd == ordere:
# Match arguments are passed in such a way that it
# is coherent with the already existing homogeneous
# functions.
r2[d] = r2[d].subs(f(x), y)
r2[e] = r2[e].subs(f(x), y)
r2.update({'xarg': xarg, 'yarg': yarg,
'd': d, 'e': e, 'y': y})
matching_hints["linear_coefficients"] = r2
matching_hints["linear_coefficients_Integral"] = r2
## Equation of the form y' + (y/x)*H(x^n*y) = 0
# that can be reduced to separable form
factor = simplify(x/f(x)*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
num, dem = factor.as_numer_denom()
num = expand(num)
dem = expand(dem)
def _degree(expr, x):
# Made this function to calculate the degree of
# x in an expression. If expr will be of form
# x**p*y, (wheare p can be variables/rationals) then it
# will return p.
for val in expr:
if val.has(x):
if isinstance(val, Pow) and val.as_base_exp()[0] == x:
return (val.as_base_exp()[1])
elif val == x:
return (val.as_base_exp()[1])
else:
return _degree(val.args, x)
return 0
def _powers(expr):
# this function will return all the different relative power of x w.r.t f(x).
# expr = x**p * f(x)**q then it will return {p/q}.
pows = set()
if isinstance(expr, Add):
exprs = expr.atoms(Add)
elif isinstance(expr, Mul):
exprs = expr.atoms(Mul)
elif isinstance(expr, Pow):
exprs = expr.atoms(Pow)
else:
exprs = {expr}
for arg in exprs:
if arg.has(x):
_, u = arg.as_independent(x, f(x))
pow = _degree((u.subs(f(x), y), ), x)/_degree((u.subs(f(x), y), ), y)
pows.add(pow)
return pows
pows = _powers(num)
pows.update(_powers(dem))
pows = list(pows)
if(len(pows)==1) and pows[0]!=zoo:
t = Dummy('t')
r2 = {'t': t}
num = num.subs(x**pows[0]*f(x), t)
dem = dem.subs(x**pows[0]*f(x), t)
test = num/dem
free = test.free_symbols
if len(free) == 1 and free.pop() == t:
r2.update({'power' : pows[0], 'u' : test})
matching_hints['separable_reduced'] = r2
matching_hints["separable_reduced_Integral"] = r2
elif order == 2:
# Liouville ODE in the form
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98
s = d*f(x).diff(x, 2) + e*df**2 + k*df
r = reduced_eq.match(s)
if r and r[d] != 0:
y = Dummy('y')
g = simplify(r[e]/r[d]).subs(f(x), y)
h = simplify(r[k]/r[d]).subs(f(x), y)
if y in h.free_symbols or x in g.free_symbols:
pass
else:
r = {'g': g, 'h': h, 'y': y}
matching_hints["Liouville"] = r
matching_hints["Liouville_Integral"] = r
# Homogeneous second order differential equation of the form
# a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3
# It has a definite power series solution at point x0 if, b3/a3 and c3/a3
# are analytic at x0.
deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
ordinary = False
if r:
if not all([r[key].is_polynomial() for key in r]):
n, d = reduced_eq.as_numer_denom()
reduced_eq = expand(n)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
if r and r[a3] != 0:
p = cancel(r[b3]/r[a3]) # Used below
q = cancel(r[c3]/r[a3]) # Used below
point = kwargs.get('x0', 0)
check = p.subs(x, point)
if not check.has(oo, NaN, zoo, -oo):
check = q.subs(x, point)
if not check.has(oo, NaN, zoo, -oo):
ordinary = True
r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
matching_hints["2nd_power_series_ordinary"] = r
# Checking if the differential equation has a regular singular point
# at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
# and (c3/a3)*((x - x0)**2) are analytic at x0.
if not ordinary:
p = cancel((x - point)*p)
check = p.subs(x, point)
if not check.has(oo, NaN, zoo, -oo):
q = cancel(((x - point)**2)*q)
check = q.subs(x, point)
if not check.has(oo, NaN, zoo, -oo):
coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
matching_hints["2nd_power_series_regular"] = coeff_dict
# For Hypergeometric solutions.
_r = {}
_r.update(r)
rn = match_2nd_hypergeometric(_r, func)
if rn:
matching_hints["2nd_hypergeometric"] = rn
matching_hints["2nd_hypergeometric_Integral"] = rn
# If the ODE has regular singular point at x0 and is of the form
# Eq((x)**2*Derivative(y(x), x, x) + x*Derivative(y(x), x) +
# (a4**2*x**(2*p)-n**2)*y(x) thus Bessel's equation
rn = match_2nd_linear_bessel(r, f(x))
if rn:
matching_hints["2nd_linear_bessel"] = rn
# If the ODE is ordinary and is of the form of Airy's Equation
# Eq(x**2*Derivative(y(x),x,x)-(ax+b)*y(x))
if p.is_zero:
a4 = Wild('a4', exclude=[x,f(x),df])
b4 = Wild('b4', exclude=[x,f(x),df])
rn = q.match(a4+b4*x)
if rn and rn[b4] != 0:
rn = {'b':rn[a4],'m':rn[b4]}
matching_hints["2nd_linear_airy"] = rn
if order > 0:
# Any ODE that can be solved with a substitution and
# repeated integration e.g.:
# `d^2/dx^2(y) + x*d/dx(y) = constant
#f'(x) must be finite for this to work
r = _nth_order_reducible_match(reduced_eq, func)
if r:
matching_hints['nth_order_reducible'] = r
# nth order linear ODE
# a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b
r = _nth_linear_match(reduced_eq, func, order)
# Constant coefficient case (a_i is constant for all i)
if r and not any(r[i].has(x) for i in r if i >= 0):
# Inhomogeneous case: F(x) is not identically 0
if r[-1]:
eq_homogeneous = Add(eq,-r[-1])
undetcoeff = _undetermined_coefficients_match(r[-1], x, func, eq_homogeneous)
s = "nth_linear_constant_coeff_variation_of_parameters"
matching_hints[s] = r
matching_hints[s + "_Integral"] = r
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints[
"nth_linear_constant_coeff_undetermined_coefficients"
] = r
# Homogeneous case: F(x) is identically 0
else:
matching_hints["nth_linear_constant_coeff_homogeneous"] = r
# nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x)
#In case of Homogeneous euler equation F(x) = 0
def _test_term(coeff, order):
r"""
Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x),
where K is independent of x and y(x), order>= 0.
So we need to check that for each term, coeff == K*x**order from
some K. We have a few cases, since coeff may have several
different types.
"""
if order < 0:
raise ValueError("order should be greater than 0")
if coeff == 0:
return True
if order == 0:
if x in coeff.free_symbols:
return False
return True
if coeff.is_Mul:
if coeff.has(f(x)):
return False
return x**order in coeff.args
elif coeff.is_Pow:
return coeff.as_base_exp() == (x, order)
elif order == 1:
return x == coeff
return False
# Find coefficient for highest derivative, multiply coefficients to
# bring the equation into Euler form if possible
r_rescaled = None
if r is not None:
coeff = r[order]
factor = x**order / coeff
r_rescaled = {i: factor*r[i] for i in r if i != 'trialset'}
# XXX: Mixing up the trialset with the coefficients is error-prone.
# These should be separated as something like r['coeffs'] and
# r['trialset']
if r_rescaled and not any(not _test_term(r_rescaled[i], i) for i in
r_rescaled if i != 'trialset' and i >= 0):
if not r_rescaled[-1]:
matching_hints["nth_linear_euler_eq_homogeneous"] = r_rescaled
else:
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r_rescaled
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r_rescaled
e, re = posify(r_rescaled[-1].subs(x, exp(x)))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
r_rescaled['trialset'] = undetcoeff['trialset']
matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r_rescaled
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = retlist[0] if retlist else None
matching_hints["ordered_hints"] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def equivalence(max_num_pow, dem_pow):
# this function is made for checking the equivalence with 2F1 type of equation.
# max_num_pow is the value of maximum power of x in numerator
# and dem_pow is list of powers of different factor of form (a*x b).
# reference from table 1 in paper - "Non-Liouvillian solutions for second order
# linear ODEs" by L. Chan, E.S. Cheb-Terrab.
# We can extend it for 1F1 and 0F1 type also.
if max_num_pow == 2:
if dem_pow in [[2, 2], [2, 2, 2]]:
return "2F1"
elif max_num_pow == 1:
if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]:
return "2F1"
elif max_num_pow == 0:
if dem_pow in [[1, 1, 2], [2, 2], [1 ,2, 2], [1, 1], [2], [1, 2], [2, 2]]:
return "2F1"
return None
def equivalence_hypergeometric(A, B, func):
from sympy import factor
# This method for finding the equivalence is only for 2F1 type.
# We can extend it for 1F1 and 0F1 type also.
x = func.args[0]
# making given equation in normal form
I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B))
# computing shifted invariant(J1) of the equation
J1 = factor(cancel(x**2*I1 + S(1)/4))
num, dem = J1.as_numer_denom()
num = powdenest(expand(num))
dem = powdenest(expand(dem))
pow_num = set()
pow_dem = set()
# this function will compute the different powers of variable(x) in J1.
# then it will help in finding value of k. k is power of x such that we can express
# J1 = x**k * J0(x**k) then all the powers in J0 become integers.
def _power_counting(num):
_pow = {0}
for val in num:
if val.has(x):
if isinstance(val, Pow) and val.as_base_exp()[0] == x:
_pow.add(val.as_base_exp()[1])
elif val == x:
_pow.add(val.as_base_exp()[1])
else:
_pow.update(_power_counting(val.args))
return _pow
pow_num = _power_counting((num, ))
pow_dem = _power_counting((dem, ))
pow_dem.update(pow_num)
_pow = pow_dem
k = gcd(_pow)
# computing I0 of the given equation
I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True)
I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True)))
num, dem = I0.as_numer_denom()
max_num_pow = max(_power_counting((num, )))
dem_args = dem.args
sing_point = []
dem_pow = []
# calculating singular point of I0.
for arg in dem_args:
if arg.has(x):
if isinstance(arg, Pow):
# (x-a)**n
dem_pow.append(arg.as_base_exp()[1])
sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0])
else:
# (x-a) type
dem_pow.append(arg.as_base_exp()[1])
sing_point.append(list(roots(arg, x).keys())[0])
dem_pow.sort()
# checking if equivalence is exists or not.
if equivalence(max_num_pow, dem_pow) == "2F1":
return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"}
else:
return None
def ode_2nd_hypergeometric(eq, func, order, match):
from sympy.simplify.hyperexpand import hyperexpand
from sympy import factor
x = func.args[0]
C0, C1 = get_numbered_constants(eq, num=2)
a = match['a']
b = match['b']
c = match['c']
A = match['A']
# B = match['B']
sol = None
if match['type'] == "2F1":
if c.is_integer == False:
sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c)
elif c == 1:
y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x)
sol = C0*hyper([a, b], [c], x) + C1*y2
elif (c-a-b).is_integer == False:
sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b)
if sol is None:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the hypergeometric method")
# applying transformation in the solution
subs = match['mobius']
dtdx = simplify(1/(subs.diff(x)))
_B = ((a + b + 1)*x - c).subs(x, subs)*dtdx
_B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx))
_A = factor((x**2 - x).subs(x, subs)*(dtdx**2))
e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True))
sol = sol.subs(x, match['mobius'])
sol = sol.subs(x, x**match['k'])
e = e.subs(x, x**match['k'])
if not A.is_zero:
e1 = Integral(A/2, x)
e1 = exp(logcombine(e1, force=True))
sol = cancel((e/e1)*x**((-match['k']+1)/2))*sol
sol = Eq(func, sol)
return sol
sol = cancel((e)*x**((-match['k']+1)/2))*sol
sol = Eq(func, sol)
return sol
def match_2nd_2F1_hypergeometric(I, k, sing_point, func):
from sympy import factor
x = func.args[0]
a = Wild("a")
b = Wild("b")
c = Wild("c")
t = Wild("t")
s = Wild("s")
r = Wild("r")
alpha = Wild("alpha")
beta = Wild("beta")
gamma = Wild("gamma")
delta = Wild("delta")
rn = {'type':None}
# I0 of the standerd 2F1 equation.
I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2)
if sing_point != [0, 1]:
# If singular point is [0, 1] then we have standerd equation.
eqs = []
sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)]
# making equations for the finding the mobius transformation
for i in range(3):
if i<len(sing_point):
eqs.append(Eq(sing_eqs[i], sing_point[i]))
else:
eqs.append(Eq(1/sing_eqs[i], 0))
# solving above equations for the mobius transformation
_beta = -alpha*sing_point[0]
_delta = -gamma*sing_point[1]
_gamma = alpha
if len(sing_point) == 3:
_gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1])
mob = (alpha*x + beta)/(gamma*x + delta)
mob = mob.subs(beta, _beta)
mob = mob.subs(delta, _delta)
mob = mob.subs(gamma, _gamma)
mob = cancel(mob)
t = (beta - delta*x)/(gamma*x - alpha)
t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma))
else:
mob = x
t = x
# applying mobius transformation in I to make it into I0.
I = I.subs(x, t)
I = I*(t.diff(x))**2
I = factor(I)
dict_I = {x**2:0, x:0, 1:0}
I0_num, I0_dem = I0.as_numer_denom()
# collecting coeff of (x**2, x), of the standerd equation.
# substituting (a-b) = s, (a+b) = r
dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)}
# collecting coeff of (x**2, x) from I0 of the given equation.
dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False))
eqs = []
# We are comparing the coeff of powers of different x, for finding the values of
# parameters of standerd equation.
for key in [x**2, x, 1]:
eqs.append(Eq(dict_I[key], dict_I0[key]))
# We can have many possible roots for the equation.
# I am selecting the root on the basis that when we have
# standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x)
# then root should be a, b, c.
_c = 1 - factor(sqrt(1+eqs[2].lhs))
if not _c.has(Symbol):
_c = min(list(roots(eqs[2], c)))
_s = factor(sqrt(eqs[0].lhs + 1))
_r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c))
_a = (_r + _s)/2
_b = (_r - _s)/2
rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"}
return rn
def match_2nd_hypergeometric(r, func):
x = func.args[0]
a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)])
b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)])
c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)])
A = cancel(r[b3]/r[a3])
B = cancel(r[c3]/r[a3])
d = equivalence_hypergeometric(A, B, func)
rn = None
if d:
if d['type'] == "2F1":
rn = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func)
if rn is not None:
rn.update({'A':A, 'B':B})
# We can extend it for 1F1 and 0F1 type also.
return rn
def match_2nd_linear_bessel(r, func):
from sympy.polys.polytools import factor
# eq = a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3*f(x)
f = func
x = func.args[0]
df = f.diff(x)
a = Wild('a', exclude=[f,df])
b = Wild('b', exclude=[x, f,df])
a4 = Wild('a4', exclude=[x,f,df])
b4 = Wild('b4', exclude=[x,f,df])
c4 = Wild('c4', exclude=[x,f,df])
d4 = Wild('d4', exclude=[x,f,df])
a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)])
b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)])
c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)])
# leading coeff of f(x).diff(x, 2)
coeff = factor(r[a3]).match(a4*(x-b)**b4)
if coeff:
# if coeff[b4] = 0 means constant coefficient
if coeff[b4] == 0:
return None
point = coeff[b]
else:
return None
if point:
r[a3] = simplify(r[a3].subs(x, x+point))
r[b3] = simplify(r[b3].subs(x, x+point))
r[c3] = simplify(r[c3].subs(x, x+point))
# making a3 in the form of x**2
r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4])))
# checking if b3 is of form c*(x-b)
coeff1 = factor(r[b3]).match(a4*(x))
if coeff1 is None:
return None
# c3 maybe of very complex form so I am simply checking (a - b) form
# if yes later I will match with the standerd form of bessel in a and b
# a, b are wild variable defined above.
_coeff2 = r[c3].match(a - b)
if _coeff2 is None:
return None
# matching with standerd form for c3
coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4))
if coeff2 is None:
return None
if _coeff2[b] == 0:
coeff2[d4] = 0
else:
coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4]
rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]}
rn['c4'] = coeff1[a4]
rn['b4'] = point
return rn
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
Some parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number,
function, order)```. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving. The value of this parameter can also be a Matrix if the system of ODEs are
linear first order of the form X' = AX where X is the vector of dependent variables.
Here, this function returns the coefficient matrix A.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
'is_constant' (boolean), which tells if the system of ODEs is constant coefficient
or not. This key is temporary addition for now and is in the match dict only when
the system of ODEs is linear first order constant coefficient homogeneous. So, this
key's value is True for now if it is available else it doesn't exist.
'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the
key 'is_constant', this key is a temporary addition and it is True since this key value
is available only when the system is linear first order constant coefficient homogeneous.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
-A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
Examples
========
>>> from sympy import Function, Eq, symbols, diff
>>> from sympy.solvers.ode.ode import classify_sysode
>>> from sympy.abc import t
>>> f, x, y = symbols('f, x, y', cls=Function)
>>> k, l, m, n = symbols('k, l, m, n', Integer=True)
>>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
>>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
>>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t)))
>>> classify_sysode(eq)
{'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)],
'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
>>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0,
(1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2,
'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
matching_hints = {"no_of_equation":i+1}
matching_hints['eq'] = eq
if i==0:
raise ValueError("classify_sysode() works for systems of ODEs. "
"For scalar ODEs, classify_ode should be used")
# find all the functions if not given
order = dict()
if funcs==[None]:
funcs = _extract_funcs(eq)
funcs = list(set(funcs))
if len(funcs) != len(eq):
raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
# This logic of list of lists in funcs to
# be replaced later.
func_dict = dict()
for func in funcs:
if not order.get(func, False):
max_order = 0
for i, eqs_ in enumerate(eq):
order_ = ode_order(eqs_,func)
if max_order < order_:
max_order = order_
eq_no = i
if eq_no in func_dict:
func_dict[eq_no] = [func_dict[eq_no], func]
else:
func_dict[eq_no] = func
order[func] = max_order
funcs = [func_dict[i] for i in range(len(func_dict))]
matching_hints['func'] = funcs
for func in funcs:
if isinstance(func, list):
for func_elem in func:
if len(func_elem.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
else:
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# find the order of all equation in system of odes
matching_hints["order"] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func] + 1):
func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k))
if is_linear_ == True:
if func_coef[j, func, k] == 0:
if k == 0:
coef = eqs.as_independent(func, as_Add=True)[1]
for xr in range(1, ode_order(eqs,func) + 1):
coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func, t, k), as_Add=True)[1]:
is_linear_ = False
else:
for func_ in funcs:
if isinstance(func_, list):
for elem_func_ in func_:
dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
else:
dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
if isinstance(func, list):
for func_elem in func:
is_linear = linearity_check(eqs, j, func_elem, is_linear)
else:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
if len(set(order.values())) == 1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear'] == True:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
# If the equation doesn't match up with any of the
# general case solvers in systems.py and the number
# of equations is greater than 2, then NotImplementedError
# should be raised.
else:
type_of_equation = None
else:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
type_of_equation = None
else:
type_of_equation = None
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S.Zero,S.Zero]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
# We can handle homogeneous case and simple constant forcings
r['d1'] = forcing[0]
r['d2'] = forcing[1]
else:
# Issue #9244: nonhomogeneous linear systems are not supported
return None
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n==0:
if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n==1:
if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
if r['d1']!=0 or r['d2']!=0:
return None
else:
if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
return None
else:
r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2']
r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2']
if p:
return "type6"
else:
# Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
return "type7"
def check_nonlinear_2eq_order1(eq, func, func_coef):
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
f = Wild('f')
g = Wild('g')
u, v = symbols('u, v', cls=Dummy)
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \
or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)):
return 'type5'
else:
return None
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
eq_type = check_type(x, y)
if not eq_type:
eq_type = check_type(y, x)
return eq_type
x = func[0].func
y = func[1].func
fc = func_coef
n = Wild('n', exclude=[x(t),y(t)])
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type1'
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type2'
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \
r2[g].subs(x(t),u).subs(y(t),v).has(t)):
return 'type3'
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
# phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
if R1 and R2:
return 'type4'
return None
def check_nonlinear_2eq_order2(eq, func, func_coef):
return None
def check_nonlinear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v, w = symbols('u, v, w', cls=Dummy)
a = Wild('a', exclude=[x(t), y(t), z(t), t])
b = Wild('b', exclude=[x(t), y(t), z(t), t])
c = Wild('c', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
F1 = Wild('F1')
F2 = Wild('F2')
F3 = Wild('F3')
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t))
r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t))
r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type1'
r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f)
if r:
r1 = collect_const(r[f]).match(a*f)
r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t))
r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type2'
r = eq[0].match(diff(x(t),t) - (F2-F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1)
if r2:
r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2])
if r1 and r2 and r3:
return 'type3'
r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1)
if r2:
r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2])
if r1 and r2 and r3:
return 'type4'
r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1))
if r2:
r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2]))
if r1 and r2 and r3:
return 'type5'
return None
def check_nonlinear_3eq_order2(eq, func, func_coef):
return None
@vectorize(0)
def odesimp(ode, eq, func, hint):
r"""
Simplifies solutions of ODEs, including trying to solve for ``func`` and
running :py:meth:`~sympy.solvers.ode.constantsimp`.
It may use knowledge of the type of solution that the hint returns to
apply additional simplifications.
It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s
in the expression, if the hint is not an ``_Integral`` hint.
This function should have no effect on expressions returned by
:py:meth:`~sympy.solvers.ode.dsolve`, as
:py:meth:`~sympy.solvers.ode.dsolve` already calls
:py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions
do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the
:py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this
function is designed for mainly internal use.
Examples
========
>>> from sympy import sin, symbols, dsolve, pprint, Function
>>> from sympy.solvers.ode.ode import odesimp
>>> x , u2, C1= symbols('x,u2,C1')
>>> f = Function('f')
>>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
... simplify=False)
>>> pprint(eq, wrap_line=False)
x
----
f(x)
/
|
| / 1 \
| -|u2 + -------|
| | /1 \|
| | sin|--||
| \ \u2//
log(f(x)) = log(C1) + | ---------------- d(u2)
| 2
| u2
|
/
>>> pprint(odesimp(eq, f(x), 1, {C1},
... hint='1st_homogeneous_coeff_subs_indep_div_dep'
... )) #doctest: +SKIP
x
--------- = C1
/f(x)\
tan|----|
\2*x /
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
constants = eq.free_symbols - ode.free_symbols
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, hint)
if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError("eq should be an instance of Equality")
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When CRootOf is implemented in solve(), we will want to return a CRootOf
# every time instead of an Equality.
# Get the f(x) on the left if possible.
if eq.rhs == func and not eq.lhs.has(func):
eq = [Eq(eq.rhs, eq.lhs)]
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
# special simplification of the rhs
if hint.startswith("nth_linear_constant_coeff"):
# Collect terms to make the solution look nice.
# This is also necessary for constantsimp to remove unnecessary
# terms from the particular solution from variation of parameters
#
# Collect is not behaving reliably here. The results for
# some linear constant-coefficient equations with repeated
# roots do not properly simplify all constants sometimes.
# 'collectterms' gives different orders sometimes, and results
# differ in collect based on that order. The
# sort-reverse trick fixes things, but may fail in the
# future. In addition, collect is splitting exponentials with
# rational powers for no reason. We have to do a match
# to fix this using Wilds.
#
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms.sort(key=default_sort_key)
collectterms.reverse()
assert len(eq) == 1 and eq[0].lhs == f(x)
sol = eq[0].rhs
sol = expand_mul(sol)
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x))
del collectterms
# Collect is splitting exponentials with rational powers for
# no reason. We call powsimp to fix.
sol = powsimp(sol)
eq[0] = Eq(f(x), sol)
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, force=True, rational=False if floats else None)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
numer, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t)) for t in eqsol]
# special simplification of the lhs.
if hint.startswith("1st_homogeneous_coeff"):
for j, eqi in enumerate(eq):
newi = logcombine(eqi, force=True)
if isinstance(newi.lhs, log) and newi.rhs == 0:
newi = Eq(newi.lhs.args[0]/C1, C1)
eq[j] = newi
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], ode.free_symbols)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+----------------------------------------------+-------------------+
| Simplicity | Return |
+==============================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+----------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+----------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+----------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :obj:`~sympy.integrals.integrals.Integral` | |
+----------------------------------------------+-------------------+
``oo`` here means the SymPy infinity, which should compare greater than
any integer.
If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> from sympy import symbols, Function, Eq, tan, Integral
>>> from sympy.solvers.ode.ode import ode_sol_simplicity
>>> x, C1, C2 = symbols('x, C1, C2')
>>> f = Function('f')
>>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
-2
>>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
-1
>>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
oo
>>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
>>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
>>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
[28, 35]
>>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
Eq(f(x)/tan(f(x)/(2*x)), C1)
"""
# TODO: if two solutions are solved for f(x), we still want to be
# able to get the simpler of the two
# See the docstring for the coercion rules. We check easier (faster)
# things here first, to save time.
if iterable(sol):
# See if there are Integrals
for i in sol:
if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
return oo
return len(str(sol))
if sol.has(Integral):
return oo
# Next, try to solve for func. This code will change slightly when CRootOf
# is implemented in solve(). Probably a CRootOf solution should fall
# somewhere between a normal solution and an unsolvable expression.
# First, see if they are already solved
if sol.lhs == func and not sol.rhs.has(func) or \
sol.rhs == func and not sol.lhs.has(func):
return -2
# We are not so lucky, try solving manually
if trysolving:
try:
sols = solve(sol, func)
if not sols:
raise NotImplementedError
except NotImplementedError:
pass
else:
return -1
# Finally, a naive computation based on the length of the string version
# of the expression. This may favor combined fractions because they
# will not have duplicate denominators, and may slightly favor expressions
# with fewer additions and subtractions, as those are separated by spaces
# by the printer.
# Additional ideas for simplicity heuristics are welcome, like maybe
# checking if a equation has a larger domain, or if constantsimp has
# introduced arbitrary constants numbered higher than the order of a
# given ODE that sol is a solution of.
return len(str(sol))
def _extract_funcs(eqs):
from sympy.core.basic import preorder_traversal
funcs = []
for eq in eqs:
derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)]
func = []
for d in derivs:
func += list(d.atoms(AppliedUndef))
for func_ in func:
funcs.append(func_)
funcs = list(uniq(funcs))
return funcs
def _get_constant_subexpressions(expr, Cs):
Cs = set(Cs)
Ces = []
def _recursive_walk(expr):
expr_syms = expr.free_symbols
if expr_syms and expr_syms.issubset(Cs):
Ces.append(expr)
else:
if expr.func == exp:
expr = expr.expand(mul=True)
if expr.func in (Add, Mul):
d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs))
if len(d[True]) > 1:
x = expr.func(*d[True])
if not x.is_number:
Ces.append(x)
elif isinstance(expr, Integral):
if expr.free_symbols.issubset(Cs) and \
all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
return
_recursive_walk(expr)
return Ces
def __remove_linear_redundancies(expr, Cs):
cnts = {i: expr.count(i) for i in Cs}
Cs = [i for i in Cs if cnts[i] > 0]
def _linear(expr):
if isinstance(expr, Add):
xs = [i for i in Cs if expr.count(i)==cnts[i] \
and 0 == expr.diff(i, 2)]
d = {}
for x in xs:
y = expr.diff(x)
if y not in d:
d[y]=[]
d[y].append(x)
for y in d:
if len(d[y]) > 1:
d[y].sort(key=str)
for x in d[y][1:]:
expr = expr.subs(x, 0)
return expr
def _recursive_walk(expr):
if len(expr.args) != 0:
expr = expr.func(*[_recursive_walk(i) for i in expr.args])
expr = _linear(expr)
return expr
if isinstance(expr, Equality):
lhs, rhs = [_recursive_walk(i) for i in expr.args]
f = lambda i: isinstance(i, Number) or i in Cs
if isinstance(lhs, Symbol) and lhs in Cs:
rhs, lhs = lhs, rhs
if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
for i in [True, False]:
for hs in [dlhs, drhs]:
if i not in hs:
hs[i] = [0]
# this calculation can be simplified
lhs = Add(*dlhs[False]) - Add(*drhs[False])
rhs = Add(*drhs[True]) - Add(*dlhs[True])
elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
if True in dlhs:
if False not in dlhs:
dlhs[False] = [1]
lhs = Mul(*dlhs[False])
rhs = rhs/Mul(*dlhs[True])
return Eq(lhs, rhs)
else:
return _recursive_walk(expr)
@vectorize(0)
def constantsimp(expr, constants):
r"""
Simplifies an expression with arbitrary constants in it.
This function is written specifically to work with
:py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use.
Simplification is done by "absorbing" the arbitrary constants into other
arbitrary constants, numbers, and symbols that they are not independent
of.
The symbols must all have the same name with numbers after it, for
example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
'``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
If the arbitrary constants are independent of the variable ``x``, then the
independent symbol would be ``x``. There is no need to specify the
dependent function, such as ``f(x)``, because it already has the
independent symbol, ``x``, in it.
Because terms are "absorbed" into arbitrary constants and because
constants are renumbered after simplifying, the arbitrary constants in
expr are not necessarily equal to the ones of the same name in the
returned result.
If two or more arbitrary constants are added, multiplied, or raised to the
power of each other, they are first absorbed together into a single
arbitrary constant. Then the new constant is combined into other terms if
necessary.
Absorption of constants is done with limited assistance:
1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join
constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
C_1 \cos(x)`;
2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are
expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants
after simplification or else arbitrary numbers on constants may appear,
e.g. `C_1 + C_3 x`.
In rare cases, a single constant can be "simplified" into two constants.
Every differential equation solution should have as many arbitrary
constants as the order of the differential equation. The result here will
be technically correct, but it may, for example, have `C_1` and `C_2` in
an expression, when `C_1` is actually equal to `C_2`. Use your discretion
in such situations, and also take advantage of the ability to use hints in
:py:meth:`~sympy.solvers.ode.dsolve`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode.ode import constantsimp
>>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y')
>>> constantsimp(2*C1*x, {C1, C2, C3})
C1*x
>>> constantsimp(C1 + 2 + x, {C1, C2, C3})
C1 + x
>>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3})
C1 + C3*x
"""
# This function works recursively. The idea is that, for Mul,
# Add, Pow, and Function, if the class has a constant in it, then
# we can simplify it, which we do by recursing down and
# simplifying up. Otherwise, we can skip that part of the
# expression.
Cs = constants
orig_expr = expr
constant_subexprs = _get_constant_subexpressions(expr, Cs)
for xe in constant_subexprs:
xes = list(xe.free_symbols)
if not xes:
continue
if all([expr.count(c) == xe.count(c) for c in xes]):
xes.sort(key=str)
expr = expr.subs(xe, xes[0])
# try to perform common sub-expression elimination of constant terms
try:
commons, rexpr = cse(expr)
commons.reverse()
rexpr = rexpr[0]
for s in commons:
cs = list(s[1].atoms(Symbol))
if len(cs) == 1 and cs[0] in Cs and \
cs[0] not in rexpr.atoms(Symbol) and \
not any(cs[0] in ex for ex in commons if ex != s):
rexpr = rexpr.subs(s[0], cs[0])
else:
rexpr = rexpr.subs(*s)
expr = rexpr
except IndexError:
pass
expr = __remove_linear_redundancies(expr, Cs)
def _conditional_term_factoring(expr):
new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
# we do not want to factor exponentials, so handle this separately
if new_expr.is_Mul:
infac = False
asfac = False
for m in new_expr.args:
if isinstance(m, exp):
asfac = True
elif m.is_Add:
infac = any(isinstance(fi, exp) for t in m.args
for fi in Mul.make_args(t))
if asfac and infac:
new_expr = expr
break
return new_expr
expr = _conditional_term_factoring(expr)
# call recursively if more simplification is possible
if orig_expr != expr:
return constantsimp(expr, Cs)
return expr
def constant_renumber(expr, variables=None, newconstants=None):
r"""
Renumber arbitrary constants in ``expr`` to use the symbol names as given
in ``newconstants``. In the process, this reorders expression terms in a
standard way.
If ``newconstants`` is not provided then the new constant names will be
``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable
giving the new symbols to use for the constants in order.
The ``variables`` argument is a list of non-constant symbols. All other
free symbols found in ``expr`` are assumed to be constants and will be
renumbered. If ``variables`` is not given then any numbered symbol
beginning with ``C`` (e.g. ``C1``) is assumed to be a constant.
Symbols are renumbered based on ``.sort_key()``, so they should be
numbered roughly in the order that they appear in the final, printed
expression. Note that this ordering is based in part on hashes, so it can
produce different results on different machines.
The structure of this function is very similar to that of
:py:meth:`~sympy.solvers.ode.constantsimp`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode.ode import constant_renumber
>>> x, C1, C2, C3 = symbols('x,C1:4')
>>> expr = C3 + C2*x + C1*x**2
>>> expr
C1*x**2 + C2*x + C3
>>> constant_renumber(expr)
C1 + C2*x + C3*x**2
The ``variables`` argument specifies which are constants so that the
other symbols will not be renumbered:
>>> constant_renumber(expr, [C1, x])
C1*x**2 + C2 + C3*x
The ``newconstants`` argument is used to specify what symbols to use when
replacing the constants:
>>> constant_renumber(expr, [x], newconstants=symbols('E1:4'))
E1 + E2*x + E3*x**2
"""
# System of expressions
if isinstance(expr, (set, list, tuple)):
return type(expr)(constant_renumber(Tuple(*expr),
variables=variables, newconstants=newconstants))
# Symbols in solution but not ODE are constants
if variables is not None:
variables = set(variables)
free_symbols = expr.free_symbols
constantsymbols = list(free_symbols - variables)
# Any Cn is a constant...
else:
variables = set()
isconstant = lambda s: s.startswith('C') and s[1:].isdigit()
constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)]
# Find new constants checking that they aren't already in the ODE
if newconstants is None:
iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables)
else:
iter_constants = (sym for sym in newconstants if sym not in variables)
constants_found = []
# make a mapping to send all constantsymbols to S.One and use
# that to make sure that term ordering is not dependent on
# the indexed value of C
C_1 = [(ci, S.One) for ci in constantsymbols]
sort_key=lambda arg: default_sort_key(arg.subs(C_1))
def _constant_renumber(expr):
r"""
We need to have an internal recursive function
"""
# For system of expressions
if isinstance(expr, Tuple):
renumbered = [_constant_renumber(e) for e in expr]
return Tuple(*renumbered)
if isinstance(expr, Equality):
return Eq(
_constant_renumber(expr.lhs),
_constant_renumber(expr.rhs))
if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
not expr.has(*constantsymbols):
# Base case, as above. Hope there aren't constants inside
# of some other class, because they won't be renumbered.
return expr
elif expr.is_Piecewise:
return expr
elif expr in constantsymbols:
if expr not in constants_found:
constants_found.append(expr)
return expr
elif expr.is_Function or expr.is_Pow:
return expr.func(
*[_constant_renumber(x) for x in expr.args])
else:
sortedargs = list(expr.args)
sortedargs.sort(key=sort_key)
return expr.func(*[_constant_renumber(x) for x in sortedargs])
expr = _constant_renumber(expr)
# Don't renumber symbols present in the ODE.
constants_found = [c for c in constants_found if c not in variables]
# Renumbering happens here
subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)}
expr = expr.subs(subs_dict, simultaneous=True)
return expr
def _handle_Integral(expr, func, hint):
r"""
Converts a solution with Integrals in it into an actual solution.
For most hints, this simply runs ``expr.doit()``.
"""
# XXX: This global y hack should be removed
global y
x = func.args[0]
f = func.func
if hint == "1st_exact":
sol = (expr.doit()).subs(y, f(x))
del y
elif hint == "1st_exact_Integral":
sol = Eq(Subs(expr.lhs, y, f(x)), expr.rhs)
del y
elif hint == "nth_linear_constant_coeff_homogeneous":
sol = expr
elif not hint.endswith("_Integral"):
sol = expr.doit()
else:
sol = expr
return sol
# FIXME: replace the general solution in the docstring with
# dsolve(equation, hint='1st_exact_Integral'). You will need to be able
# to have assumptions on P and Q that dP/dy = dQ/dx.
def ode_1st_exact(eq, func, order, match):
r"""
Solves 1st order exact ordinary differential equations.
A 1st order differential equation is called exact if it is the total
differential of a function. That is, the differential equation
.. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0
is exact if there is some function `F(x, y)` such that `P(x, y) =
\partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can
be shown that a necessary and sufficient condition for a first order ODE
to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`.
Then, the solution will be as given below::
>>> from sympy import Function, Eq, Integral, symbols, pprint
>>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1')
>>> P, Q, F= map(Function, ['P', 'Q', 'F'])
>>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) +
... Integral(Q(x0, t), (t, y0, y))), C1))
x y
/ /
| |
F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1
| |
/ /
x0 y0
Where the first partials of `P` and `Q` exist and are continuous in a
simply connected region.
A note: SymPy currently has no way to represent inert substitution on an
expression, so the hint ``1st_exact_Integral`` will return an integral
with `dy`. This is supposed to represent the function that you are
solving for.
Examples
========
>>> from sympy import Function, dsolve, cos, sin
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
... f(x), hint='1st_exact')
Eq(x*cos(f(x)) + f(x)**3/3, C1)
References
==========
- https://en.wikipedia.org/wiki/Exact_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 73
# indirect doctest
"""
x = func.args[0]
r = match # d+e*diff(f(x),x)
e = r[r['e']]
d = r[r['d']]
# XXX: This global y hack should be removed
global y # This is the only way to pass dummy y to _handle_Integral
y = r['y']
C1 = get_numbered_constants(eq, num=1)
# Refer Joel Moses, "Symbolic Integration - The Stormy Decade",
# Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558
# which gives the method to solve an exact differential equation.
sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y)
return Eq(sol, C1)
def ode_1st_homogeneous_coeff_best(eq, func, order, match):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# They produce different integrals, so try them both and see which
# one is easier.
sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq,
func, order, match)
sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq,
func, order, match)
simplify = match.get('simplify', True)
if simplify:
# why is odesimp called here? Should it be at the usual spot?
sol1 = odesimp(eq, sol1, func, "1st_homogeneous_coeff_subs_indep_div_dep")
sol2 = odesimp(eq, sol2, func, "1st_homogeneous_coeff_subs_dep_div_indep")
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func,
trysolving=not simplify))
def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'))
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`.
Examples
========
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False))
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u1 = Dummy('u1') # u1 == f(x)/x
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0)
yarg = match.get('yarg', 0)
int = Integral(
(-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}),
(u1, None, f(x)/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'))
x
----
f(x)
/
|
| -g(u2)
| ---------------- d(u2)
| u2*g(u2) + h(u2)
|
/
<BLANKLINE>
f(x) = C1*e
Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`.
Examples
========
>>> from sympy import Function, pprint, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u2 = Dummy('u2') # u2 == x/f(x)
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0) # If xarg present take xarg, else zero
yarg = match.get('yarg', 0) # If yarg present take yarg, else zero
int = Integral(
simplify(
(-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})),
(u2, None, x/f(x)))
sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> from sympy import Function, homogeneous_order, sqrt
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x,y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError("homogeneous_order: no symbols were given.")
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return None
# These are all constants
if (eq.is_Number or
eq.is_NumberSymbol or
eq.is_number
):
return S.Zero
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return None
else:
dummyvar = next(dum)
eq = eq.subs(i, dummyvar)
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return None
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else S.Zero
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
if eqs is S.One:
return S.Zero # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_Liouville(eq, func, order, match):
r"""
Solves 2nd order Liouville differential equations.
The general form of a Liouville ODE is
.. math:: \frac{d^2 y}{dx^2} + g(y) \left(\!
\frac{dy}{dx}\!\right)^2 + h(x)
\frac{dy}{dx}\text{.}
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint, diff
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 +
... h(x)*diff(f(x),x), 0)
>>> pprint(genform)
2 2
/d \ d d
g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0
\dx / dx 2
dx
>>> pprint(dsolve(genform, f(x), hint='Liouville_Integral'))
f(x)
/ /
| |
| / | /
| | | |
| - | h(x) dx | | g(y) dy
| | | |
| / | /
C1 + C2* | e dx + | e dy = 0
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) +
... diff(f(x), x)/x, f(x), hint='Liouville'))
________________ ________________
[f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ]
References
==========
- Goldstein and Braun, "Advanced Methods for the Solution of Differential
Equations", pp. 98
- http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville
# indirect doctest
"""
# Liouville ODE:
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x, 2))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98, as well as
# http://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville
x = func.args[0]
f = func.func
r = match # f(x).diff(x, 2) + g*f(x).diff(x)**2 + h*f(x).diff(x)
y = r['y']
C1, C2 = get_numbered_constants(eq, num=2)
int = Integral(exp(Integral(r['g'], y)), (y, None, f(x)))
sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0)
return sol
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogeneous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
/ 4 2 \ / 2\
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x /
\24 2 / \ 6 /
References
==========
- http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n", integer=True)
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function("r")
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs(n, n - powm[k].as_independent(n)[0])
startind = powm[k].subs(n, index)
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs(n, i):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = S.Zero
# Stripping of terms so that the sum starts with the same number.
teq = S.Zero
suminit = seriesdict.values()
rkeys = seriesdict.keys()
req = Add(*rkeys)
if any(suminit):
maxval = max(suminit)
for term in seriesdict:
val = seriesdict[term]
if val != maxval:
for i in range(val, maxval):
teq += term.subs(n, val)
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key = lambda x: x.args[0])
sol = solve(teq, maxf)
if isinstance(sol, list):
sol = sol[0]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key = lambda x: x.args[0])
minf = min(fargs, key = lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
if isinstance(rhs, list):
rhs = rhs[0]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs(n, startiter)
nlhs = lhs.subs(n, startiter)
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term in finaldict:
if finaldict[term]:
fact = term.args[0]
series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_linear_airy(eq, func, order, match):
r"""
Gives solution of the Airy differential equation
.. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0
in terms of Airy special functions airyai and airybi.
Examples
========
>>> from sympy import dsolve, Function
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) - x*f(x)
>>> dsolve(eq)
Eq(f(x), C1*airyai(x) + C2*airybi(x))
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
b = match['b']
m = match['m']
if m.is_positive:
arg = - b/cbrt(m)**2 - cbrt(m)*x
elif m.is_negative:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
else:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
return Eq(f(x), C0*airyai(arg) + C1*airybi(arg))
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogeneous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_regular'))
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
m = Dummy("m") # for solving the indicial equation
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = series(term, n=1, x0=x0)
if isinstance(term, Order):
indicial.append(S.Zero)
else:
for arg in term.args:
if not arg.has(x):
indicial.append(arg)
break
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and isinstance(sollist, list) and all(
[sol.is_real for sol in sollist]):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m1 = sollist[0]
m2 = sollist[1]
if m1 < m2:
m1, m2 = m2, m1
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
if serdict1:
finalseries1 = C0
for key in serdict1:
power = int(key.name[1:])
finalseries1 += serdict1[key]*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = S.Zero
if serdict2:
for key in serdict2:
power = int(key.name[1:])
finalseries2 += serdict2[key]*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
def ode_2nd_linear_bessel(eq, func, order, match):
r"""
Gives solution of the Bessel differential equation
.. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x)
if n is integer then the solution is of the form Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x)) as both the solutions are linearly independent else if
n is a fraction then the solution is of the form Eq(f(x), C0 besselj(n,x)
+ C1 besselj(-n,x)) which can also transform into Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x)).
Examples
========
>>> from sympy.abc import x
>>> from sympy import Symbol
>>> v = Symbol('v', positive=True)
>>> from sympy.solvers.ode import dsolve
>>> from sympy import Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y
>>> dsolve(genform)
Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x))
References
==========
https://www.math24.net/bessel-differential-equation/
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = match['n']
a4 = match['a4']
c4 = match['c4']
d4 = match['d4']
b4 = match['b4']
n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2)
return Eq(f(x), ((x**(Rational(1-c4,2)))*(C0*besselj(n/d4,a4*x**d4/d4)
+ C1*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4))
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy("d")
numsyms = numbered_symbols("C", start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
serlist = []
for ser in [p, q]:
# Order term not present
if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
if x0:
ser = ser.subs(x, x + x0)
dict_ = Poly(ser, x).as_dict()
# Order term present
else:
tseries = series(ser, x=x0, n=n+1)
# Removing order
dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = S.Zero
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol("C" + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
return False
else:
frobdict[numsyms[i]] = S.Zero
else:
frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
return frobdict
def _nth_order_reducible_match(eq, func):
r"""
Matches any differential equation that can be rewritten with a smaller
order. Only derivatives of ``func`` alone, wrt a single variable,
are considered, and only in them should ``func`` appear.
"""
# ODE only handles functions of 1 variable so this affirms that state
assert len(func.args) == 1
x = func.args[0]
vc = [d.variable_count[0] for d in eq.atoms(Derivative)
if d.expr == func and len(d.variable_count) == 1]
ords = [c for v, c in vc if v == x]
if len(ords) < 2:
return
smallest = min(ords)
# make sure func does not appear outside of derivatives
D = Dummy()
if eq.subs(func.diff(x, smallest), D).has(func):
return
return {'n': smallest}
def ode_nth_order_reducible(eq, func, order, match):
r"""
Solves ODEs that only involve derivatives of the dependent variable using
a substitution of the form `f^n(x) = g(x)`.
For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be
transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and
`f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If
that gives an explicit solution for `g` then `f` is found simply by
integration.
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0)
>>> dsolve(eq, f(x), hint='nth_order_reducible')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))
"""
x = func.args[0]
f = func.func
n = match['n']
# get a unique function name for g
names = [a.name for a in eq.atoms(AppliedUndef)]
while True:
name = Dummy().name
if name not in names:
g = Function(name)
break
w = f(x).diff(x, n)
geq = eq.subs(w, g(x))
gsol = dsolve(geq, g(x))
if not isinstance(gsol, list):
gsol = [gsol]
# Might be multiple solutions to the reduced ODE:
fsol = []
for gsoli in gsol:
fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times
fsol.append(fsoli)
if len(fsol) == 1:
fsol = fsol[0]
return fsol
def _remove_redundant_solutions(eq, solns, order, var):
r"""
Remove redundant solutions from the set of solutions.
This function is needed because otherwise dsolve can return
redundant solutions. As an example consider:
eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0)
There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0
leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0
leading to the solution f(x) = C1. In this particular case we then see
that the second solution is a special case of the first and we don't
want to return it.
This does not always happen. If we have
eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0)
then we get the algebraic solution f(x) = [-2, 2] and the integral solution
f(x) = x + C1 and in this case the two solutions are not equivalent wrt
initial conditions so both should be returned.
"""
def is_special_case_of(soln1, soln2):
return _is_special_case_of(soln1, soln2, eq, order, var)
unique_solns = []
for soln1 in solns:
for soln2 in unique_solns[:]:
if is_special_case_of(soln1, soln2):
break
elif is_special_case_of(soln2, soln1):
unique_solns.remove(soln2)
else:
unique_solns.append(soln1)
return unique_solns
def _is_special_case_of(soln1, soln2, eq, order, var):
r"""
True if soln1 is found to be a special case of soln2 wrt some value of the
constants that appear in soln2. False otherwise.
"""
# The solutions returned by dsolve may be given explicitly or implicitly.
# We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs)
# of the two solutions.
#
# Since this is supposed to hold for all x it also holds for derivatives.
# For an order n ode we should be able to differentiate
# each solution n times to get n+1 equations.
#
# We then try to solve those n+1 equations for the integrations constants
# in sol2. If we can find a solution that doesn't depend on x then it
# means that some value of the constants in sol1 is a special case of
# sol2 corresponding to a particular choice of the integration constants.
# In case the solution is in implicit form we subtract the sides
soln1 = soln1.rhs - soln1.lhs
soln2 = soln2.rhs - soln2.lhs
# Work for the series solution
if soln1.has(Order) and soln2.has(Order):
if soln1.getO() == soln2.getO():
soln1 = soln1.removeO()
soln2 = soln2.removeO()
else:
return False
elif soln1.has(Order) or soln2.has(Order):
return False
constants1 = soln1.free_symbols.difference(eq.free_symbols)
constants2 = soln2.free_symbols.difference(eq.free_symbols)
constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1))
if len(constants1) == 1:
constants1_new = {constants1_new}
for c_old, c_new in zip(constants1, constants1_new):
soln1 = soln1.subs(c_old, c_new)
# n equations for sol1 = sol2, sol1'=sol2', ...
lhs = soln1
rhs = soln2
eqns = [Eq(lhs, rhs)]
for n in range(1, order):
lhs = lhs.diff(var)
rhs = rhs.diff(var)
eq = Eq(lhs, rhs)
eqns.append(eq)
# BooleanTrue/False awkwardly show up for trivial equations
if any(isinstance(eq, BooleanFalse) for eq in eqns):
return False
eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)]
try:
constant_solns = solve(eqns, constants2)
except NotImplementedError:
return False
# Sometimes returns a dict and sometimes a list of dicts
if isinstance(constant_solns, dict):
constant_solns = [constant_solns]
# after solving the issue 17418, maybe we don't need the following checksol code.
for constant_soln in constant_solns:
for eq in eqns:
eq=eq.rhs-eq.lhs
if checksol(eq, constant_soln) is not True:
return False
# If any solution gives all constants as expressions that don't depend on
# x then there exists constants for soln2 that give soln1
for constant_soln in constant_solns:
if not any(c.has(var) for c in constant_soln.values()):
return True
return False
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that derivative.
The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is
not linear. This function assumes that ``func`` has already been checked
to be good.
Examples
========
>>> from sympy import Function, cos, sin
>>> from sympy.abc import x
>>> from sympy.solvers.ode.ode import _nth_linear_match
>>> f = Function('f')
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(x), f(x), 3)
{-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1}
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(f(x)), f(x), 3) == None
True
"""
x = func.args[0]
one_x = {x}
terms = {i: S.Zero for i in range(-1, order + 1)}
for i in Add.make_args(eq):
if not i.has(func):
terms[-1] += i
else:
c, f = i.as_independent(func)
if (isinstance(f, Derivative)
and set(f.variables) == one_x
and f.args[0] == func):
terms[f.derivative_count] += c
elif f == func:
terms[len(f.args[1:])] += c
else:
return None
return terms
def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Euler's formula. The general
solution is the sum of the terms found. If SymPy cannot find exact roots
to the characteristic equation, a
:py:obj:`~.ComplexRootOf` instance will be returned
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'))
2
f(x) = x *(C1 + C2*x)
References
==========
- https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
- C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12
# indirect doctest
"""
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms = []
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
constants.reverse()
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S.Zero
# We need keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
ln = log
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gsol += (x**root) * constants.pop()
if multiplicity != 1:
raise ValueError("Value should be 1")
collectterms = [(0, root, 0)] + collectterms
elif root.is_real:
gsol += ln(x)**i*(x**root) * constants.pop()
collectterms = [(i, root, 0)] + collectterms
else:
reroot = re(root)
imroot = im(root)
gsol += ln(x)**i * (x**reroot) * (
constants.pop() * sin(abs(imroot)*ln(x))
+ constants.pop() * cos(imroot*ln(x)))
# Preserve ordering (multiplicity, real part, imaginary part)
# It will be assumed implicitly when constructing
# fundamental solution sets.
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'sol':
return Eq(f(x), gsol)
elif returns in ('list' 'both'):
# HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through)
# Create a list of (hopefully) linearly independent solutions
gensols = []
# Keep track of when to use sin or cos for nonzero imroot
for i, reroot, imroot in collectterms:
if imroot == 0:
gensols.append(ln(x)**i*x**reroot)
else:
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
if sin_form in gensols:
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
gensols.append(cos_form)
else:
gensols.append(sin_form)
if returns == 'list':
return gensols
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of linearly independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> from sympy import dsolve, Function, Derivative, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
x = func.args[0]
f = func.func
r = match
chareq, eq, symbol = S.Zero, S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
for i in range(1,degree(Poly(chareq, symbol))+1):
eq += chareq.coeff(symbol**i)*diff(f(x), x, i)
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(r[-1].subs(x, exp(x)))
eq += e.subs(re)
match = _nth_linear_match(eq, f(x), ode_order(eq, f(x)))
eq_homogeneous = Add(eq,-match[-1])
match['trialset'] = _undetermined_coefficients_match(match[-1], x, func, eq_homogeneous)['trialset']
return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand()
def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes SymPy cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, Derivative
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
x = func.args[0]
f = func.func
r = match
gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both')
match.update(gensol)
r[-1] = r[-1]/r[ode_order(eq, f(x))]
sol = _solve_variation_of_parameters(eq, func, order, match)
return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))])
def _linear_coeff_match(expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> from sympy import Function
>>> from sympy.abc import x
>>> from sympy.solvers.ode.ode import _linear_coeff_match
>>> from sympy.functions.elementary.trigonometric import sin
>>> f = Function('f')
>>> _linear_coeff_match((
... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x))
(1/9, 22/9)
>>> _linear_coeff_match(
... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x))
(19/27, 2/27)
>>> _linear_coeff_match(sin(f(x)/x), f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r'''
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
'''
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r'''
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
'''
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def ode_linear_coefficients(eq, func, order, match):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
Examples
========
>>> from sympy import Function, pprint
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> df = f(x).diff(x)
>>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1)
>>> dsolve(eq, hint='linear_coefficients')
[Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)]
>>> pprint(dsolve(eq, hint='linear_coefficients'))
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
return ode_1st_homogeneous_coeff_best(eq, func, order, match)
def ode_separable_reduced(eq, func, order, match):
r"""
Solves a differential equation that can be reduced to the separable form.
The general form of this equation is
.. math:: y' + (y/x) H(x^n y) = 0\text{}.
This can be solved by substituting `u(y) = x^n y`. The equation then
reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} -
\frac{1}{x} = 0`.
The general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x, n
>>> f, g = map(Function, ['f', 'g'])
>>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x))
>>> pprint(genform)
/ n \
d f(x)*g\x *f(x)/
--(f(x)) + ---------------
dx x
>>> pprint(dsolve(genform, hint='separable_reduced'))
n
x *f(x)
/
|
| 1
| ------------ dy = C1 + log(x)
| y*(n - g(y))
|
/
See Also
========
:meth:`sympy.solvers.ode.ode.ode_separable`
Examples
========
>>> from sympy import Function, pprint
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = (x - x**2*f(x))*d - f(x)
>>> dsolve(eq, hint='separable_reduced')
[Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)]
>>> pprint(dsolve(eq, hint='separable_reduced'))
___________ ___________
/ 2 / 2
1 - \/ C1*x + 1 \/ C1*x + 1 + 1
[f(x) = ------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Arguments are passed in a way so that they are coherent with the
# ode_separable function
x = func.args[0]
f = func.func
y = Dummy('y')
u = match['u'].subs(match['t'], y)
ycoeff = 1/(y*(match['power'] - u))
m1 = {y: 1, x: -1/x, 'coeff': 1}
m2 = {y: ycoeff, x: 1, 'coeff': 1}
r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)}
return ode_separable(eq, func, order, r)
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> from sympy import Function, pprint, exp
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'))
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, p.p 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match.get('f0')
value = match.get('f0val')
terms = match.get('terms')
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialization
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo) or hc.has(NaN) or hc.has(zoo):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='sol'):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0))
+ (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1)))
+ C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1)))
+ (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3)))
+ C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3))))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
for use with non homogeneous solution methods like variation of
parameters and undetermined coefficients. Note that, though the
solutions should be linearly independent, this function does not
explicitly check that. You can do ``assert simplify(wronskian(sollist))
!= 0`` to check for linear independence. Also, ``assert len(sollist) ==
order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- https://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if type(i) == str or i < 0:
pass
else:
chareq += r[i]*symbol**i
chareq = Poly(chareq, symbol)
# Can't just call roots because it doesn't return rootof for unsolveable
# polynomials.
chareqroots = roots(chareq, multiple=True)
if len(chareqroots) != order:
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()])
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
# We need to keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
#
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms = []
gensols = []
conjugate_roots = [] # used to prevent double-use of conjugate roots
# Loop over roots in theorder provided by roots/rootof...
for root in chareqroots:
# but don't repoeat multiple roots.
if root not in charroots:
continue
multiplicity = charroots.pop(root)
for i in range(multiplicity):
if chareq_is_complex:
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
continue
reroot = re(root)
imroot = im(root)
if imroot.has(atan2) and reroot.has(atan2):
# Remove this condition when re and im stop returning
# circular atan2 usages.
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
else:
if root in conjugate_roots:
collectterms = [(i, reroot, imroot)] + collectterms
continue
if imroot == 0:
gensols.append(x**i*exp(reroot*x))
collectterms = [(i, reroot, 0)] + collectterms
continue
conjugate_roots.append(conjugate(root))
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
# This ordering is important
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'list':
return gensols
elif returns in ('sol' 'both'):
gsol = Add(*[i*j for (i, j) in zip(constants, gensols)])
if returns == 'sol':
return Eq(f(x), gsol)
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'))
/ / 3\\
| | x || -x 4*sin(2*x) 3*cos(2*x)
f(x) = |C1 + x*|C2 + --||*e - ---------- + ----------
\ \ 3 // 25 25
References
==========
- https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 221
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_undetermined_coefficients(eq, func, order, match)
def _solve_undetermined_coefficients(eq, func, order, match):
r"""
Helper function for the method of undetermined coefficients.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_undetermined_coefficients`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
``trialset``
The set of trial functions as returned by
``_undetermined_coefficients_match()['trialset']``.
"""
x = func.args[0]
f = func.func
r = match
coeffs = numbered_symbols('a', cls=Dummy)
coefflist = []
gensols = r['list']
gsol = r['sol']
trialset = r['trialset']
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply" +
" undetermined coefficients to " + str(eq) +
" (number of terms != order)")
trialfunc = 0
for i in trialset:
c = next(coeffs)
coefflist.append(c)
trialfunc += c*i
eqs = sub_func_doit(eq, f(x), trialfunc)
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
eqs = _mexpand(eqs)
for i in Add.make_args(eqs):
s = separatevars(i, dict=True, symbols=[x])
if coeffsdict.get(s[x]):
coeffsdict[s[x]] += s['coeff']
else:
coeffsdict[s[x]] = s['coeff']
coeffvals = solve(list(coeffsdict.values()), coefflist)
if not coeffvals:
raise NotImplementedError(
"Could not solve `%s` using the "
"method of undetermined coefficients "
"(unable to solve for coefficients)." % eq)
psol = trialfunc.subs(coeffvals)
return Eq(f(x), gsol.rhs + psol)
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
r"""
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomials in `x` (the
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
`e^{a x}` terms (in other words, it has a finite number of linearly
independent derivatives).
Note that you may still need to multiply each term returned here by
sufficient `x` to make it linearly independent with the solutions to the
homogeneous equation.
This is intended for internal use by ``undetermined_coefficients`` hints.
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
for example, you will need to manually convert `\sin^2(x)` into `[1 +
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
it.
Examples
========
>>> from sympy import log, exp
>>> from sympy.solvers.ode.ode import _undetermined_coefficients_match
>>> from sympy.abc import x
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
>>> _undetermined_coefficients_match(log(x), x)
{'test': False}
"""
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
def _test_term(expr, x):
r"""
Test if ``expr`` fits the proper form for undetermined coefficients.
"""
if not expr.has(x):
return True
elif expr.is_Add:
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Mul:
if expr.has(sin, cos):
foundtrig = False
# Make sure that there is only one trig function in the args.
# See the docstring.
for i in expr.args:
if i.has(sin, cos):
if foundtrig:
return False
else:
foundtrig = True
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Function:
if expr.func in (sin, cos, exp, sinh, cosh):
if expr.args[0].match(a*x + b):
return True
else:
return False
else:
return False
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
expr.exp >= 0:
return True
elif expr.is_Pow and expr.base.is_number:
if expr.exp.match(a*x + b):
return True
else:
return False
elif expr.is_Symbol or expr.is_number:
return True
else:
return False
def _get_trial_set(expr, x, exprs=set()):
r"""
Returns a set of trial terms for undetermined coefficients.
The idea behind undetermined coefficients is that the terms expression
repeat themselves after a finite number of derivatives, except for the
coefficients (they are linearly dependent). So if we collect these,
we should have the terms of our trial function.
"""
def _remove_coefficient(expr, x):
r"""
Returns the expression without a coefficient.
Similar to expr.as_independent(x)[1], except it only works
multiplicatively.
"""
term = S.One
if expr.is_Mul:
for i in expr.args:
if i.has(x):
term *= i
elif expr.has(x):
term = expr
return term
expr = expand_mul(expr)
if expr.is_Add:
for term in expr.args:
if _remove_coefficient(term, x) in exprs:
pass
else:
exprs.add(_remove_coefficient(term, x))
exprs = exprs.union(_get_trial_set(term, x, exprs))
else:
term = _remove_coefficient(expr, x)
tmpset = exprs.union({term})
oldset = set()
while tmpset != oldset:
# If you get stuck in this loop, then _test_term is probably
# broken
oldset = tmpset.copy()
expr = expr.diff(x)
term = _remove_coefficient(expr, x)
if term.is_Add:
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
else:
tmpset.add(term)
exprs = tmpset
return exprs
def is_homogeneous_solution(term):
r""" This function checks whether the given trialset contains any root
of homogenous equation"""
return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
retdict['test'] = _test_term(expr, x)
if retdict['test']:
# Try to generate a list of trial solutions that will have the
# undetermined coefficients. Note that if any of these are not linearly
# independent with any of the solutions to the homogeneous equation,
# then they will need to be multiplied by sufficient x to make them so.
# This function DOES NOT do that (it doesn't even look at the
# homogeneous equation).
temp_set = set()
for i in Add.make_args(expr):
act = _get_trial_set(i,x)
if eq_homogeneous is not S.Zero:
while any(is_homogeneous_solution(ts) for ts in act):
act = {x*ts for ts in act}
temp_set = temp_set.union(act)
retdict['trialset'] = temp_set
return retdict
def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
SymPy cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'))
/ / / x*log(x) 11*x\\\ x
f(x) = |C1 + x*|C2 + x*|C3 + -------- - ----|||*e
\ \ \ 6 36 ///
References
==========
- https://en.wikipedia.org/wiki/Variation_of_parameters
- http://planetmath.org/VariationOfParameters
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 233
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_variation_of_parameters(eq, func, order, match)
def _solve_variation_of_parameters(eq, func, order, match):
r"""
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_variation_of_parameters`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
"""
x = func.args[0]
f = func.func
r = match
psol = 0
gensols = r['list']
gsol = r['sol']
wr = wronskian(gensols, x)
if r.get('simplify', True):
wr = simplify(wr) # We need much better simplification for
# some ODEs. See issue 4662, for example.
# To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
wr = trigsimp(wr, deep=True, recursive=True)
if not wr:
# The wronskian will be 0 iff the solutions are not linearly
# independent.
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply " +
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply " +
"variation of parameters to " +
str(eq) + " (number of terms != order)")
negoneterm = (-1)**(order)
for i in gensols:
psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def ode_separable(eq, func, order, match):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be written as `P(y)
\tfrac{dy}{dx} = Q(x)`. The solution can then just be found by
rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`.
This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back
end, so if a separable equation is not caught by this solver, it is most
likely the fault of that function.
:py:meth:`~sympy.simplify.simplify.separatevars` is
smart enough to do most expansion and factoring necessary to convert a
separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The
general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f'])
>>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x)))
>>> pprint(genform)
d
a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x))
dx
>>> pprint(dsolve(genform, f(x), hint='separable_Integral'))
f(x)
/ /
| |
| b(y) | c(x)
| ---- dy = C1 + | ---- dx
| d(y) | a(x)
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x),
... hint='separable', simplify=False))
/ 2 \ 2
log\3*f (x) - 1/ x
---------------- = C1 + --
6 2
References
==========
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 52
# indirect doctest
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
r = match # {'m1':m1, 'm2':m2, 'y':y}
u = r.get('hint', f(x)) # get u from separable_reduced else get f(x)
return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']],
(r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x]/
r['m2'][x], x) + C1)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Lie groups solver has been implemented "
"only for first order differential equations")
else:
df = func.diff(x)
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs(func, y)
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: S(sol[dxi]).subs(func, y),
eta: S(sol[deta]).subs(func, y)}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs(y, func)))
else:
soltup.append((True, 0))
return soltup
def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf):
xi = Function("xi")
eta = Function("eta")
f = func.func
x = func.args[0]
y = match['y']
h = match['h']
tempsol = []
if not inf:
try:
inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
except ValueError:
return None
for infsim in inf:
xiinf = (infsim[xi(x, func)]).subs(func, y)
etainf = (infsim[eta(x, func)]).subs(func, y)
# This condition creates recursion while using pdsolve.
# Since the first step while solving a PDE of form
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
# is to solve the ODE dy/dx = b/a
if simplify(etainf/xiinf) == h:
continue
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
r = pdsolve(rpde, func=f(x, y)).rhs
s = pdsolve(rpde - 1, func=f(x, y)).rhs
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
r = Dummy("r")
s = Dummy("s")
C1 = Symbol("C1")
rcoord = newcoord[0]
scoord = newcoord[-1]
try:
sol = solve([r - rcoord, s - scoord], x, y, dict=True)
if sol == []:
continue
except NotImplementedError:
continue
else:
sol = sol[0]
xsub = sol[x]
ysub = sol[y]
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
if num and denom:
diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
sep = separatevars(diffeq, symbols=[r, s], dict=True)
if sep:
# Trying to separate, r and s coordinates
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
# Substituting and reverting back to original coordinates
deq = deq.subs([(r, rcoord), (s, scoord)])
try:
sdeq = solve(deq, y)
except NotImplementedError:
tempsol.append(deq)
else:
return [Eq(f(x), sol) for sol in sdeq]
elif denom: # (ds/dr) is zero which means s is constant
return [Eq(f(x), solve(scoord - C1, y)[0])]
elif num: # (dr/ds) is zero which means r is constant
return [Eq(f(x), solve(rcoord - C1, y)[0])]
# If nothing works, return solution as it is, without solving for y
if tempsol:
return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
return None
def _ode_lie_group( s, func, order, match):
heuristics = lie_heuristics
inf = {}
f = func.func
x = func.args[0]
df = func.diff(x)
xi = Function("xi")
eta = Function("eta")
xis = match['xi']
etas = match['eta']
y = match.pop('y', None)
if y:
h = -simplify(match[match['d']]/match[match['e']])
y = y
else:
y = Dummy("y")
h = s.subs(func, y)
if xis is not None and etas is not None:
inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]:
heuristics = ["user_defined"] + list(heuristics)
match = {'h': h, 'y': y}
# This is done so that if any heuristic raises a ValueError
# another heuristic can be used.
sol = None
for heuristic in heuristics:
sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf)
if sol:
return sol
return sol
def ode_lie_group(eq, func, order, match):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted
ODE can be easily solved by quadrature. It makes use of the
:py:meth:`sympy.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by substituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> from sympy import Function, dsolve, exp, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'))
/ 2\ 2
| x | -x
f(x) = |C1 + --|*e
\ 2 /
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
x = func.args[0]
df = func.diff(x)
try:
eqsol = solve(eq, df)
except NotImplementedError:
eqsol = []
desols = []
for s in eqsol:
sol = _ode_lie_group(s, func, order, match=match)
if sol:
desols.extend(sol)
if desols == []:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the lie group method")
return desols
def _lie_group_remove(coords):
r"""
This function is strictly meant for internal use by the Lie group ODE solving
method. It replaces arbitrary functions returned by pdsolve as follows:
1] If coords is an arbitrary function, then its argument is returned.
2] An arbitrary function in an Add object is replaced by zero.
3] An arbitrary function in a Mul object is replaced by one.
4] If there is no arbitrary function coords is returned unchanged.
Examples
========
>>> from sympy.solvers.ode.ode import _lie_group_remove
>>> from sympy import Function
>>> from sympy.abc import x, y
>>> F = Function("F")
>>> eq = x**2*y
>>> _lie_group_remove(eq)
x**2*y
>>> eq = F(x**2*y)
>>> _lie_group_remove(eq)
x**2*y
>>> eq = x*y**2 + F(x**3)
>>> _lie_group_remove(eq)
x*y**2
>>> eq = (F(x**3) + y)*x**4
>>> _lie_group_remove(eq)
x**4*y
"""
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs(func, 0)
return coords
elif coords.is_Pow:
base, expr = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return base**expr
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if not isinstance(coords, AppliedUndef):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
r"""
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
They are tangents to the coordinate curves of the new system.
Consider the transformation `(x, y) \to (X, Y)` such that the
differential equation remains invariant. `\xi` and `\eta` are the tangents to
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \xi,
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \eta,
The infinitesimals can be found by solving the following PDE:
>>> from sympy import Function, Eq, pprint
>>> from sympy.abc import x, y
>>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
>>> h = h(x, y) # dy/dx = h
>>> eta = eta(x, y)
>>> xi = xi(x, y)
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
>>> pprint(genform)
/d d \ d 2 d
|--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
\dy dx / dy dy
<BLANKLINE>
d d
i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
dx dx
Solving the above mentioned PDE is not trivial, and can be solved only by
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
infinitesimal is found, the attempt to find more heuristics stops. This is done to
optimise the speed of solving the differential equation. If a list of all the
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
the complete list of infinitesimals. If the infinitesimals for a particular
heuristic needs to be found, it can be passed as a flag to ``hint``.
Examples
========
>>> from sympy import Function
>>> from sympy.solvers.ode.ode import infinitesimals
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x) - x**2*f(x)
>>> infinitesimals(eq)
[{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Infinitesimals for only "
"first order ODE's have been implemented")
else:
df = func.diff(x)
# Matching differential equation of the form a*df + b
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
if match: # Used by lie_group hint
h = match['h']
y = match['y']
else:
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy("y")
h = h.subs(func, y)
u = Dummy("u")
hx = h.diff(x)
hy = h.diff(y)
hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
if hint == 'all':
xieta = []
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
inflist = function(match, comp=True)
if inflist:
xieta.extend([inf for inf in inflist if inf not in xieta])
if xieta:
return xieta
else:
raise NotImplementedError("Infinitesimals could not be found for "
"the given ODE")
elif hint == 'default':
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
xieta = function(match, comp=False)
if xieta:
return xieta
raise NotImplementedError("Infinitesimals could not be found for"
" the given ODE")
elif hint not in lie_heuristics:
raise ValueError("Heuristic not recognized: " + hint)
else:
function = globals()['lie_heuristic_' + hint]
xieta = function(match, comp=True)
if xieta:
return xieta
else:
raise ValueError("Infinitesimals could not be found using the"
" given heuristic")
def lie_heuristic_abaco1_simple(match, comp=False):
r"""
The first heuristic uses the following four sets of
assumptions on `\xi` and `\eta`
.. math:: \xi = 0, \eta = f(x)
.. math:: \xi = 0, \eta = f(y)
.. math:: \xi = f(x), \eta = 0
.. math:: \xi = f(y), \eta = 0
The success of this heuristic is determined by algebraic factorisation.
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x})*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
xieta = []
y = match['y']
h = match['h']
func = match['func']
x = func.args[0]
hx = match['hx']
hy = match['hy']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
hysym = hy.free_symbols
if y not in hysym:
try:
fx = exp(integrate(hy, x))
except NotImplementedError:
pass
else:
inf = {xi: S.Zero, eta: fx}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = hy/h
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: S.Zero, eta: fy.subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/h
facsym = factor.free_symbols
if y not in facsym:
try:
fx = exp(integrate(factor, x))
except NotImplementedError:
pass
else:
inf = {xi: fx, eta: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/(h**2)
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: fy.subs(y, func), eta: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco1_product(match, comp=False):
r"""
The second heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x)*g(y)
.. math:: \eta = f(x)*g(y), \xi = 0
The first assumption of this heuristic holds good if
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
separable in `x` and `y`, then the separated factors containing `x`
is `f(x)`, and `g(y)` is obtained by
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
of `y` only.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again
interchanged, to get `\eta` as `f(x)*g(y)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
y = match['y']
h = match['h']
hinv = match['hinv']
func = match['func']
x = func.args[0]
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*h)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
u1 = Dummy("u1")
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
etaval = fx*gy
etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
inf = {eta: etaval.subs(y, func), xi: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_bivariate(match, comp=False):
r"""
The third heuristic assumes the infinitesimals `\xi` and `\eta`
to be bi-variate polynomials in `x` and `y`. The assumption made here
for the logic below is that `h` is a rational function in `x` and `y`
though that may not be necessary for the infinitesimals to be
bivariate polynomials. The coefficients of the infinitesimals
are found out by substituting them in the PDE and grouping similar terms
that are polynomials and since they form a linear system, solve and check
for non trivial solutions. The degree of the assumed bivariates
are increased till a certain maximum value.
References
==========
- Lie Groups and Differential Equations
pp. 327 - pp. 329
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
# The maximum degree that the infinitesimals can take is
# calculated by this technique.
etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
num, denom = cancel(ipde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
deta = Function('deta')(x, y)
dxi = Function('dxi')(x, y)
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
- dxi*hx - deta*hy)
xieq = Symbol("xi0")
etaeq = Symbol("eta0")
for i in range(deg + 1):
if i:
xieq += Add(*[
Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
etaeq += Add(*[
Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
pden = expand(pden)
# If the individual terms are monomials, the coefficients
# are grouped
if pden.is_polynomial(x, y) and pden.is_Add:
polyy = Poly(pden, x, y).as_dict()
if polyy:
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
soldict = solve(polyy.values(), *symset)
if isinstance(soldict, list):
soldict = soldict[0]
if any(soldict.values()):
xired = xieq.subs(soldict)
etared = etaeq.subs(soldict)
# Scaling is done by substituting one for the parameters
# This can be any number except zero.
dict_ = {sym: 1 for sym in symset}
inf = {eta: etared.subs(dict_).subs(y, func),
xi: xired.subs(dict_).subs(y, func)}
return [inf]
def lie_heuristic_chi(match, comp=False):
r"""
The aim of the fourth heuristic is to find the function `\chi(x, y)`
that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
- \frac{\partial h}{\partial y}\chi = 0`.
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
`h` should be a rational function in `x` and `y`. The method used here is
to substitute a general binomial for `\chi` up to a certain maximum degree
is reached. The coefficients of the polynomials, are calculated by by collecting
terms of the same order in `x` and `y`.
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
which would give `-\xi` as the quotient and `\eta` as the remainder.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
h = match['h']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
schi, schix, schiy = symbols("schi, schix, schiy")
cpde = schix + h*schiy - hy*schi
num, denom = cancel(cpde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
chi = Function('chi')(x, y)
chix = chi.diff(x)
chiy = chi.diff(y)
cpde = chix + h*chiy - hy*chi
chieq = Symbol("chi")
for i in range(1, deg + 1):
chieq += Add(*[
Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
cnum = expand(cnum)
if cnum.is_polynomial(x, y) and cnum.is_Add:
cpoly = Poly(cnum, x, y).as_dict()
if cpoly:
solsyms = chieq.free_symbols - {x, y}
soldict = solve(cpoly.values(), *solsyms)
if isinstance(soldict, list):
soldict = soldict[0]
if any(soldict.values()):
chieq = chieq.subs(soldict)
dict_ = {sym: 1 for sym in solsyms}
chieq = chieq.subs(dict_)
# After finding chi, the main aim is to find out
# eta, xi by the equation eta = xi*h + chi
# One method to set xi, would be rearranging it to
# (eta/h) - xi = (chi/h). This would mean dividing
# chi by h would give -xi as the quotient and eta
# as the remainder. Thanks to Sean Vig for suggesting
# this method.
xic, etac = div(chieq, h)
inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
return [inf]
def lie_heuristic_function_sum(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x) + g(y)
.. math:: \eta = f(x) + g(y), \xi = 0
The first assumption of this heuristic holds good if
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
\partial x^{2}}(h^{-1}))^{-1}]
is separable in `x` and `y`,
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
From this `g(y)` can be determined.
2. The separated factors containing `x` is `f''(x)`.
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates
are again interchanged, to get `\eta` as `f(x) + g(y)`.
For both assumptions, the constant factors are separated among `g(y)`
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
obtained from 2]. If not possible, then this heuristic fails.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
h = match['h']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
for odefac in [h, hinv]:
factor = odefac*((1/odefac).diff(x, 2))
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
k = Dummy("k")
try:
gy = k*integrate(sep[y], y)
except NotImplementedError:
pass
else:
fdd = 1/(k*sep[x]*sep['coeff'])
fx = simplify(fdd/factor - gy)
check = simplify(fx.diff(x, 2) - fdd)
if fx:
if not check:
fx = fx.subs(k, 1)
gy = (gy/k)
else:
sol = solve(check, k)
if sol:
sol = sol[0]
fx = fx.subs(k, sol)
gy = (gy/k)*sol
else:
continue
if odefac == hinv: # Inverse ODE
fx = fx.subs(x, y)
gy = gy.subs(y, x)
etaval = factor_terms(fx + gy)
if etaval.is_Mul:
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
if odefac == hinv: # Inverse ODE
inf = {eta: etaval.subs(y, func), xi : S.Zero}
else:
inf = {xi: etaval.subs(y, func), eta : S.Zero}
if not comp:
return [inf]
else:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco2_similar(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = g(x), \xi = f(x)
.. math:: \eta = f(y), \xi = g(y)
For the first assumption,
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
\partial yy}}` is calculated. Let us say this value is A
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
and `A(x)*f(x)` gives `g(x)`
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
\partial Y}} = \gamma` is calculated. If
a] `\gamma` is a function of `x` alone
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
factor = cancel(h.diff(y)/h.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{xi: tau, eta: gx}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{xi: tau, eta: gx}]
factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
hinv + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
def lie_heuristic_abaco2_unique_unknown(match, comp=False):
r"""
This heuristic assumes the presence of unknown functions or known functions
with non-integer powers.
1. A list of all functions and non-integer powers containing x and y
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
\frac{\partial f}{\partial x}} = R`
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
`\xi` and `\eta`
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
If yes, then return `\xi` and `\eta`
If not, then check if
a] :math:`\xi = -R,\eta = 1`
b] :math:`\xi = 1, \eta = -\frac{1}{R}`
are solutions.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
funclist = []
for atom in h.atoms(Pow):
base, exp = atom.as_base_exp()
if base.has(x) and base.has(y):
if not exp.is_Integer:
funclist.append(atom)
for function in h.atoms(AppliedUndef):
syms = function.free_symbols
if x in syms and y in syms:
funclist.append(function)
for f in funclist:
frac = cancel(f.diff(y)/f.diff(x))
sep = separatevars(frac, dict=True, symbols=[x, y])
if sep and sep['coeff']:
xitry1 = sep[x]
etatry1 = -1/(sep[y]*sep['coeff'])
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
if not simplify(pde1):
return [{xi: xitry1, eta: etatry1.subs(y, func)}]
xitry2 = 1/etatry1
etatry2 = 1/xitry1
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
if not simplify(expand(pde2)):
return [{xi: xitry2.subs(y, func), eta: etatry2}]
else:
etatry = -1/frac
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
if not simplify(pde):
return [{xi: S.One, eta: etatry.subs(y, func)}]
xitry = -frac
pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
if not simplify(expand(pde)):
return [{xi: xitry.subs(y, func), eta: S.One}]
def lie_heuristic_abaco2_unique_general(match, comp=False):
r"""
This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
without making any assumptions on `h`.
The complete sequence of steps is given in the paper mentioned below.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
A = hx.diff(y)
B = hy.diff(y) + hy**2
C = hx.diff(x) - hx**2
if not (A and B and C):
return
Ax = A.diff(x)
Ay = A.diff(y)
Axy = Ax.diff(y)
Axx = Ax.diff(x)
Ayy = Ay.diff(y)
D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
if not D:
E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
if E1:
E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if not E2:
E3 = simplify(
E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
if not E3:
etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -4*A**3*etaval/E1
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
else:
E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if E1:
E2 = simplify(
4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
if not E2:
E3 = simplify(
-(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
(A*hx - 3*Ax)*E1)*E1)
if not E3:
etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -E1*etaval/D
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
def lie_heuristic_linear(match, comp=False):
r"""
This heuristic assumes
1. `\xi = ax + by + c` and
2. `\eta = fx + gy + h`
After substituting the following assumptions in the determining PDE, it
reduces to
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
- (fx + gy + c)\frac{\partial h}{\partial y}
Solving the reduced PDE obtained, using the method of characteristics, becomes
impractical. The method followed is grouping similar terms and solving the system
of linear equations obtained. The difference between the bivariate heuristic is that
`h` need not be a rational function in this case.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
coeffdict = {}
symbols = numbered_symbols("c", cls=Dummy)
symlist = [next(symbols) for _ in islice(symbols, 6)]
C0, C1, C2, C3, C4, C5 = symlist
pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
pde, denom = pde.as_numer_denom()
pde = powsimp(expand(pde))
if pde.is_Add:
terms = pde.args
for term in terms:
if term.is_Mul:
rem = Mul(*[m for m in term.args if not m.has(x, y)])
xypart = term/rem
if xypart not in coeffdict:
coeffdict[xypart] = rem
else:
coeffdict[xypart] += rem
else:
if term not in coeffdict:
coeffdict[term] = S.One
else:
coeffdict[term] += S.One
sollist = coeffdict.values()
soldict = solve(sollist, symlist)
if soldict:
if isinstance(soldict, list):
soldict = soldict[0]
subval = soldict.values()
if any(t for t in subval):
onedict = dict(zip(symlist, [1]*6))
xival = C0*x + C1*func + C2
etaval = C3*x + C4*func + C5
xival = xival.subs(soldict)
etaval = etaval.subs(soldict)
xival = xival.subs(onedict)
etaval = etaval.subs(onedict)
return [{xi: xival, eta: etaval}]
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
# and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
r['a'] = -fc[0,x(t),0]/fc[0,x(t),1]
r['c'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['b'] = -fc[0,y(t),0]/fc[0,x(t),1]
r['d'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S.Zero,S.Zero]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
r['k1'] = forcing[0]
r['k2'] = forcing[1]
else:
raise NotImplementedError("Only homogeneous problems are supported" +
" (and constant inhomogeneity)")
if match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order1_type6(x, y, t, r, eq)
if match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order1_type7(x, y, t, r, eq)
return sol
def _linear_2eq_order1_type6(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y
This is solved by first multiplying the first equation by `-a` and adding
it to the second equation to obtain
.. math:: y' - a x' = -a h(t) (y - a x)
Setting `U = y - ax` and integrating the equation we arrive at
.. math:: y - ax = C_1 e^{-a \int h(t) \,dt}
and on substituting the value of y in first equation give rise to first order ODEs. After solving for
`x`, we can obtain `y` by substituting the value of `x` in second equation.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
p = 0
q = 0
p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0])
p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0])
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q!=0 and n==0:
if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j:
p = 1
s = j
break
if q!=0 and n==1:
if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j:
p = 2
s = j
break
if p == 1:
equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t)))
hint1 = classify_ode(equ)[1]
sol1 = dsolve(equ, hint=hint1+'_Integral').rhs
sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t))
elif p ==2:
equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
hint1 = classify_ode(equ)[1]
sol2 = dsolve(equ, hint=hint1+'_Integral').rhs
sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type7(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = h(t) x + p(t) y
Differentiating the first equation and substituting the value of `y`
from second equation will give a second-order linear equation
.. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0
This above equation can be easily integrated if following conditions are satisfied.
1. `fgp - g^{2} h + f g' - f' g = 0`
2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg`
If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes
a constant coefficient differential equation which is also solved by current solver.
Otherwise if the above condition fails then,
a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)`
Then the general solution is expressed as
.. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt
.. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt]
where C1 and C2 are arbitrary constants and
.. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b']
e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t)
m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t)
m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t)
if e1 == 0:
sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif e2 == 0:
sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t):
sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t):
sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
else:
x0 = Function('x0')(t) # x0 and y0 being particular solutions
y0 = Function('y0')(t)
F = exp(Integral(r['a'],t))
P = exp(Integral(r['d'],t))
sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t)
sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_nonlinear_2eq_order1(match_):
func = match_['func']
eq = match_['eq']
fc = match_['func_coeff']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_2eq_order1_type5(func, t, eq)
return sol
x = func[0].func
y = func[1].func
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_2eq_order1_type1(x, y, t, eq)
elif match_['type_of_equation'] == 'type2':
sol = _nonlinear_2eq_order1_type2(x, y, t, eq)
elif match_['type_of_equation'] == 'type3':
sol = _nonlinear_2eq_order1_type3(x, y, t, eq)
elif match_['type_of_equation'] == 'type4':
sol = _nonlinear_2eq_order1_type4(x, y, t, eq)
return sol
def _nonlinear_2eq_order1_type1(x, y, t, eq):
r"""
Equations:
.. math:: x' = x^n F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `n \neq 1`
.. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}}
if `n = 1`
.. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy}
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v = symbols('u, v')
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n!=1:
phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n))
else:
phi = C1*exp(Integral(1/g, v))
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type2(x, y, t, eq):
r"""
Equations:
.. math:: x' = e^{\lambda x} F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `\lambda \neq 0`
.. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy)
if `\lambda = 0`
.. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v = symbols('u, v')
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n:
phi = -1/n*log(C1 - n*Integral(1/g, v))
else:
phi = C1 + Integral(1/g, v)
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type3(x, y, t, eq):
r"""
Autonomous system of general form
.. math:: x' = F(x,y)
.. math:: y' = G(x,y)
Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general
solution of the first-order equation
.. math:: F(x,y) y'_x = G(x,y)
Then the general solution of the original system of equations has the form
.. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
v = Function('v')
u = Symbol('u')
f = Wild('f')
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
F = r1[f].subs(x(t), u).subs(y(t), v(u))
G = r2[g].subs(x(t), u).subs(y(t), v(u))
sol2r = dsolve(Eq(diff(v(u), u), G/F))
if isinstance(sol2r, Equality):
sol2r = [sol2r]
for sol2s in sol2r:
sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u)
sol = []
for sols in sol1:
sol.append(Eq(x(t), sols))
sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols)))
return sol
def _nonlinear_2eq_order1_type4(x, y, t, eq):
r"""
Equation:
.. math:: x' = f_1(x) g_1(y) \phi(x,y,t)
.. math:: y' = f_2(x) g_2(y) \phi(x,y,t)
First integral:
.. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C
where `C` is an arbitrary constant.
On solving the first integral for `x` (resp., `y` ) and on substituting the
resulting expression into either equation of the original solution, one
arrives at a first-order equation for determining `y` (resp., `x` ).
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v = symbols('u, v')
U, V = symbols('U, V', cls=Function)
f = Wild('f')
g = Wild('g')
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
F1 = R1[f1]; F2 = R2[f2]
G1 = R1[g1]; G2 = R2[g2]
sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u)
sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v)
sol = []
for sols in sol1r:
sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs))
for sols in sol2r:
sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs))
return set(sol)
def _nonlinear_2eq_order1_type5(func, t, eq):
r"""
Clairaut system of ODEs
.. math:: x = t x' + F(x',y')
.. math:: y = t y' + G(x',y')
The following are solutions of the system
`(i)` straight lines:
.. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2)
where `C_1` and `C_2` are arbitrary constants;
`(ii)` envelopes of the above lines;
`(iii)` continuously differentiable lines made up from segments of the lines
`(i)` and `(ii)`.
"""
C1, C2 = get_numbered_constants(eq, num=2)
f = Wild('f')
g = Wild('g')
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
return [r1, r2]
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
[r1, r2] = check_type(x, y)
if not (r1 and r2):
[r1, r2] = check_type(y, x)
x, y = y, x
x1 = diff(x(t),t); y1 = diff(y(t),t)
return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
def sysode_nonlinear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
eq = match_['eq']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq)
if match_['type_of_equation'] == 'type2':
sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq)
if match_['type_of_equation'] == 'type3':
sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq)
if match_['type_of_equation'] == 'type4':
sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq)
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq)
return sol
def _nonlinear_3eq_order1_type1(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a separable first-order equation on `x`. Similarly doing that
for other two equations, we will arrive at first order equation on `y` and `z` too.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t))
r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t)))
r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
b = vals[0].subs(w, c)
a = vals[1].subs(w, c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x)
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y)
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z)
return [sol1, sol2, sol3]
def _nonlinear_3eq_order1_type2(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z f(x, y, z, t)
.. math:: b y' = (c - a) z x f(x, y, z, t)
.. math:: c z' = (a - b) x y f(x, y, z, t)
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a first-order differential equations on `x`. Similarly doing
that for other two equations we will arrive at first order equation on `y` and `z`.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f)
r = collect_const(r1[f]).match(p*f)
r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t)))
r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
a = vals[0].subs(w, c)
b = vals[1].subs(w, c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f])
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f])
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f])
return [sol1, sol2, sol3]
def _nonlinear_3eq_order1_type3(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2
where `F_n = F_n(x, y, z, t)`.
1. First Integral:
.. math:: a x + b y + c z = C_1,
where C is an arbitrary constant.
2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)`
Then, on eliminating `t` and `z` from the first two equation of the system, one
arrives at the first-order equation
.. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) -
b F_3 (x, y, z)}
where `z = \frac{1}{c} (C_1 - a x - b y)`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
fu, fv, fw = symbols('u, v, w', cls=Function)
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = (diff(x(t), t) - eq[0]).match(F2-F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w)
F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w)
F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w)
z_xy = (C1-a*u-b*v)/c
y_zx = (C1-a*u-c*w)/b
x_yz = (C1-b*v-c*w)/a
y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs
z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs
z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs
x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs
y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs
x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs
sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs
sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs
sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs
return [sol1, sol2, sol3]
def _nonlinear_3eq_order1_type4(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2
where `F_n = F_n (x, y, z, t)`
1. First integral:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
where `C` is an arbitrary constant.
2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on
eliminating `t` and `z` from the first two equations of the system, one arrives at
the first-order equation
.. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)}
{c z F_2 (x, y, z) - b y F_3 (x, y, z)}
where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
x_yz = sqrt((C1 - b*v**2 - c*w**2)/a)
y_zx = sqrt((C1 - c*w**2 - a*u**2)/b)
z_xy = sqrt((C1 - a*u**2 - b*v**2)/c)
y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [sol1, sol2, sol3]
def _nonlinear_3eq_order1_type5(x, y, z, t, eq):
r"""
.. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2)
where `F_n = F_n (x, y, z, t)` and are arbitrary functions.
First Integral:
.. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1
where `C` is an arbitrary constant. If the function `F_n` is independent of `t`,
then, by eliminating `t` and `z` from the first two equations of the system, one
arrives at a first-order equation.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
fu, fv, fw = symbols('u, v, w', cls=Function)
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1)))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w)
F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w)
F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w)
x_yz = (C1*v**-b*w**-c)**-a
y_zx = (C1*w**-c*u**-a)**-b
z_xy = (C1*u**-a*v**-b)**-c
y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs
z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs
z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs
x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs
y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs
x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs
sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs
sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs
sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs
return [sol1, sol2, sol3]
#This import is written at the bottom to avoid circular imports.
from .single import (NthAlgebraic, Factorable, FirstLinear, AlmostLinear,
Bernoulli, SingleODEProblem, SingleODESolver, RiccatiSpecial)
|
0211befc65a77c85addcd7380f184ecb0d864e161919929172eb786b8c74dbb0 | from sympy import Eq, factor, factorial, Function, Lambda, rf, S, sqrt, symbols, I, \
expand, binomial, Rational, Symbol, cos, sin, Abs
from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio
from sympy.testing.pytest import raises, slow
from sympy.abc import a, b
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_poly([-1, -1, 1], 1, n) == -1
assert rsolve_poly([-1, n + 1], n, n) == 1
assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2
assert rsolve_poly([-n - 1, n], 1, n) == C1*n - 1
assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1
assert rsolve_poly([-1, 1], n**5 + n**3, n) == \
C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3
def test_rsolve_ratio():
solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n,
-2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n)
assert solution in [
C1*((-2*n + 3)/(n**2 - 1))/3,
(S.Half)*(C1*(-3 + 2*n)/(-1 + n**2)),
(S.Half)*(C1*( 3 - 2*n)/( 1 - n**2)),
(S.Half)*(C2*(-3 + 2*n)/(-1 + n**2)),
(S.Half)*(C2*( 3 - 2*n)/( 1 - n**2)),
]
def test_rsolve_hyper():
assert rsolve_hyper([-1, -1, 1], 0, n) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [
C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n),
C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n),
]
assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [
C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n),
C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n),
]
assert rsolve_hyper(
[2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n
assert rsolve_hyper(
[n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == None
assert rsolve_hyper([-n - 1, -1, 1], 0, n) == None
assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2
assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2
assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n
assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2)
assert rsolve_hyper([1, 1, 1], 0, n).expand() == \
C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n
assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) is None
def recurrence_term(c, f):
"""Compute RHS of recurrence in f(n) with coefficients in c."""
return sum(c[i]*f.subs(n, n + i) for i in range(len(c)))
def test_rsolve_bulk():
"""Some bulk-generated tests."""
funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3*
n**3 + 12*n**4 - 52*n**5 ]
coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 -
n + 12, 1] ]
for p in funcs:
# compute difference
for c in coeffs:
q = recurrence_term(c, p)
if p.is_polynomial(n):
assert rsolve_poly(c, q, n) == p
# See issue 3956:
#if p.is_hypergeometric(n):
# assert rsolve_hyper(c, q, n) == p
def test_rsolve():
f = y(n + 2) - y(n + 1) - y(n)
h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
- sqrt(5)*(S.Half - S.Half*sqrt(5))**n
assert rsolve(f, y(n)) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve(f, y(n), [0, 5]) == h
assert rsolve(f, y(n), {0: 0, 1: 5}) == h
assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n)
g = C1*factorial(n) + C0*2**n
h = -3*factorial(n) + 3*2**n
assert rsolve(f, y(n)) == g
assert rsolve(f, y(n), []) == g
assert rsolve(f, y(n), {}) == g
assert rsolve(f, y(n), [0, 3]) == h
assert rsolve(f, y(n), {0: 0, 1: 3}) == h
assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - y(n - 1) - 2
assert rsolve(f, y(n), {y(0): 0}) == 2*n
assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = 3*y(n - 1) - y(n) - 1
assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half
assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half
assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - 1/n*y(n - 1)
assert rsolve(f, y(n)) == C0/factorial(n)
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - 1/n*y(n - 1) - 1
assert rsolve(f, y(n)) is None
f = 2*y(n - 1) + (1 - n)*y(n)/n
assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n
assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2
assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n)
assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2)
assert rsolve(
f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n)
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n
assert rsolve(y(n) - a*y(n-2),y(n), \
{y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \
a**(n/2)*(-(-1)**n*b + a)
f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n)
yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)})
sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12
assert factor(expand(yn, func=True)) == sol
assert (rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n)) -
(C0*((sqrt(-a**2 + 1) - 1)/a)**n +
C1*((-sqrt(-a**2 + 1) - 1)/a)**n)).simplify() == 0
assert rsolve((k + 1)*y(k), y(k)) is None
assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k))
is None)
assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4
def test_rsolve_raises():
x = Function('x')
raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n)))
raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0}))
raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n)))
def test_issue_6844():
f = y(n + 2) - y(n + 1) + y(n)/4
assert rsolve(f, y(n)) == 2**(-n)*(C0 + C1*n)
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2*2**(-n)*n
def test_issue_18751():
r = Symbol('r', real=True, positive=True)
theta = Symbol('theta', real=True)
f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2)
assert rsolve(f, y(n)) == \
C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n
def test_constant_naming():
#issue 8697
assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C0+C1+C2*n
assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == C0*(-1)**n + (-1)**n*C1*n + (-1)**n*C2*n**2
assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2
#issue 19630
assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*n
@slow
def test_issue_15751():
f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8)
assert rsolve(f, y(n)) is not None
def test_issue_17990():
f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3)
sol = rsolve(f, y(n))
expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 +
3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036
*sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) -
S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n
assert sol == expected
e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf()
assert abs(e + 0.130434782608696) < 1e-13
|
9d5b5278db727ddda16249f06a69112257815efdfee3551a722771d0fea38fb2 | from sympy import (acos, acosh, atan, cos, Derivative, diff,
Dummy, Eq, Ne, exp, Function, I, Integral, LambertW, log, O, pi,
Rational, rootof, S, sin, sqrt, Subs, Symbol, tan, asin, sinh,
Piecewise, symbols, Poly, sec, re, im, atan2, collect)
from sympy.solvers.ode import (classify_ode,
homogeneous_order, infinitesimals, checkinfsol,
dsolve)
from sympy.solvers.ode.subscheck import checkodesol, checksysodesol
from sympy.solvers.ode.ode import (_linear_coeff_match,
_undetermined_coefficients_match, classify_sysode,
constant_renumber, constantsimp, get_numbered_constants, solve_ics)
from sympy.functions import airyai, airybi
from sympy.solvers.deutils import ode_order
from sympy.testing.pytest import XFAIL, skip, raises, slow, ON_TRAVIS
C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11')
u, x, y, z = symbols('u,x:z', real=True)
f = Function('f')
g = Function('g')
h = Function('h')
# Note: the tests below may fail (but still be correct) if ODE solver,
# the integral engine, solve(), or even simplify() changes. Also, in
# differently formatted solutions, the arbitrary constants might not be
# equal. Using specific hints in tests can help to avoid this.
# Tests of order higher than 1 should run the solutions through
# constant_renumber because it will normalize it (constant_renumber causes
# dsolve() to return different results on different machines)
def test_get_numbered_constants():
with raises(ValueError):
get_numbered_constants(None)
def test_dsolve_all_hint():
eq = f(x).diff(x)
output = dsolve(eq, hint='all')
# Match the Dummy variables:
sol1 = output['separable_Integral']
_y = sol1.lhs.args[1][0]
sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral']
_u1 = sol1.rhs.args[1].args[1][0]
expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_homogeneous_coeff_best': Eq(f(x), C1),
'Bernoulli': Eq(f(x), C1),
'nth_algebraic': Eq(f(x), C1),
'nth_linear_euler_eq_homogeneous': Eq(f(x), C1),
'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1),
'separable': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1),
'nth_algebraic_Integral': Eq(f(x), C1),
'1st_linear': Eq(f(x), C1),
'1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)),
'lie_group': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))),
'1st_power_series': Eq(f(x), C1),
'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)),
'1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1),
'best': Eq(f(x), C1),
'best_hint': 'nth_algebraic',
'default': 'nth_algebraic',
'order': 1}
assert output == expected
assert dsolve(eq, hint='best') == Eq(f(x), C1)
def test_dsolve_ics():
# Maybe this should just use one of the solutions instead of raising...
with raises(NotImplementedError):
dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1})
@slow
@XFAIL
def test_nonlinear_3eq_order1_type1():
if ON_TRAVIS:
skip("Too slow for travis.")
a, b, c = symbols('a b c')
eqs = [
a * f(x).diff(x) - (b - c) * g(x) * h(x),
b * g(x).diff(x) - (c - a) * h(x) * f(x),
c * h(x).diff(x) - (a - b) * f(x) * g(x),
]
assert dsolve(eqs) # NotImplementedError
def test_dsolve_euler_rootof():
eq = x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x)
sol = Eq(f(x),
C1*x
+ C2*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 0)
+ C3*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 1)
+ C4*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 2)
+ C5*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 3)
+ C6*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 4)
)
assert dsolve(eq) == sol
def test_nth_euler_imroot():
eq = x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x
sol = Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x))
dsolve_sol = dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters')
assert dsolve_sol == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_constant_coeff_circular_atan2():
eq = f(x).diff(x, x) + y*f(x)
sol = Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y)))
assert dsolve(eq) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
@XFAIL
def test_nonlinear_3eq_order1_type4():
eqs = [
Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))),
Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))),
Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))),
]
dsolve(eqs) # KeyError when matching
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
@slow
@XFAIL
def test_nonlinear_3eq_order1_type3():
if ON_TRAVIS:
skip("Too slow for travis.")
eqs = [
Eq(f(x).diff(x), (2*f(x)**2 - 3 )),
Eq(g(x).diff(x), (4 - 2*h(x) )),
Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)),
]
dsolve(eqs) # Not sure if this finishes...
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
@XFAIL
def test_nonlinear_3eq_order1_type5():
eqs = [
Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))),
Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))),
Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))),
]
dsolve(eqs) # KeyError
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
def test_linear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
k, l, m, n = symbols('k, l, m, n', Integer=True)
t = Symbol('t')
x0, y0 = symbols('x0, y0', cls=Function)
eq1 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23))
sol1 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \
Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23))
sol2 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \
Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))]
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t)))
sol3 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
sol4 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t)))
sol5 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t)))
sol6 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \
exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))]
s = dsolve(eq6)
assert s == sol6 # too complicated to test with subs and simplify
# assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails
def test_nonlinear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol1 = [
Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq1) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5))
sol2 = [
Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3))
tt = Rational(2, 3)
sol3 = [
Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)),
Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)]
assert dsolve(eq3) == sol3
# FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2))
sol4 = {Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))}
assert dsolve(eq4) == sol4
# FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2))
sol5 = {Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)}
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol6 = [
Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
@slow
def test_nonlinear_3eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t, u = symbols('t u')
eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t))
sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))),
C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)),
(u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)]
# FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0])
eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t))
sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 +
sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)),
(u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)]
# FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0])
@slow
def test_dsolve_options():
eq = x*f(x).diff(x) + f(x)
a = dsolve(eq, hint='all')
b = dsolve(eq, hint='all', simplify=False)
c = dsolve(eq, hint='all_Integral')
keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
'1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral',
'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
'default', 'lie_group',
'nth_linear_euler_eq_homogeneous', 'order',
'separable', 'separable_Integral']
Integral_keys = ['1st_exact_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral',
'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default',
'nth_linear_euler_eq_homogeneous',
'order', 'separable_Integral']
assert sorted(a.keys()) == keys
assert a['order'] == ode_order(eq, f(x))
assert a['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best') == Eq(f(x), C1/x)
assert a['default'] == 'separable'
assert a['best_hint'] == 'separable'
assert not a['1st_exact'].has(Integral)
assert not a['separable'].has(Integral)
assert not a['1st_homogeneous_coeff_best'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not a['1st_linear'].has(Integral)
assert a['1st_linear_Integral'].has(Integral)
assert a['1st_exact_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert a['separable_Integral'].has(Integral)
assert sorted(b.keys()) == keys
assert b['order'] == ode_order(eq, f(x))
assert b['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x)
assert b['default'] == 'separable'
assert b['best_hint'] == '1st_linear'
assert a['separable'] != b['separable']
assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
b['1st_homogeneous_coeff_subs_dep_div_indep']
assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
b['1st_homogeneous_coeff_subs_indep_div_dep']
assert not b['1st_exact'].has(Integral)
assert not b['separable'].has(Integral)
assert not b['1st_homogeneous_coeff_best'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not b['1st_linear'].has(Integral)
assert b['1st_linear_Integral'].has(Integral)
assert b['1st_exact_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert b['separable_Integral'].has(Integral)
assert sorted(c.keys()) == Integral_keys
raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
hint="1st_linear_Integral") == \
Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
exp(Integral(1, x)), x))*exp(-Integral(1, x)))
def test_classify_ode():
assert classify_ode(f(x).diff(x, 2), f(x)) == \
(
'nth_algebraic',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'Liouville',
'2nd_power_series_ordinary',
'nth_algebraic_Integral',
'Liouville_Integral',
)
assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral')
assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == (
'nth_algebraic',
'separable',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable',
'nth_algebraic',
'separable',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
# issue 4749: f(x) should be cleared from highest derivative before classifying
a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x))
b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x))
c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x))
assert a == ('1st_linear',
'Bernoulli',
'almost_linear',
'1st_power_series', "lie_group",
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert b == ('factorable',
'1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert c == ('1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert classify_ode(
2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x)
) == ('Bernoulli', 'almost_linear', 'lie_group',
'Bernoulli_Integral', 'almost_linear_Integral')
assert 'Riccati_special_minus2' in \
classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x))
raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff(
y), f(x, y)))
# issue 5176
k = Symbol('k')
assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) +
k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \
('separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
# preprocessing
ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral')
# w/o f(x) given
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans
# w/ f(x) and prep=True
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x),
prep=True) == ans
assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_linear',
'Bernoulli', '1st_power_series',
'lie_group', 'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'nth_algebraic_Integral',
'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral')
# test issue 13864
assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \
('1st_power_series', 'lie_group')
assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict)
def test_classify_ode_ics():
# Dummy
eq = f(x).diff(x, x) - f(x)
# Not f(0) or f'(0)
ics = {x: 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
############################
# f(0) type (AppliedUndef) #
############################
# Wrong function
ics = {g(0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(0, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(0): f(1)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(0): 1}
classify_ode(eq, f(x), ics=ics)
#####################
# f'(0) type (Subs) #
#####################
# Wrong function
ics = {g(x).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Wrong variable
ics = {f(y).diff(y).subs(y, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, y).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, 0): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): 1}
classify_ode(eq, f(x), ics=ics)
###########################
# f'(y) type (Derivative) #
###########################
# Wrong function
ics = {g(x).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, z).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, y): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, y): 1}
classify_ode(eq, f(x), ics=ics)
def test_classify_sysode():
# Here x is assumed to be x(t) and y as y(t) for simplicity.
# Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively.
k, l, m, n = symbols('k, l, m, n', Integer=True)
k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True)
P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function)
P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function)
x, y, z = symbols('x, y, z', cls=Function)
t = symbols('t')
x1 = diff(x(t),t) ; y1 = diff(y(t),t) ;
eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t))))
sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \
[x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \
y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq6) == sol6
eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t)))
sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \
'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \
Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq7) == sol7
eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)))
sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \
[-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \
Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \
(1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2}
assert classify_sysode(eq8) == sol8
eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5))
sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \
'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \
-y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq11) == sol11
eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2))
sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \
'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \
Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq13) == sol13
def test_solve_ics():
# Basic tests that things work from dsolve.
assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \
Eq(f(x), sqrt(2 * x + 2))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1,
f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x))
assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)],
[f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))]
# Test cases where dsolve returns two solutions.
eq = (x**2*f(x)**2 - x).diff(x)
assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x),
-sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)]
assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x),
-sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)]
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \
{C2: 1}
# Some more complicated tests Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)}
K, r, f0 = symbols('K r f0')
sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1)))
assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol
#Order dependent issues Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
# XXX: Ought to be ValueError
raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1}))
# Degenerate case. f'(0) is identically 0.
raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0}))
EI, q, L = symbols('EI q L')
# eq = Eq(EI*diff(f(x), x, 4), q)
sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))]
funcs = [f(x)]
constants = [C1, C2, C3, C4]
# Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)),
# and Subs
ics1 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
f(L).diff(L, 2): 0,
f(L).diff(L, 3): 0}
ics2 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
Subs(f(x).diff(x, 2), x, L): 0,
Subs(f(x).diff(x, 3), x, L): 0}
solved_constants1 = solve_ics(sols, funcs, constants, ics1)
solved_constants2 = solve_ics(sols, funcs, constants, ics2)
assert solved_constants1 == solved_constants2 == {
C1: 0,
C2: 0,
C3: L**2*q/(4*EI),
C4: -L*q/(6*EI)}
def test_ode_order():
f = Function('f')
g = Function('g')
x = Symbol('x')
assert ode_order(3*x*exp(f(x)), f(x)) == 0
assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1
assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2
assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3
assert ode_order(diff(f(x), x, x), g(x)) == 0
assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2
assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0
# issue 5835: ode_order has to also work for unevaluated derivatives
# (ie, without using doit()).
assert ode_order(Derivative(x*f(x), x), f(x)) == 1
assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2
assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0
assert ode_order(Derivative(f(x), x, x), g(x)) == 0
assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1
assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3
assert ode_order(
x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3
# In all tests below, checkodesol has the order option set to prevent
# superfluous calls to ode_order(), and the solve_for_func flag set to False
# because dsolve() already tries to solve for the function, unless the
# simplify=False option is set.
def test_old_ode_tests():
# These are simple tests from the old ode module
eq1 = Eq(f(x).diff(x), 0)
eq2 = Eq(3*f(x).diff(x) - 5, 0)
eq3 = Eq(3*f(x).diff(x), 5)
eq4 = Eq(9*f(x).diff(x, x) + f(x), 0)
eq5 = Eq(9*f(x).diff(x, x), f(x))
# Type: a(x)f'(x)+b(x)*f(x)+c(x)=0
eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0)
eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0)
# Type: 2nd order, constant coefficients (two real different roots)
eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0)
# Type: 2nd order, constant coefficients (two real equal roots)
eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0)
# Type: 2nd order, constant coefficients (two complex roots)
eq10 = Eq(3*f(x).diff(x) - 1, 0)
eq11 = Eq(x*f(x).diff(x) - 1, 0)
sol1 = Eq(f(x), C1)
sol2 = Eq(f(x), C1 + x*Rational(5, 3))
sol3 = Eq(f(x), C1 + x*Rational(5, 3))
sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3))
sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))
sol6 = Eq(f(x), (C1 - cos(x))/x**3)
sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x))
sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))
sol10 = Eq(f(x), C1 + x/3)
sol11 = Eq(f(x), C1 + log(x))
assert dsolve(eq1) == sol1
assert dsolve(eq1.lhs) == sol1
assert dsolve(eq2) == sol2
assert dsolve(eq3) == sol3
assert dsolve(eq4) == sol4
assert dsolve(eq5) == sol5
assert dsolve(eq6) == sol6
assert dsolve(eq7) == sol7
assert dsolve(eq8) == sol8
assert dsolve(eq9) == sol9
assert dsolve(eq10) == sol10
assert dsolve(eq11) == sol11
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0]
def test_homogeneous_order():
assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0
assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None
assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1
assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/
(pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6)
assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0
assert homogeneous_order(f(x), x, f(x)) == 1
assert homogeneous_order(f(x)**2, x, f(x)) == 2
assert homogeneous_order(x*y*z, x, y) == 2
assert homogeneous_order(x*y*z, x, y, z) == 3
assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2
assert homogeneous_order(f(x, y)**2, x, f(x), y) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None
assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None
assert homogeneous_order(f(y), f(x), x) is None
assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0
assert homogeneous_order(log(1/y) + log(x**2), x, y) is None
assert homogeneous_order(log(1/y) + log(x), x, y) == 0
assert homogeneous_order(log(x/y), x, y) == 0
assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0
a = Symbol('a')
assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0
assert homogeneous_order(f(x).diff(x), x, y) is None
assert homogeneous_order(-f(x).diff(x) + x, x, y) is None
assert homogeneous_order(O(x), x, y) is None
assert homogeneous_order(x + O(x**2), x, y) is None
assert homogeneous_order(x**pi, x) == pi
assert homogeneous_order(x**x, x) is None
raises(ValueError, lambda: homogeneous_order(x*y))
@slow
def test_1st_homogeneous_coeff_ode():
# Type: First order homogeneous, y'=f(y/x)
eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x)
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x)
eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x)
eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x)
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
eq8 = x + f(x) - (x - f(x))*f(x).diff(x)
sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))
sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))
sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x)))
sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)
sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)
sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))
sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))
# indep_div_dep actually has a simpler solution for eq2,
# but it runs too slow
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3
assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4
assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5
assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol6
assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7
assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8
# FIXME: sol3 and sol5 don't work with checkodesol (because of LambertW?)
# previous code was testing with these other solutions:
sol3b = Eq(-f(x)/(1 + log(x/f(x))), C1)
sol5b = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5b, order=1, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check2():
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
sol2 = Eq(x/tan(f(x)/(2*x)), C1)
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check3():
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
# This solution is correct:
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1)))
assert dsolve(eq3) == sol3
# FIXME: Checked in test_1st_homogeneous_coeff_ode_check3_check below
# Alternate form:
sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x)))
assert checkodesol(eq3, sol3a, solve_for_func=True)[0]
@XFAIL
def test_1st_homogeneous_coeff_ode_check3_check():
# See test_1st_homogeneous_coeff_ode_check3 above
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1)))
assert checkodesol(eq3, sol3) == (True, 0) # XFAIL
def test_1st_homogeneous_coeff_ode_check7():
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))
assert dsolve(eq7) == sol7
assert checkodesol(eq7, sol7, order=1, solve_for_func=False) == (True, 0)
def test_1st_homogeneous_coeff_ode2():
eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x)
eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x)
eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x)
sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))]
sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1))
sol3 = Eq(f(x), log((1/(C1 - log(x)))**x))
# specific hints are applied for speed reasons
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3
# FIXME: sol3 doesn't work with checkodesol (because of **x?)
# previous code was testing with this other solution:
sol3b = Eq(f(x), log(log(C1/x)**(-x)))
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check9():
_u2 = Dummy('u2')
__a = Dummy('a')
eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a,
x/f(x))) + log(C1*f(x)), 0)
assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode3():
# The standard integration engine cannot handle one of the integrals
# involved (see issue 4551). meijerg code comes up with an answer, but in
# unconventional form.
# checkodesol fails for this equation, so its test is in
# test_1st_homogeneous_coeff_ode_check9 above. It has to compare string
# expressions because u2 is a dummy variable.
eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol = Eq(log(f(x)), C1 + Piecewise(
(acosh(f(x)/x), abs(f(x)**2)/x**2 > 1),
(-I*asin(f(x)/x), True)))
assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol
def test_1st_homogeneous_coeff_corner_case():
eq1 = f(x).diff(x) - f(x)/x
c1 = classify_ode(eq1, f(x))
eq2 = x*f(x).diff(x) - f(x)
c2 = classify_ode(eq2, f(x))
sdi = "1st_homogeneous_coeff_subs_dep_div_indep"
sid = "1st_homogeneous_coeff_subs_indep_div_dep"
assert sid not in c1 and sdi not in c1
assert sid not in c2 and sdi not in c2
@slow
def test_nth_linear_constant_coeff_homogeneous():
# From Exercise 20, in Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 220
a = Symbol('a', positive=True)
k = Symbol('k', real=True)
eq1 = f(x).diff(x, 2) + 2*f(x).diff(x)
eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x)
eq3 = f(x).diff(x, 2) - f(x)
eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x)
eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x)
eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0)
eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x)
eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x)
eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \
4*f(x).diff(x) - 2*f(x)
eq10 = f(x).diff(x, 4) - a**2*f(x)
eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x)
eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x)
eq13 = f(x).diff(x, 4)
eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x)
eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x)
eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x)
eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x)
eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3)
eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2)
eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \
12*f(x).diff(x) + 36*f(x)
eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x)
eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x)
eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x)
eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x)
eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x)
eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x)
eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x)
eq28 = f(x).diff(x, 3) + 8*f(x)
eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2)
eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x)
eq31 = f(x).diff(x, 4) + f(x).diff(x, 2) + f(x)
eq32 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x)
sol1 = Eq(f(x), C1 + C2*exp(-2*x))
sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x))
sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))
sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))
sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1)))
sol7 = Eq(f(x), C3*exp(3*x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))
sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x))
sol9 = Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))
sol10 = Eq(f(x),
C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) +
C4*exp(-x*sqrt(a)))
sol11 = Eq(f(x),
C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))
sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))
sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)
sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x))
sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))
sol16 = Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x))
sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x))
sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))
sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2)))
sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))
sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(x*Rational(5, 6)))
sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))
sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))
sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))
sol25 = Eq(f(x),
C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) +
C4*cos(x*sqrt(2)))
sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))
sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))
sol28 = Eq(f(x),
(C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))
sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x)
sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))
sol31 = Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))/sqrt(exp(x))
+ (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*sqrt(exp(x)))
sol32 = Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2))
+ C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2)))
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
sol13s = constant_renumber(sol13)
sol14s = constant_renumber(sol14)
sol15s = constant_renumber(sol15)
sol16s = constant_renumber(sol16)
sol17s = constant_renumber(sol17)
sol18s = constant_renumber(sol18)
sol19s = constant_renumber(sol19)
sol20s = constant_renumber(sol20)
sol21s = constant_renumber(sol21)
sol22s = constant_renumber(sol22)
sol23s = constant_renumber(sol23)
sol24s = constant_renumber(sol24)
sol25s = constant_renumber(sol25)
sol26s = constant_renumber(sol26)
sol27s = constant_renumber(sol27)
sol28s = constant_renumber(sol28)
sol29s = constant_renumber(sol29)
sol30s = constant_renumber(sol30)
assert dsolve(eq1) in (sol1, sol1s)
assert dsolve(eq2) in (sol2, sol2s)
assert dsolve(eq3) in (sol3, sol3s)
assert dsolve(eq4) in (sol4, sol4s)
assert dsolve(eq5) in (sol5, sol5s)
assert dsolve(eq6) in (sol6, sol6s)
got = dsolve(eq7)
assert got in (sol7, sol7s), got
assert dsolve(eq8) in (sol8, sol8s)
got = dsolve(eq9)
assert got in (sol9, sol9s), got
assert dsolve(eq10) in (sol10, sol10s)
assert dsolve(eq11) in (sol11, sol11s)
assert dsolve(eq12) in (sol12, sol12s)
assert dsolve(eq13) in (sol13, sol13s)
assert dsolve(eq14) in (sol14, sol14s)
assert dsolve(eq15) in (sol15, sol15s)
got = dsolve(eq16)
assert got in (sol16, sol16s), got
assert dsolve(eq17) in (sol17, sol17s)
assert dsolve(eq18) in (sol18, sol18s)
assert dsolve(eq19) in (sol19, sol19s)
assert dsolve(eq20) in (sol20, sol20s)
assert dsolve(eq21) in (sol21, sol21s)
assert dsolve(eq22) in (sol22, sol22s)
assert dsolve(eq23) in (sol23, sol23s)
assert dsolve(eq24) in (sol24, sol24s)
assert dsolve(eq25) in (sol25, sol25s)
assert dsolve(eq26) in (sol26, sol26s)
assert dsolve(eq27) in (sol27, sol27s)
assert dsolve(eq28) in (sol28, sol28s)
assert dsolve(eq29) in (sol29, sol29s)
assert dsolve(eq30) in (sol30, sol30s)
assert dsolve(eq31) in (sol31,)
assert dsolve(eq32) in (sol32,)
assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0]
assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0]
assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0]
assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0]
assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0]
assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0]
assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0]
assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0]
assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0]
assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0]
assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0]
assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0]
assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0]
assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0]
assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0]
assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0]
assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0]
assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0]
assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0]
assert checkodesol(eq31, sol31, order=4, solve_for_func=False)[0]
assert checkodesol(eq32, sol32, order=4, solve_for_func=False)[0]
# Issue #15237
eqn = Derivative(x*f(x), x, x, x)
hint = 'nth_linear_constant_coeff_homogeneous'
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=True))
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=False))
def test_nth_linear_constant_coeff_homogeneous_rootof():
# One real root, two complex conjugate pairs
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(r1*x)
+ exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x))
+ exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Three real roots, one complex conjugate pair
eq = f(x).diff(x,5) - 3*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 3*x + 1, n) for n in range(5)]
sol = Eq(f(x),
C3*exp(r1*x) + C4*exp(r2*x) + C5*exp(r3*x)
+ exp(re(r4)*x) * (C1*sin(im(r4)*x) + C2*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five distinct real roots
eq = f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)]
sol = Eq(f(x), C1*exp(r1*x) + C2*exp(r2*x) + C3*exp(r3*x) + C4*exp(r4*x) + C5*exp(r5*x))
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Rational root and unsolvable quintic
eq = f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x)
r2, r3, r4, r5, r6 = [rootof(x**5 - x**4 + 10, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(5*x)
+ C6*exp(x*r2)
+ exp(re(r3)*x) * (C1*sin(im(r3)*x) + C2*cos(im(r3)*x))
+ exp(re(r5)*x) * (C3*sin(im(r5)*x) + C4*cos(im(r5)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five double roots (this is (x**5 - x + 1)**2)
eq = f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - x + 1, n) for n in range(5)]
sol = Eq(f(x), (C1 + C2*x)*exp(x*r1) + (C10*sin(x*im(r4)) + C7*x*sin(x*im(r4)) + (
C8 + C9*x)*cos(x*im(r4)))*exp(x*re(r4)) + (C3*x*sin(x*im(r2)) + C6*sin(x*im(r2)
) + (C4 + C5*x)*cos(x*im(r2)))*exp(x*re(r2)))
got = dsolve(eq)
assert sol == got, got
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
def test_nth_linear_constant_coeff_homogeneous_irrational():
our_hint='nth_linear_constant_coeff_homogeneous'
eq = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
E = exp(1)
eq = Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
@XFAIL
@slow
def test_nth_linear_constant_coeff_homogeneous_rootof_sol():
# See https://github.com/sympy/sympy/issues/15753
if ON_TRAVIS:
skip("Too slow for travis.")
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
sol = Eq(f(x),
C1*exp(x*rootof(x**5 + 11*x - 2, 0)) +
C2*exp(x*rootof(x**5 + 11*x - 2, 1)) +
C3*exp(x*rootof(x**5 + 11*x - 2, 2)) +
C4*exp(x*rootof(x**5 + 11*x - 2, 3)) +
C5*exp(x*rootof(x**5 + 11*x - 2, 4)))
assert checkodesol(eq, sol, order=5, solve_for_func=False)[0]
@XFAIL
def test_noncircularized_real_imaginary_parts():
# If this passes, lines numbered 3878-3882 (at the time of this commit)
# of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous
# should be removed.
y = sqrt(1+x)
i, r = im(y), re(y)
assert not (i.has(atan2) and r.has(atan2))
def test_collect_respecting_exponentials():
# If this test passes, lines 1306-1311 (at the time of this commit)
# of sympy/solvers/ode.py should be removed.
sol = 1 + exp(x/2)
assert sol == collect( sol, exp(x/3))
def test_undetermined_coefficients_match():
assert _undetermined_coefficients_match(g(x), x) == {'test': False}
assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \
{'test': True, 'trialset':
{cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}}
assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
{'test': False}
s = {cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
exp(2*x)*sin(x)*(x**2 + x + 1), x
) == {
'test': True, 'trialset': {exp(2*x)*sin(x), x**2*exp(2*x)*sin(x),
cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x),
x*exp(2*x)*sin(x)}}
assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False}
assert _undetermined_coefficients_match(log(x), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}}
assert _undetermined_coefficients_match(x**y, x) == {'test': False}
assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \
{'test': True, 'trialset': {exp(1 + 3*x)}}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x),
x**2*sin(x), cos(x), sin(x)}}
assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \
{'test': False}
assert _undetermined_coefficients_match(
x**2*sin(x)*exp(x) + x*sin(x) + x, x
) == {
'test': True, 'trialset': {x**2*cos(x)*exp(x), x, cos(x), S.One,
exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x),
x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)}}
assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == {
'trialset': {x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)},
'test': True,
}
assert _undetermined_coefficients_match(2**x*x, x) == \
{'test': True, 'trialset': {2**x, x*2**x}}
assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
{'test': True, 'trialset': {2**x*exp(2*x)}}
assert _undetermined_coefficients_match(exp(-x)/x, x) == \
{'test': False}
# Below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
assert _undetermined_coefficients_match(S(4), x) == \
{'test': True, 'trialset': {S.One}}
assert _undetermined_coefficients_match(12*exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
assert _undetermined_coefficients_match(exp(I*x), x) == \
{'test': True, 'trialset': {exp(I*x)}}
assert _undetermined_coefficients_match(sin(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(cos(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
{'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}}
assert _undetermined_coefficients_match(x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
{'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
{'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}}
assert _undetermined_coefficients_match(x - sin(x), x) == \
{'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(4*x*sin(x), x) == \
{'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}}
assert _undetermined_coefficients_match(x*sin(2*x), x) == \
{'test': True, 'trialset':
{x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}}
assert _undetermined_coefficients_match(x**2*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}}
assert _undetermined_coefficients_match(x*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(x + exp(2*x), x) == \
{'test': True, 'trialset': {S.One, x, exp(2*x)}}
assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
{'test': True, 'trialset': {cos(x), sin(x), exp(-x)}}
assert _undetermined_coefficients_match(exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
# converted from sin(x)**2
assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
{'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}}
# converted from exp(2*x)*sin(x)**2
assert _undetermined_coefficients_match(
exp(2*x)*(S.Half + cos(2*x)/2), x
) == {
'test': True, 'trialset': {exp(2*x)*sin(2*x), cos(2*x)*exp(2*x),
exp(2*x)}}
assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \
{'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
# converted from sin(2*x)*sin(x)
assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \
{'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}}
assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
def test_issue_12623():
t = symbols("t")
u = symbols("u",cls=Function)
R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True)
omega = Symbol('omega')
eqRLC_1 = Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha)
sol_1 = Eq(u(t), C*L*alpha + C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)))
assert dsolve(eqRLC_1) == sol_1
assert checkodesol(eqRLC_1, sol_1) == (True, 0)
eqRLC_2 = Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) )
sol_2 = Eq(u(t),
C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ E_0*exp(I*omega*t)/(-C*L*omega**2 + I*C*R*omega + 1))
assert dsolve(eqRLC_2) == sol_2
assert checkodesol(eqRLC_2, sol_2) == (True, 0)
#issue-https://github.com/sympy/sympy/issues/12623
def test_unexpanded_Liouville_ODE():
# This is the same as eq1 from test_Liouville_ODE() above.
eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2
eq2 = eq1*exp(-f(x))/exp(f(x))
sol2 = Eq(f(x), C1 + log(x) - log(C2 + x))
sol2s = constant_renumber(sol2)
assert dsolve(eq2) in (sol2, sol2s)
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
def test_issue_4785():
from sympy.abc import A
eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2
assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral', 'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
# issue 4864
eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x)
assert classify_ode(eq, f(x)) == ('1st_exact',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group', '1st_exact_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
def test_issue_4825():
raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x)))
assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
# See also issue 3793, test Z13.
raises(ValueError, lambda: dsolve(f(x).diff(x), f(y)))
assert classify_ode(f(x).diff(x), f(y), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
def test_constant_renumber_order_issue_5308():
from sympy.utilities.iterables import variations
assert constant_renumber(C1*x + C2*y) == \
constant_renumber(C1*y + C2*x) == \
C1*x + C2*y
e = C1*(C2 + x)*(C3 + y)
for a, b, c in variations([C1, C2, C3], 3):
assert constant_renumber(a*(b + x)*(c + y)) == e
def test_constant_renumber():
e1, e2, x, y = symbols("e1:3 x y")
exprs = [e2*x, e1*x + e2*y]
assert constant_renumber(exprs[0]) == e2*x
assert constant_renumber(exprs[0], variables=[x]) == C1*x
assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x
assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x]
assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x]
def test_issue_5770():
k = Symbol("k", real=True)
t = Symbol('t')
w = Function('w')
sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t))
assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6
assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), {C1, C2}) == \
C1*cos(x)*exp(x)
assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), {C1, C2, C3}) == \
C1*cos(x) + C3*sin(x)
assert constantsimp(exp(C1 + x), {C1}) == C1*exp(x)
assert constantsimp(x + C1 + y, {C1, y}) == C1 + x
assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), {C1}) == C1 + x
def test_issue_5112_5430():
assert homogeneous_order(-log(x) + acosh(x), x) is None
assert homogeneous_order(y - log(x), x, y) is None
def test_issue_5095():
f = Function('f')
raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf'))
def test_exact_enhancement():
f = Function('f')(x)
df = Derivative(f, x)
eq = f/x**2 + ((f*x - 1)/x)*df
sol = [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x*f - 1) + df*(x**2 - x*f)
sol = [Eq(f, x - sqrt(C1 + x**2 - 2*log(x))),
Eq(f, x + sqrt(C1 + x**2 - 2*log(x)))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x + 2)*sin(f) + df*x*cos(f)
sol = [Eq(f, -asin(C1*exp(-x)/x**2) + pi),
Eq(f, asin(C1*exp(-x)/x**2))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
def test_homogeneous_function():
f = Function('f')
eq1 = tan(x + f(x))
eq2 = sin((3*x)/(4*f(x)))
eq3 = cos(x*f(x)*Rational(3, 4))
eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x))
eq5 = exp((2*x**2)/(3*f(x)**2))
eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2)))
eq7 = sin((3*x)/(5*f(x) + x**2))
assert homogeneous_order(eq1, x, f(x)) == None
assert homogeneous_order(eq2, x, f(x)) == 0
assert homogeneous_order(eq3, x, f(x)) == None
assert homogeneous_order(eq4, x, f(x)) == 0
assert homogeneous_order(eq5, x, f(x)) == 0
assert homogeneous_order(eq6, x, f(x)) == 0
assert homogeneous_order(eq7, x, f(x)) == None
def test_linear_coeff_match():
n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11)
rat = n/d
eq1 = sin(rat) + cos(rat.expand())
eq2 = rat
eq3 = log(sin(rat))
ans = (4, Rational(-13, 3))
assert _linear_coeff_match(eq1, f(x)) == ans
assert _linear_coeff_match(eq2, f(x)) == ans
assert _linear_coeff_match(eq3, f(x)) == ans
# no c
eq4 = (3*x)/f(x)
# not x and f(x)
eq5 = (3*x + 2)/x
# denom will be zero
eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5)
# not rational coefficient
eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5)
assert _linear_coeff_match(eq4, f(x)) is None
assert _linear_coeff_match(eq5, f(x)) is None
assert _linear_coeff_match(eq6, f(x)) is None
assert _linear_coeff_match(eq7, f(x)) is None
def test_linear_coefficients():
f = Function('f')
sol = Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))
eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3)
assert dsolve(eq, hint='linear_coefficients') == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_constantsimp_take_problem():
c = exp(C1) + 2
assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2
def test_issue_6879():
f = Function('f')
eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x))
sol = (C1 + C2*x)*exp(x) + cos(x)/2
assert dsolve(eq).rhs == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_issue_6989():
f = Function('f')
k = Symbol('k')
eq = f(x).diff(x) - x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = -f(x).diff(x) + x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_heuristic1():
y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0")
f = Function('f')
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
eq = Eq(df, x**2*f(x))
eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x)
eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2)
eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x))
eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2)
eq5 = x**2*df - f(x) + x**2*exp(x - (1/x))
eqlist = [eq, eq1, eq2, eq3, eq4, eq5]
i = infinitesimals(eq, hint='abaco1_simple')
assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0},
{eta(x, f(x)): f(x), xi(x, f(x)): 0},
{eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}]
i1 = infinitesimals(eq1, hint='abaco1_simple')
assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}]
i2 = infinitesimals(eq2, hint='abaco1_simple')
assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}]
i3 = infinitesimals(eq3, hint='abaco1_simple')
assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1},
{eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}]
i4 = infinitesimals(eq4, hint='abaco1_simple')
assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0},
{eta(x, f(x)): 0,
xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}]
i5 = infinitesimals(eq5, hint='abaco1_simple')
assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}]
ilist = [i, i1, i2, i3, i4, i5]
for eq, i in (zip(eqlist, ilist)):
check = checkinfsol(eq, i)
assert check[0]
def test_issue_6247():
eq = f(x).diff(x, x) + 4*f(x)
sol = Eq(f(x), C1*sin(2*x) + C2*cos(2*x))
assert dsolve(eq) == sol
assert checkodesol(eq, sol, order=1)[0]
def test_heuristic2():
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
# This ODE can be solved by the Lie Group method, when there are
# better assumptions
eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2)
i = infinitesimals(eq, hint='abaco1_product')
assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
@slow
def test_heuristic3():
xi = Function('xi')
eta = Function('eta')
a, b = symbols("a b")
df = f(x).diff(x)
eq = x**2*df + x*f(x) + f(x)**2 + x**2
i = infinitesimals(eq, hint='bivariate')
assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}]
assert checkinfsol(eq, i)[0]
eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x
i = infinitesimals(eq, hint='bivariate')
assert checkinfsol(eq, i)[0]
def test_heuristic_4():
y, a = symbols("y a")
eq = x*(f(x).diff(x)) + 1 - f(x)**2
i = infinitesimals(eq, hint='chi')
assert checkinfsol(eq, i)[0]
def test_heuristic_function_sum():
xi = Function('xi')
eta = Function('eta')
eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x +
(1 - 3*f(x))*(x/f(x)**2))
i = infinitesimals(eq, hint='function_sum')
assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_similar():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
eq = f(x).diff(x) - F(a*x + b*f(x))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x)))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_unique_unknown():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
x = Symbol("x", positive=True)
eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b)
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x)))
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}]
assert checkinfsol(eq, i)[0]
eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert checkinfsol(eq, i)[0]
def test_heuristic_linear():
a, b, m, n = symbols("a b m n")
eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1))
i = infinitesimals(eq, hint='linear')
assert checkinfsol(eq, i)[0]
@XFAIL
def test_kamke():
a, b, alpha, c = symbols("a b alpha c")
eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c
i = infinitesimals(eq, hint='sum_function') # XFAIL
assert checkinfsol(eq, i)[0]
def test_series():
C1 = Symbol("C1")
eq = f(x).diff(x) - f(x)
sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 +
C1*x**5/120 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - x*f(x)
sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - sin(x*f(x))
sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3))
assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol
# FIXME: The solution here should be O((x-2)**3) so is incorrect
#assert checkodesol(eq, sol, order=1)[0]
@XFAIL
def test_lie_group_issue15219():
eqn = exp(f(x).diff(x)-f(x))
assert 'lie_group' not in classify_ode(eqn, f(x))
def test_user_infinitesimals():
x = Symbol("x") # assuming x is real generates an error
eq = x*(f(x).diff(x)) + 1 - f(x)**2
sol = Eq(f(x), (C1 + x**2)/(C1 - x**2))
infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0}
assert dsolve(eq, hint='lie_group', **infinitesimals) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_7081():
eq = x*(f(x).diff(x)) + 1 - f(x)**2
s = Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2))
assert dsolve(eq) == s
assert checkodesol(eq, s) == (True, 0)
@slow
def test_2nd_power_series_ordinary():
C1, C2 = symbols("C1 C2")
eq = f(x).diff(x, 2) - x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary') == sol
assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1)
+ C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2))
+ O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol
# FIXME: Solution should be O((x+2)**6)
# assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*x + C1 + O(x**2))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1)
+ C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_Airy_equation():
eq = f(x).diff(x, 2) - x*f(x)
sol = Eq(f(x), C1*airyai(x) + C2*airybi(x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
eq = f(x).diff(x, 2) + 2*x*f(x)
sol = Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
def test_2nd_power_series_regular():
C1, C2 = symbols("C1 C2")
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 +
1)*f(x)
sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + (
x**2 - 2)*f(x)
sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x +
C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x)
sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) +
C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_7093():
x = Symbol("x") # assuming x is real leads to an error
sol = [Eq(f(x), C1 - 2*x*sqrt(x**3)/5),
Eq(f(x), C1 + 2*x*sqrt(x**3)/5)]
eq = Derivative(f(x), x)**2 - x**3
assert set(dsolve(eq)) == set(sol)
assert checkodesol(eq, sol) == [(True, 0)] * 2
def test_dsolve_linsystem_symbol():
eps = Symbol('epsilon', positive=True)
eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x)))
sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)),
Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
def test_C1_function_9239():
t = Symbol('t')
C1 = Function('C1')
C2 = Function('C2')
C3 = Symbol('C3')
C4 = Symbol('C4')
eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t)))
sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)),
Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0])
def test_issue_15056():
t = Symbol('t')
C3 = Symbol('C3')
assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3
def test_issue_10379():
t,y = symbols('t,y')
eq = f(t).diff(t)-(1-51.05*y*f(t))
sol = Eq(f(t), (0.019588638589618*exp(y*(C1 - 51.05*t)) + 0.019588638589618)/y)
dsolve_sol = dsolve(eq, rational=False)
assert str(dsolve_sol) == str(sol)
assert checkodesol(eq, dsolve_sol)[0]
def test_issue_10867():
x = Symbol('x')
eq = Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3)
sol = Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2)
assert dsolve(eq, g(x)) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_issue_4838():
# Issue #15999
eq = f(x).diff(x) - C1*f(x)
sol = Eq(f(x), C2*exp(C1*x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
# Issue #13691
eq = f(x).diff(x) - C1*g(x).diff(x)
sol = Eq(f(x), C2 + C1*g(x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, f(x), order=1, solve_for_func=False) == (True, 0)
# Issue #4838
eq = f(x).diff(x) - 3*C1 - 3*x**2
sol = Eq(f(x), C2 + 3*C1*x + x**3)
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
@slow
def test_issue_14395():
eq = Derivative(f(x), x, x) + 9*f(x) - sec(x)
sol = Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x))
- 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x))
assert dsolve(eq, f(x)) == sol
# FIXME: assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
# Needs to be a way to know how to combine derivatives in the expression
def test_factoring_ode():
from sympy import Mul
eqn = Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x)
# 2-arg Mul!
soln = Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False))
assert checkodesol(eqn, soln, order=2, solve_for_func=False)[0]
assert soln == dsolve(eqn, f(x))
def test_issue_11542():
m = 96
g = 9.8
k = .2
f1 = g * m
t = Symbol('t')
v = Function('v')
v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0)
assert str(v_equation) == \
'Eq(v(t), -68.585712797929/tanh(C1 - 0.142886901662352*t))'
def test_issue_15913():
eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x)
sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x)
assert checkodesol(eq, sol) == (True, 0)
sol = C1 + C2*exp(-x*y)
eq = Derivative(y*f(x), x) + f(x).diff(x, 2)
assert checkodesol(eq, sol, f(x)) == (True, 0)
def test_issue_16146():
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)]))
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)]))
def test_dsolve_remove_redundant_solutions():
eq = (f(x)-2)*f(x).diff(x)
sol = Eq(f(x), C1)
assert dsolve(eq) == sol
eq = (f(x)-sin(x))*(f(x).diff(x, 2))
sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))}
assert set(dsolve(eq)) == sol
eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3)
sol = Eq(f(x), C1 + C2*x + C3*x**2)
assert dsolve(eq) == sol
def test_issue_17322():
eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x))
sol = [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
eq = f(x).diff(x)*(f(x).diff(x)+f(x))
sol = [Eq(f(x), C1), Eq(f(x), C1*exp(-x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
def test_issue_13060():
A, B = symbols("A B", cls=Function)
t = Symbol("t")
eq = [Eq(Derivative(A(t), t), A(t)*B(t)), Eq(Derivative(B(t), t), A(t)*B(t))]
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, [0, 0])
|
582e57c0135f8d11ea7a5084bf1e2c3a3fd02e4b0f95ba2dcea817cdcd081789 | #
# The main tests for the code in single.py are currently located in
# sympy/solvers/tests/test_ode.py
#
r"""
This File contains test functions for the individual hints used for solving ODEs.
Examples of each solver will be returned by _get_examples_ode_sol_name_of_solver.
Examples should have a key 'XFAIL' which stores the list of hints if they are
expected to fail for that hint.
Functions that are for internal use:
1) _ode_solver_test(ode_examples) - It takes dictionary of examples returned by
_get_examples method and tests them with their respective hints.
2) _test_particular_example(our_hint, example_name) - It tests the ODE example corresponding
to the hint provided.
3) _test_all_hints(runxfail=False) - It is used to test all the examples with all the hints
currently implemented. It calls _test_all_examples_for_one_hint() which outputs whether the
given hint functions properly if it classifies the ODE example.
If runxfail flag is set to True then it will only test the examples which are expected to fail.
Everytime the ODE of partiular solver are added then _test_all_hints() is to execuetd to find
the possible failures of different solver hints.
4) _test_all_examples_for_one_hint(our_hint, all_examples) - It takes hint as argument and checks
this hint against all the ODE examples and gives output as the number of ODEs matched, number
of ODEs which were solved correctly, list of ODEs which gives incorrect solution and list of
ODEs which raises exception.
"""
from sympy import (acos, asin, asinh, atan, cos, Derivative, Dummy, diff,
E, Eq, exp, hyper, I, Integral, integrate, LambertW, log, Ne, pi, Piecewise, Rational, S, sin, sinh, tan,
sqrt, symbols, Ei, erfi)
from sympy.core import Function, Symbol
from sympy.functions import airyai, airybi, besselj, bessely
from sympy.integrals.risch import NonElementaryIntegral
from sympy.solvers.ode import classify_ode, dsolve
from sympy.solvers.ode.ode import allhints, _remove_redundant_solutions
from sympy.solvers.ode.single import (FirstLinear, ODEMatchError,
SingleODEProblem, SingleODESolver)
from sympy.solvers.ode.subscheck import checkodesol
from sympy.testing.pytest import raises, slow, ON_TRAVIS
import traceback
x = Symbol('x')
u = Symbol('u')
y = Symbol('y')
f = Function('f')
g = Function('g')
C1, C2, C3, C4, C5 = symbols('C1:6')
hint_message = """\
Hint did not match the example {example}.
The ODE is:
{eq}.
The expected hint was
{our_hint}\
"""
expected_sol_message = """\
Different solution found from dsolve for example {example}.
The ODE is:
{eq}
The expected solution was
{sol}
What dsolve returned is:
{dsolve_sol}\
"""
checkodesol_msg = """\
solution found is not correct for example {example}.
The ODE is:
{eq}\
"""
dsol_incorrect_msg = """\
solution returned by dsolve is incorrect when using {hint}.
The ODE is:
{eq}
The expected solution was
{sol}
what dsolve returned is:
{dsolve_sol}
You can test this with:
eq = {eq}
sol = dsolve(eq, hint='{hint}')
print(sol)
print(checkodesol(eq, sol))
"""
exception_msg = """\
dsolve raised exception : {e}
when using {hint} for the example {example}
You can test this with:
from sympy.solvers.ode.tests.test_single import _test_an_example
_test_an_example('{hint}', example_name = '{example}')
The ODE is:
{eq}
\
"""
check_hint_msg = """\
Tested hint was : {hint}
Total of {matched} examples matched with this hint.
Out of which {solve} gave correct results.
Examples which gave incorrect results are {unsolve}.
Examples which raised exceptions are {exceptions}
\
"""
def _add_example_keys(func):
def inner():
solver=func()
examples=[]
for example in solver['examples']:
temp={
'eq': solver['examples'][example]['eq'],
'sol': solver['examples'][example]['sol'],
'XFAIL': solver['examples'][example].get('XFAIL', []),
'func': solver['examples'][example].get('func',solver['func']),
'example_name': example,
'slow': solver['examples'][example].get('slow', False),
'simplify_flag':solver['examples'][example].get('simplify_flag',True),
'checkodesol_XFAIL': solver['examples'][example].get('checkodesol_XFAIL', False),
'dsolve_too_slow':solver['examples'][example].get('dsolve_too_slow',False),
'checkodesol_too_slow':solver['examples'][example].get('checkodesol_too_slow',False),
'hint': solver['hint']
}
examples.append(temp)
return examples
return inner()
def _ode_solver_test(ode_examples, run_slow_test=False):
for example in ode_examples:
if ((not run_slow_test) and example['slow']) or (run_slow_test and (not example['slow'])):
continue
result = _test_particular_example(example['hint'], example, solver_flag=True)
if result['xpass_msg'] != "":
print(result['xpass_msg'])
def _test_all_hints(runxfail=False):
all_hints = list(allhints)+["default"]
all_examples = _get_all_examples()
for our_hint in all_hints:
if our_hint.endswith('_Integral') or 'series' in our_hint:
continue
_test_all_examples_for_one_hint(our_hint, all_examples, runxfail)
def _test_dummy_sol(expected_sol,dsolve_sol):
if type(dsolve_sol)==list:
return any(expected_sol.dummy_eq(sub_dsol) for sub_dsol in dsolve_sol)
else:
return expected_sol.dummy_eq(dsolve_sol)
def _test_an_example(our_hint, example_name):
all_examples = _get_all_examples()
for example in all_examples:
if example['example_name'] == example_name:
_test_particular_example(our_hint, example)
def _test_particular_example(our_hint, ode_example, solver_flag=False):
eq = ode_example['eq']
expected_sol = ode_example['sol']
example = ode_example['example_name']
xfail = our_hint in ode_example['XFAIL']
func = ode_example['func']
result = {'msg': '', 'xpass_msg': ''}
simplify_flag=ode_example['simplify_flag']
checkodesol_XFAIL = ode_example['checkodesol_XFAIL']
dsolve_too_slow = ode_example['dsolve_too_slow']
checkodesol_too_slow = ode_example['checkodesol_too_slow']
xpass = True
if solver_flag:
if our_hint not in classify_ode(eq, func):
message = hint_message.format(example=example, eq=eq, our_hint=our_hint)
raise AssertionError(message)
if our_hint in classify_ode(eq, func):
result['match_list'] = example
try:
if not (dsolve_too_slow):
dsolve_sol = dsolve(eq, func, simplify=simplify_flag,hint=our_hint)
else:
if len(expected_sol)==1:
dsolve_sol = expected_sol[0]
else:
dsolve_sol = expected_sol
except Exception as e:
dsolve_sol = []
result['exception_list'] = example
if not solver_flag:
traceback.print_exc()
result['msg'] = exception_msg.format(e=str(e), hint=our_hint, example=example, eq=eq)
if solver_flag and not xfail:
print(result['msg'])
raise
xpass = False
if solver_flag and dsolve_sol!=[]:
expect_sol_check = False
if type(dsolve_sol)==list:
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
else:
expect_sol_check = sub_sol not in dsolve_sol
if expect_sol_check:
break
else:
expect_sol_check = dsolve_sol not in expected_sol
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
if expect_sol_check:
message = expected_sol_message.format(example=example, eq=eq, sol=expected_sol, dsolve_sol=dsolve_sol)
raise AssertionError(message)
expected_checkodesol = [(True, 0) for i in range(len(expected_sol))]
if len(expected_sol) == 1:
expected_checkodesol = (True, 0)
if not (checkodesol_too_slow and ON_TRAVIS):
if not checkodesol_XFAIL:
if checkodesol(eq, dsolve_sol, solve_for_func=False) != expected_checkodesol:
result['unsolve_list'] = example
xpass = False
message = dsol_incorrect_msg.format(hint=our_hint, eq=eq, sol=expected_sol,dsolve_sol=dsolve_sol)
if solver_flag:
message = checkodesol_msg.format(example=example, eq=eq)
raise AssertionError(message)
else:
result['msg'] = 'AssertionError: ' + message
if xpass and xfail:
result['xpass_msg'] = example + "is now passing for the hint" + our_hint
return result
def _test_all_examples_for_one_hint(our_hint, all_examples=[], runxfail=None):
if all_examples == []:
all_examples = _get_all_examples()
match_list, unsolve_list, exception_list = [], [], []
for ode_example in all_examples:
xfail = our_hint in ode_example['XFAIL']
if runxfail and not xfail:
continue
if xfail:
continue
result = _test_particular_example(our_hint, ode_example)
match_list += result.get('match_list',[])
unsolve_list += result.get('unsolve_list',[])
exception_list += result.get('exception_list',[])
if runxfail is not None:
msg = result['msg']
if msg!='':
print(result['msg'])
# print(result.get('xpass_msg',''))
if runxfail is None:
match_count = len(match_list)
solved = len(match_list)-len(unsolve_list)-len(exception_list)
msg = check_hint_msg.format(hint=our_hint, matched=match_count, solve=solved, unsolve=unsolve_list, exceptions=exception_list)
print(msg)
def test_SingleODESolver():
# Test that not implemented methods give NotImplementedError
# Subclasses should override these methods.
problem = SingleODEProblem(f(x).diff(x), f(x), x)
solver = SingleODESolver(problem)
raises(NotImplementedError, lambda: solver.matches())
raises(NotImplementedError, lambda: solver.get_general_solution())
raises(NotImplementedError, lambda: solver._matches())
raises(NotImplementedError, lambda: solver._get_general_solution())
# This ODE can not be solved by the FirstLinear solver. Here we test that
# it does not match and the asking for a general solution gives
# ODEMatchError
problem = SingleODEProblem(f(x).diff(x) + f(x)*f(x), f(x), x)
solver = FirstLinear(problem)
raises(ODEMatchError, lambda: solver.get_general_solution())
solver = FirstLinear(problem)
assert solver.matches() is False
#These are just test for order of ODE
problem = SingleODEProblem(f(x).diff(x) + f(x), f(x), x)
assert problem.order == 1
problem = SingleODEProblem(f(x).diff(x,4) + f(x).diff(x,2) - f(x).diff(x,3), f(x), x)
assert problem.order == 4
def test_lie_group():
_ode_solver_test(_get_examples_ode_sol_lie_group)
def test_separable_reduced():
df = f(x).diff(x)
eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
_ode_solver_test(_get_examples_ode_sol_separable_reduced)
@slow
def test_slow_examples_separable_reduced():
_ode_solver_test(_get_examples_ode_sol_separable_reduced, run_slow_test=True)
def test_2nd_2F1_hypergeometric():
_ode_solver_test(_get_examples_ode_sol_2nd_2F1_hypergeometric)
def test_2nd_2F1_hypergeometric_intrgral():
eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x)
sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 -
x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x -
1), x)/4)*hyper((S(1)/2, -1), (1,), x))
assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral')
assert checkodesol(eq, sol) == (True, 0)
def test_2nd_linear_bessel_equation():
_ode_solver_test(_get_examples_ode_sol_2nd_linear_bessel)
def test_nth_algebraic():
eqn = f(x) + f(x)*f(x).diff(x)
solns = [Eq(f(x), exp(x)),
Eq(f(x), C1*exp(C2*x))]
solns_final = _remove_redundant_solutions(eqn, solns, 2, x)
assert solns_final == [Eq(f(x), C1*exp(C2*x))]
_ode_solver_test(_get_examples_ode_sol_nth_algebraic)
@slow
def test_slow_examples_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters, run_slow_test=True)
def test_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters)
@slow
def test_nth_linear_constant_coeff_variation_of_parameters__integral():
# solve_variation_of_parameters shouldn't attempt to simplify the
# Wronskian if simplify=False. If wronskian() ever gets good enough
# to simplify the result itself, this test might fail.
our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral'
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True)
sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False)
assert sol_simp != sol_nsimp
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
@slow
def test_slow_examples_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact, run_slow_test=True)
def test_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact)
def test_1st_exact_integral():
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral')
assert checkodesol(eq, sol_1, order=1, solve_for_func=False)
@slow
def test_slow_examples_nth_order_reducible():
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible, run_slow_test=True)
@slow
def test_slow_examples_nth_linear_constant_coeff_undetermined_coefficients():
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients, run_slow_test=True)
@slow
def test_slow_examples_separable():
_ode_solver_test(_get_examples_ode_sol_separable, run_slow_test=True)
def test_nth_linear_constant_coeff_undetermined_coefficients():
#issue-https://github.com/sympy/sympy/issues/5787
# This test case is to show the classification of imaginary constants under
# nth_linear_constant_coeff_undetermined_coefficients
eq = Eq(diff(f(x), x), I*f(x) + S.Half - I)
our_hint = 'nth_linear_constant_coeff_undetermined_coefficients'
assert our_hint in classify_ode(eq)
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients)
def test_nth_order_reducible():
from sympy.solvers.ode.ode import _nth_order_reducible_match
F = lambda eq: _nth_order_reducible_match(eq, f(x))
D = Derivative
assert F(D(y*f(x), x, y) + D(f(x), x)) is None
assert F(D(y*f(y), y, y) + D(f(y), y)) is None
assert F(f(x)*D(f(x), x) + D(f(x), x, 2)) is None
assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) is None # no simplification by design
assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) is None
assert F(D(f(x), x, 2) + D(f(x), x, 3)) == dict(n=2)
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible)
def test_separable():
_ode_solver_test(_get_examples_ode_sol_separable)
def test_factorable():
assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x)
_ode_solver_test(_get_examples_ode_sol_factorable)
def test_Riccati_special_minus2():
_ode_solver_test(_get_examples_ode_sol_riccati)
def test_Bernoulli():
_ode_solver_test(_get_examples_ode_sol_bernoulli)
def test_1st_linear():
_ode_solver_test(_get_examples_ode_sol_1st_linear)
def test_almost_linear():
_ode_solver_test(_get_examples_ode_sol_almost_linear)
def test_Liouville_ODE():
hint = 'Liouville'
not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 -
diff(f(x), x)**2/2, f(x))
not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 -
x*diff(f(x), x)**2/2, f(x))
assert hint not in not_Liouville1
assert hint not in not_Liouville2
assert hint + '_Integral' not in not_Liouville1
assert hint + '_Integral' not in not_Liouville2
_ode_solver_test(_get_examples_ode_sol_liouville)
def test_nth_order_linear_euler_eq_homogeneous():
x, t, a, b, c = symbols('x t a b c')
y = Function('y')
our_hint = "nth_linear_euler_eq_homogeneous"
eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t)
assert our_hint in classify_ode(eq)
eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2)
assert our_hint in classify_ode(eq)
_ode_solver_test(_get_examples_ode_sol_euler_homogeneous)
def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients():
x, t = symbols('x t')
a, b, c, d = symbols('a b c d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"
eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x
assert our_hint in classify_ode(eq, f(x))
eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x)
assert our_hint in classify_ode(eq, f(x))
_ode_solver_test(_get_examples_ode_sol_euler_undetermined_coeff)
def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters():
x, t = symbols('x, t')
a, b, c, d = symbols('a, b, c, d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"
eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2)
assert our_hint in classify_ode(eq, f(x))
eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x))
assert our_hint in classify_ode(eq, f(x))
_ode_solver_test(_get_examples_ode_sol_euler_var_para)
@_add_example_keys
def _get_examples_ode_sol_euler_homogeneous():
return {
'hint': "nth_linear_euler_eq_homogeneous",
'func': f(x),
'examples':{
'euler_hom_01': {
'eq': Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1 + C2*x**Rational(5, 2))],
},
'euler_hom_02': {
'eq': Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1*sqrt(x) + C2*x**3)]
},
'euler_hom_03': {
'eq': Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), (C1 + C2*log(x))/x**2)]
},
'euler_hom_04': {
'eq': Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),
'sol': [Eq(f(x), C1/x**2 + C2*x + C3*x**3)]
},
'euler_hom_05': {
'eq': Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),
'sol': [Eq(f(x), x**5*(C1 + C2*log(x) + C3*log(x)**2))]
},
'euler_hom_06': {
'eq': x**2*diff(f(x), x, 2) + x*diff(f(x), x) - 9*f(x),
'sol': [Eq(f(x), C1*x**-3 + C2*x**3)]
},
'euler_hom_07': {
'eq': sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x),
'sol': [Eq(f(x), C1*sin(log(x)) + C2*cos(log(x)))],
'XFAIL': ['2nd_power_series_regular','nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients']
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_undetermined_coeff():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
'func': f(x),
'examples':{
'euler_undet_01': {
'eq': Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1),
'sol': [Eq(f(x), C1 + C2*log(x) + log(x)**2/2)]
},
'euler_undet_02': {
'eq': Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3),
'sol': [Eq(f(x), x*(C1 + C2*x + Rational(1, 2)*x**2))]
},
'euler_undet_03': {
'eq': Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x),
'sol': [Eq(f(x), (C1 + C2*x**4 - log(x)**2/8 - log(x)/16)/x)]
},
'euler_undet_04': {
'eq': Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)),
'sol': [Eq(f(x), C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256))]
},
'euler_undet_05': {
'eq': Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)),
'sol': [Eq(f(x), C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36))]
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/5096
'euler_undet_06': {
'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2),
'sol': [Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2))]
},
'euler_undet_07': {
'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2),
'sol': [Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5)]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_var_para():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
'func': f(x),
'examples':{
'euler_var_01': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4),
'sol': [Eq(f(x), x*(C1 + C2*x + x**3/6))]
},
'euler_var_02': {
'eq': Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)),
'sol': [Eq(f(x), C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2))]
},
'euler_var_03': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)),
'sol': [Eq(f(x), x*(C1 + C2*x + x*exp(x) - 2*exp(x)))]
},
'euler_var_04': {
'eq': x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x),
'sol': [Eq(f(x), C1*x + C2*x**2 + log(x)/2 + Rational(3, 4))]
},
'euler_var_05': {
'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_bernoulli():
# Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n
return {
'hint': "Bernoulli",
'func': f(x),
'examples':{
'bernoulli_01': {
'eq': Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0),
'sol': [Eq(f(x), 1/(C1*x + 1))],
'XFAIL': ['separable_reduced']
},
'bernoulli_02': {
'eq': f(x).diff(x) - y*f(x),
'sol': [Eq(f(x), C1*exp(x*y))]
},
'bernoulli_03': {
'eq': f(x)*f(x).diff(x) - 1,
'sol': [Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_riccati():
# Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2
return {
'hint': "Riccati_special_minus2",
'func': f(x),
'examples':{
'riccati_01': {
'eq': 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2),
'sol': [Eq(f(x), (-sqrt(3)*tan(C1 + sqrt(3)*log(x)/4) + 3)/(2*x))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_1st_linear():
# Type: first order linear form f'(x)+p(x)f(x)=q(x)
return {
'hint': "1st_linear",
'func': f(x),
'examples':{
'linear_01': {
'eq': Eq(f(x).diff(x) + x*f(x), x**2),
'sol': [Eq(f(x), (C1 + x*exp(x**2/2)- sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_factorable():
""" some hints are marked as xfail for examples because they missed additional algebraic solution
which could be found by Factorable hint. Fact_01 raise exception for
nth_linear_constant_coeff_undetermined_coefficients"""
y = Dummy('y')
a0,a1,a2,a3,a4 = symbols('a0, a1, a2, a3, a4')
return {
'hint': "factorable",
'func': f(x),
'examples':{
'fact_01': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'lie_group', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_linear_constant_coeff_undetermined_coefficients']
},
'fact_02': {
'eq': f(x)*(f(x).diff(x)+f(x)*x+2),
'sol': [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))*exp(-x**2/2)), Eq(f(x), 0)],
'XFAIL': ['Bernoulli', '1st_linear', 'lie_group']
},
'fact_03': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)),
'sol': [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),Eq(f(x), C1*exp(-x**3/3))]
},
'fact_04': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)),
'sol': [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))]
},
'fact_05': {
'eq': (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4),
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)]
},
'fact_06': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x),
'sol': [Eq(f(x), C1)]
},
'fact_07': {
'eq': (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1),
'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]
},
'fact_08': {
'eq': Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x)]
},
'fact_09': {
'eq': f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x),
x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x),
x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x),
x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,
'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),
Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]
},
'fact_10': {
'eq': x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x),
(x, 2))**2 + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x),
x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x),
(x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2,
'sol': [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)), Eq(f(x), C1*besselj(sqrt(3),
x) + C2*bessely(sqrt(3), x))]
},
'fact_11': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))),
'sol': [], #currently dsolve doesn't return any solution for this example
'XFAIL': ['factorable']
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/15889
'fact_12': {
'eq': exp(f(x).diff(x))-f(x)**2,
'sol': [Eq(NonElementaryIntegral(1/log(y**2), (y, f(x))), C1 + x)],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_13': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_14': {
'eq': f(x).diff(x)**2 - f(x),
'sol': [Eq(f(x), C1**2/4 - C1*x/2 + x**2/4)]
},
'fact_15': {
'eq': f(x).diff(x)**2 - f(x)**2,
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]
},
'fact_16': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))]
},
# kamke ode 1.1
'fact_17': {
'eq': f(x).diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2),
'sol': [Eq(f(x), C1 + Integral(1/sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4), x))]
},
# This is from issue: https://github.com/sympy/sympy/issues/9446
'fact_18':{
'eq': Eq(f(2 * x), sin(Derivative(f(x)))),
'sol': [Eq(f(x), C1 + pi*x - Integral(asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))],
'checkodesol_XFAIL':True
},
}
}
@_add_example_keys
def _get_examples_ode_sol_almost_linear():
from sympy import Ei
A = Symbol('A', positive=True)
f = Function('f')
d = f(x).diff(x)
return {
'hint': "almost_linear",
'func': f(x),
'examples':{
'almost_lin_01': {
'eq': x**2*f(x)**2*d + f(x)**3 + 1,
'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)),
Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2),
Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)],
},
'almost_lin_02': {
'eq': x*f(x)*d + 2*x*f(x)**2 + 1,
'sol': [Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))]
},
'almost_lin_03': {
'eq': x*d + x*f(x) + 1,
'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))]
},
'almost_lin_04': {
'eq': x*exp(f(x))*d + exp(f(x)) + 3*x,
'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))],
},
'almost_lin_05': {
'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2,
'sol': [Eq(f(x), (C1 + Piecewise(
(x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_liouville():
return {
'hint': "Liouville",
'func': f(x),
'examples':{
'liouville_01': {
'eq': diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2,
'sol': [Eq(f(x), log(x/(C1 + C2*x)))],
},
'liouville_02': {
'eq': diff(x*exp(-f(x)), x, x),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_03': {
'eq': ((diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x))).expand(),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_04': {
'eq': diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))],
},
'liouville_05': {
'eq': x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*exp(-x))), Eq(f(x), sqrt(C1 + C2*exp(-x)))],
},
'liouville_06': {
'eq': Eq((x*exp(f(x))).diff(x, x), 0),
'sol': [Eq(f(x), log(C1 + C2/x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_algebraic():
M, m, r, t = symbols('M m r t')
phi = Function('phi')
# This one needs a substitution f' = g.
# 'algeb_12': {
# 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
# 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
# },
return {
'hint': "nth_algebraic",
'func': f(x),
'examples':{
'algeb_01': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x),
'sol': [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)]
},
'algeb_02': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_03': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_04': {
'eq': Eq(-M * phi(t).diff(t),
Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)),
'sol': [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))],
'func': phi(t)
},
'algeb_05': {
'eq': (1 - sin(f(x))) * f(x).diff(x),
'sol': [Eq(f(x), C1)],
'XFAIL': ['separable'] #It raised exception.
},
'algeb_06': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]
},
'algeb_07': {
'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)),
'sol': [Eq(f(x), C1 + g(x))],
},
'algeb_08': {
'eq': f(x).diff(x) - C1, #this example is from issue 15999
'sol': [Eq(f(x), C1*x + C2)],
},
'algeb_09': {
'eq': f(x)*f(x).diff(x),
'sol': [Eq(f(x), C1)],
},
'algeb_10': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)],
},
'algeb_11': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters']
#nth_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution.
},
'algeb_12': {
'eq': Derivative(x*f(x), x, x, x),
'sol': [Eq(f(x), (C1 + C2*x + C3*x**2) / x)],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
'algeb_13': {
'eq': Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)),
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_order_reducible():
return {
'hint': "nth_order_reducible",
'func': f(x),
'examples':{
'reducible_01': {
'eq': Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0),
'sol': [Eq(f(x),C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) +
sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))],
'slow': True,
},
'reducible_02': {
'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
'slow': True,
},
'reducible_03': {
'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))],
'slow': True,
},
'reducible_04': {
'eq': f(x).diff(x, 2) + 2*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x))],
},
'reducible_05': {
'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))],
'slow': True,
},
'reducible_06': {
'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))],
'slow': True,
},
'reducible_07': {
'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3),
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))],
'slow': True,
},
'reducible_08': {
'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],
'slow': True,
},
'reducible_09': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],
'slow': True,
},
'reducible_10': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*(x*sin(x) + cos(x)) + C3*(-x*cos(x) + sin(x)) + C4*sin(x) + C5*cos(x))],
'slow': True,
},
'reducible_11': {
'eq': f(x).diff(x, 2) - f(x).diff(x)**3,
'sol': [Eq(f(x), C1 - sqrt(2)*(I*C2 + I*x)*sqrt(1/(C2 + x))),
Eq(f(x), C1 + sqrt(2)*(I*C2 + I*x)*sqrt(1/(C2 + x)))],
'slow': True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_undetermined_coefficients():
# examples 3-27 below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
return {
'hint': "nth_linear_constant_coeff_undetermined_coefficients",
'func': f(x),
'examples':{
'undet_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'undet_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'undet_03': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'undet_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'undet_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x),
'sol': [Eq(f(x), (S(3)/10 + I/10)*(C1*exp(-2*x) + C2*exp(-x) - I*exp(I*x)))],
'slow': True,
},
'undet_06': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - sin(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + sin(x)/10 - 3*cos(x)/10)],
'slow': True,
},
'undet_07': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - cos(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 3*sin(x)/10 + cos(x)/10)],
'slow': True,
},
'undet_08': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(x) + sin(x)/5 - 3*cos(x)/5 + 4)],
'slow': True,
},
'undet_09': {
'eq': f2 + f(x).diff(x) + f(x) - x**2,
'sol': [Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))],
'slow': True,
},
'undet_10': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'undet_11': {
'eq': f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x),
'sol': [Eq(f(x), C1 + C2*exp(3*x) - 3*exp(2*x)*sin(x)/5 - exp(2*x)*cos(x)/5)],
'slow': True,
},
'undet_12': {
'eq': f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x),
'sol': [Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))],
'slow': True,
},
'undet_13': {
'eq': f2 + f(x).diff(x) - x**2 - 2*x,
'sol': [Eq(f(x), C1 + x**3/3 + C2*exp(-x))],
'slow': True,
},
'undet_14': {
'eq': f2 + f(x).diff(x) - x - sin(2*x),
'sol': [Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))],
'slow': True,
},
'undet_15': {
'eq': f2 + f(x) - 4*x*sin(x),
'sol': [Eq(f(x), (C1 - x**2)*cos(x) + (C2 + x)*sin(x))],
'slow': True,
},
'undet_16': {
'eq': f2 + 4*f(x) - x*sin(2*x),
'sol': [Eq(f(x), (C1 - x**2/8)*cos(2*x) + (C2 + x/16)*sin(2*x))],
'slow': True,
},
'undet_17': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'undet_18': {
'eq': f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \
x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 - x**3/60 + x/3)))*exp(-x))],
'slow': True,
},
'undet_19': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2,
'sol': [Eq(f(x), C2*exp(-x) + x**2/2 - x*Rational(3,2) + (C1 - x)*exp(-2*x) + Rational(7,4))],
'slow': True,
},
'undet_20': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'undet_21': {
'eq': f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x),
'sol': [Eq(f(x), Rational(-1, 36) - x/6 + C2*exp(-3*x) + (C1 + x/5)*exp(2*x))],
'slow': True,
},
'undet_22': {
'eq': f2 + f(x) - sin(x) - exp(-x),
'sol': [Eq(f(x), C2*sin(x) + (C1 - x/2)*cos(x) + exp(-x)/2)],
'slow': True,
},
'undet_23': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'undet_24': {
'eq': f2 + f(x) - S.Half - cos(2*x)/2,
'sol': [Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))],
'slow': True,
},
'undet_25': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2),
'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)],
'slow': True,
},
#Note: 'undet_26' is referred in 'undet_37'
'undet_26': {
'eq': (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x -
sin(x) - cos(x)),
'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8))*sin(x) + (C4 + x*(C5 + x/8))*cos(x))],
'slow': True,
},
'undet_27': {
'eq': f2 + f(x) - cos(x)/2 + cos(3*x)/2,
'sol': [Eq(f(x), cos(3*x)/16 + C2*cos(x) + (C1 + x/4)*sin(x))],
'slow': True,
},
'undet_28': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/19358
'undet_29': {
'eq': f2 + f(x).diff(x) + exp(x-C1),
'sol': [Eq(f(x), C2 + C3*exp(-x) - exp(-C1 + x)/2)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/18408
'undet_30': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x),
'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2)],
},
'undet_31': {
'eq': f(x).diff(x, 2) - 49*f(x) - sinh(3*x),
'sol': [Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40)],
},
'undet_32': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x),
'sol': [Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x))],
},
# https://github.com/sympy/sympy/issues/5096
'undet_33': {
'eq': f(x).diff(x, x) + f(x) - x*sin(x - 2),
'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4)],
},
'undet_34': {
'eq': f(x).diff(x, 2) + f(x) - x**4*sin(x-1),
'sol': [ Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4)],
},
'undet_35': {
'eq': f(x).diff(x, 2) - f(x) - exp(x - 1),
'sol': [Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x))],
},
'undet_36': {
'eq': f(x).diff(x, 2)+f(x)-(sin(x-2)+1),
'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1)],
},
# Equivalent to example_name 'undet_26'.
# This previously failed because the algorithm for undetermined coefficients
# didn't know to multiply exp(I*x) by sufficient x because it is linearly
# dependent on sin(x) and cos(x).
'undet_37': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x),
'sol': [Eq(f(x), C1 + x**2*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_separable():
# test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and
# Pollard, pg. 55
a = Symbol('a')
return {
'hint': "separable",
'func': f(x),
'examples':{
'separable_01': {
'eq': f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*exp(x))],
},
'separable_02': {
'eq': x*f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*x)],
},
'separable_03': {
'eq': f(x).diff(x) + sin(x),
'sol': [Eq(f(x), C1 + cos(x))],
},
'separable_04': {
'eq': f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x),
'sol': [Eq(f(x), tan(C1 + atan(x)))],
},
'separable_05': {
'eq': f(x).diff(x)/tan(x) - f(x) - 2,
'sol': [Eq(f(x), C1/cos(x) - 2)],
},
'separable_06': {
'eq': f(x).diff(x) * (1 - sin(f(x))) - 1,
'sol': [Eq(-x + f(x) + cos(f(x)), C1)],
},
'separable_07': {
'eq': f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x),
'sol': [Eq(f(x), (-x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2),
Eq(f(x), -((x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1))/2)],
'slow': True,
},
'separable_08': {
'eq': f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1)),
Eq(f(x), sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1))],
'slow': True,
},
'separable_09': {
'eq': x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2),
'sol': [Eq(f(x), sinh(C1 - log(log(x))))], #One more solution is f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_10': {
'eq': exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x),
'sol': [Eq(E*exp(x) + log(cos(f(x)) - 1)/2 - log(cos(f(x)) + 1)/2 + cos(f(x)), C1)],
'slow': True,
},
'separable_11': {
'eq': (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)),
'sol': [Eq(f(x), -acos(C1*sqrt(-a**2 + x**2)) + 2*pi),
Eq(f(x), acos(C1*sqrt(-a**2 + x**2)))],
'slow': True,
},
'separable_12': {
'eq': f(x).diff(x) - f(x)*tan(x),
'sol': [Eq(f(x), C1/cos(x))],
},
'separable_13': {
'eq': (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)),
'sol': [Eq(f(x), pi - asin(C1*(x**2 - 2*x + 1)*exp(2*x))),
Eq(f(x), asin(C1*(x**2 - 2*x + 1)*exp(2*x)))],
},
'separable_14': {
'eq': f(x).diff(x) - f(x)*log(f(x))/tan(x),
'sol': [Eq(f(x), exp(C1*sin(x)))],
},
'separable_15': {
'eq': x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)),
'sol': [Eq(f(x), tan(C1/x))], #Two more solutions are f(x)=0 and f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_16': {
'eq': f(x).diff(x) + x*(f(x) + 1),
'sol': [Eq(f(x), -1 + C1*exp(-x**2/2))],
},
'separable_17': {
'eq': exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(log(1/(C1 + x**2 + 2*x)))),
Eq(f(x), sqrt(log(1/(C1 + x**2 + 2*x))))],
},
'separable_18': {
'eq': f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*exp(-x))],
},
'separable_19': {
'eq': sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x),
'sol': [Eq(f(x), pi - acos(C1/cos(x)**2)/2), Eq(f(x), acos(C1/cos(x)**2)/2)],
},
'separable_20': {
'eq': (1 - x)*f(x).diff(x) - x*(f(x) + 1),
'sol': [Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))],
},
'separable_21': {
'eq': f(x)*diff(f(x), x) + x - 3*x*f(x)**2,
'sol': [Eq(f(x), -sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3),
Eq(f(x), sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3)],
},
'separable_22': {
'eq': f(x).diff(x) - exp(x + f(x)),
'sol': [Eq(f(x), log(-1/(C1 + exp(x))))],
'XFAIL': ['lie_group'] #It shows 'NoneType' object is not subscriptable for lie_group.
},
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_exact():
# Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0,
# where dp/df == dq/dx
'''
Example 7 is an exact equation that fails under the exact engine. It is caught
by first order homogeneous albeit with a much contorted solution. The
exact engine fails because of a poorly simplified integral of q(0,y)dy,
where q is the function multiplying f'. The solutions should be
Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is
equivalent, but it is so complex that checkodesol fails, and takes a long
time to do so.
'''
return {
'hint': "1st_exact",
'func': f(x),
'examples':{
'1st_exact_01': {
'eq': sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x),
'sol': [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))],
'slow': True,
},
'1st_exact_02': {
'eq': (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x),
'sol': [Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))],
'XFAIL': ['lie_group'], #It shows dsolve raises an exception: List index out of range for lie_group
'slow': True,
'checkodesol_XFAIL':True
},
'1st_exact_03': {
'eq': 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x),
'sol': [Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)],
'XFAIL': ['lie_group'], #It goes into infinite loop for lie_group.
'slow': True,
},
'1st_exact_04': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'slow': True,
},
'1st_exact_05': {
'eq': 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x),
'sol': [Eq(x**2*f(x) + f(x)**3/3, C1)],
'slow': True,
'simplify_flag':False
},
# This was from issue: https://github.com/sympy/sympy/issues/11290
'1st_exact_06': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'simplify_flag':False
},
'1st_exact_07': {
'eq': x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x),
'sol': [Eq(log(x),
C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x +
27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)*
log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) +
9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) +
9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))],
'slow': True,
'dsolve_too_slow':True
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_var_of_parameters():
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
return {
'hint': "nth_linear_constant_coeff_variation_of_parameters",
'func': f(x),
'examples':{
'var_of_parameters_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_03': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
'var_of_parameters_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'var_of_parameters_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'var_of_parameters_06': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'var_of_parameters_07': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'var_of_parameters_08': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'var_of_parameters_09': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'var_of_parameters_10': {
'eq': f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x,
'sol': [Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))],
'slow': True,
},
'var_of_parameters_11': {
'eq': f2 + f(x) - 1/sin(x)*1/cos(x),
'sol': [Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2
)*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x))],
'slow': True,
},
'var_of_parameters_12': {
'eq': f(x).diff(x, 4) - 1/x,
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + x**3*(C4 + log(x)/6))],
'slow': True,
},
# These were from issue: https://github.com/sympy/sympy/issues/15996
'var_of_parameters_13': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x),
'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + x*(C5 + I*x/8 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2)
+ 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x))],
},
'var_of_parameters_14': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x),
'sol': [Eq(f(x), C1 + (C2 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_linear_bessel():
return {
'hint': "2nd_linear_bessel",
'func': f(x),
'examples':{
'2nd_lin_bessel_01': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x),
'sol': [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x))],
},
'2nd_lin_bessel_02': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x),
'sol': [Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x))],
},
'2nd_lin_bessel_03': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x),
'sol': [Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x))],
},
'2nd_lin_bessel_04': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x),
'sol': [Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x))],
},
'2nd_lin_bessel_05': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x),
'sol': [Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2))],
},
'2nd_lin_bessel_06': {
'eq': x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x),
'sol': [Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x))],
},
'2nd_lin_bessel_07': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x),
'sol': [Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))],
},
'2nd_lin_bessel_08': {
'eq': x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x),
'sol': [Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x))))],
},
'2nd_lin_bessel_09': {
'eq': x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x),
'sol': [Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2)))],
},
'2nd_lin_bessel_10': {
'eq': (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x),
'sol': [Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4)))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_2F1_hypergeometric():
return {
'hint': "2nd_hypergeometric",
'func': f(x),
'examples':{
'2nd_2F1_hyper_01': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x),
'sol': [Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x))],
},
'2nd_2F1_hyper_02': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) +
C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2))],
},
'2nd_2F1_hyper_03': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) +
C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2))],
},
'2nd_2F1_hyper_04': {
'eq': -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) +
x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2)),
'sol': [Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) +
C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84))],
'checkodesol_XFAIL':True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_separable_reduced():
df = f(x).diff(x)
return {
'hint': "separable_reduced",
'func': f(x),
'examples':{
'separable_reduced_01': {
'eq': x* df + f(x)* (1 / (x**2*f(x) - 1)),
'sol': [Eq(log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
#Note: 'separable_reduced_02' is referred in 'separable_reduced_11'
'separable_reduced_02': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(log(x**3*f(x))/4 + log(x**3*f(x) - Rational(4,3))/12, C1 + log(x))],
'simplify_flag': False,
'checkodesol_XFAIL':True, #It hangs for this.
},
'separable_reduced_03': {
'eq': x*df + f(x)*(x**2*f(x)),
'sol': [Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_04': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0),
'sol': [Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_05': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0),
'sol': [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))],
},
'separable_reduced_06': {
'eq': Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0),
'sol': [Eq(f(x), C1 + 1/(2*x**2))],
},
'separable_reduced_07': {
'eq': Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0),
'sol': [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2)],
},
'separable_reduced_08': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0),
'sol': [Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
'separable_reduced_09': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0),
'sol': [Eq(f(x), 3/(C1*x**3 - 1))],
},
'separable_reduced_10': {
'eq': Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0),
'sol': [Eq(- log(x) - log(f(x) + 1) + log(f(x)) + 1/f(x), C1)],
'XFAIL': ['lie_group'],#No algorithms are implemented to solve equation -C1 + x*(_y + 1)*exp(-1/_y)/_y
},
# Equivalent to example_name 'separable_reduced_02'. Only difference is testing with simplify=True
'separable_reduced_11': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1)
+ x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1))
- exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3))],
'checkodesol_XFAIL':True, #It hangs for this.
'slow': True,
},
#These were from issue: https://github.com/sympy/sympy/issues/6247
'separable_reduced_12': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2*C1/(C1*x**2 - 1))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_lie_group():
a, b, c = symbols("a b c")
return {
'hint': "lie_group",
'func': f(x),
'examples':{
#Example 1-4 were from issue: https://github.com/sympy/sympy/issues/17322
'lie_group_01': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
'checkodesol_too_slow': True,
},
'lie_group_02': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_03': {
'eq': Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0),
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_04': {
'eq': f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x),
'sol': [],
'XFAIL': ['lie_group'],
},
'lie_group_05': {
'eq': f(x).diff(x)**2,
'sol': [Eq(f(x), C1)],
},
'lie_group_06': {
'eq': Eq(f(x).diff(x), x**2*f(x)),
'sol': [Eq(f(x), C1*exp(x**3)**Rational(1, 3))],
},
'lie_group_07': {
'eq': f(x).diff(x) + a*f(x) - c*exp(b*x),
'sol': [Eq(f(x), Piecewise(((-C1*(a + b) + c*exp(x*(a + b)))*exp(-a*x)/(a + b),\
Ne(a, -b)), ((-C1 + c*x)*exp(-a*x), True)))],
},
'lie_group_08': {
'eq': f(x).diff(x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), (C1 + x**2/2)*exp(-x**2))],
},
'lie_group_09': {
'eq': (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)),
'sol': [Eq(f(x), log(C1/(2*x + 1) + 2))],
},
'lie_group_10': {
'eq': x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)),
'sol': [Eq(f(x), -((C1 + exp(x))*exp(-1/x)))],
},
'lie_group_11': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2/(C1 + x**2))],
},
'lie_group_12': {
'eq': diff(f(x),x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), exp(-x**2)*(C1 + x**2/2))],
},
'lie_group_13': {
'eq': diff(f(x),x) + f(x)*cos(x) - exp(2*x),
'sol': [Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x)))],
},
'lie_group_14': {
'eq': diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2,
'sol': [Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)],
},
'lie_group_15': {
'eq': x*diff(f(x),x) + f(x) - x*sin(x),
'sol': [Eq(f(x), (C1 - x*cos(x) + sin(x))/x)],
},
'lie_group_16': {
'eq': x*diff(f(x),x) - f(x) - x/log(x),
'sol': [Eq(f(x), x*(C1 + log(log(x))))],
},
'lie_group_17': {
'eq': (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)),
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))],
},
'lie_group_18': {
'eq': f(x).diff(x) * (f(x).diff(x) - f(x)),
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1)],
},
}
}
def _get_all_examples():
all_examples = _get_examples_ode_sol_euler_homogeneous + \
_get_examples_ode_sol_euler_undetermined_coeff + \
_get_examples_ode_sol_euler_var_para + \
_get_examples_ode_sol_factorable + \
_get_examples_ode_sol_bernoulli + \
_get_examples_ode_sol_nth_algebraic + \
_get_examples_ode_sol_riccati + \
_get_examples_ode_sol_1st_linear + \
_get_examples_ode_sol_1st_exact + \
_get_examples_ode_sol_almost_linear + \
_get_examples_ode_sol_nth_order_reducible + \
_get_examples_ode_sol_nth_linear_undetermined_coefficients + \
_get_examples_ode_sol_liouville + \
_get_examples_ode_sol_separable + \
_get_examples_ode_sol_nth_linear_var_of_parameters + \
_get_examples_ode_sol_2nd_linear_bessel + \
_get_examples_ode_sol_2nd_2F1_hypergeometric + \
_get_examples_ode_sol_separable_reduced
return all_examples
|
c540e0a5480036bb51503514983f78a1439cfd8269a443094a080e083e9ed56d | """ Generic SymPy-Independent Strategies """
def identity(x):
yield x
def exhaust(brule):
""" Apply a branching rule repeatedly until it has no effect """
def exhaust_brl(expr):
seen = {expr}
for nexpr in brule(expr):
if nexpr not in seen:
seen.add(nexpr)
yield from exhaust_brl(nexpr)
if seen == {expr}:
yield expr
return exhaust_brl
def onaction(brule, fn):
def onaction_brl(expr):
for result in brule(expr):
if result != expr:
fn(brule, expr, result)
yield result
return onaction_brl
def debug(brule, file=None):
""" Print the input and output expressions at each rule application """
if not file:
from sys import stdout
file = stdout
def write(brl, expr, result):
file.write("Rule: %s\n" % brl.__name__)
file.write("In: %s\nOut: %s\n\n" % (expr, result))
return onaction(brule, write)
def multiplex(*brules):
""" Multiplex many branching rules into one """
def multiplex_brl(expr):
seen = set()
for brl in brules:
for nexpr in brl(expr):
if nexpr not in seen:
seen.add(nexpr)
yield nexpr
return multiplex_brl
def condition(cond, brule):
""" Only apply branching rule if condition is true """
def conditioned_brl(expr):
if cond(expr):
yield from brule(expr)
else:
pass
return conditioned_brl
def sfilter(pred, brule):
""" Yield only those results which satisfy the predicate """
def filtered_brl(expr):
yield from filter(pred, brule(expr))
return filtered_brl
def notempty(brule):
def notempty_brl(expr):
yielded = False
for nexpr in brule(expr):
yielded = True
yield nexpr
if not yielded:
yield expr
return notempty_brl
def do_one(*brules):
""" Execute one of the branching rules """
def do_one_brl(expr):
yielded = False
for brl in brules:
for nexpr in brl(expr):
yielded = True
yield nexpr
if yielded:
return
return do_one_brl
def chain(*brules):
"""
Compose a sequence of brules so that they apply to the expr sequentially
"""
def chain_brl(expr):
if not brules:
yield expr
return
head, tail = brules[0], brules[1:]
for nexpr in head(expr):
yield from chain(*tail)(nexpr)
return chain_brl
def yieldify(rl):
""" Turn a rule into a branching rule """
def brl(expr):
yield rl(expr)
return brl
|
3e7d5cbd621fd1ffe9c93dccbe809f67292a122388af443be62a889a02a2fb8d | from sympy.strategies.tree import treeapply, greedy, allresults, brute
from functools import partial, reduce
def test_treeapply():
tree = ([3, 3], [4, 1], 2)
assert treeapply(tree, {list: min, tuple: max}) == 3
add = lambda *args: sum(args)
mul = lambda *args: reduce(lambda a, b: a*b, args, 1)
assert treeapply(tree, {list: add, tuple: mul}) == 60
def test_treeapply_leaf():
assert treeapply(3, {}, leaf=lambda x: x**2) == 9
tree = ([3, 3], [4, 1], 2)
treep1 = ([4, 4], [5, 2], 3)
assert treeapply(tree, {list: min, tuple: max}, leaf=lambda x: x+1) == \
treeapply(treep1, {list: min, tuple: max})
def test_treeapply_strategies():
from sympy.strategies import chain, minimize
join = {list: chain, tuple: minimize}
inc = lambda x: x + 1
dec = lambda x: x - 1
double = lambda x: 2*x
assert treeapply(inc, join) == inc
assert treeapply((inc, dec), join)(5) == minimize(inc, dec)(5)
assert treeapply([inc, dec], join)(5) == chain(inc, dec)(5)
tree = (inc, [dec, double]) # either inc or dec-then-double
assert treeapply(tree, join)(5) == 6
assert treeapply(tree, join)(1) == 0
maximize = partial(minimize, objective=lambda x: -x)
join = {list: chain, tuple: maximize}
fn = treeapply(tree, join)
assert fn(4) == 6 # highest value comes from the dec then double
assert fn(1) == 2 # highest value comes from the inc
def test_greedy():
inc = lambda x: x + 1
dec = lambda x: x - 1
double = lambda x: 2*x
tree = [inc, (dec, double)] # either inc or dec-then-double
fn = greedy(tree, objective=lambda x: -x)
assert fn(4) == 6 # highest value comes from the dec then double
assert fn(1) == 2 # highest value comes from the inc
tree = [inc, dec, [inc, dec, [(inc, inc), (dec, dec)]]]
lowest = greedy(tree)
assert lowest(10) == 8
highest = greedy(tree, objective=lambda x: -x)
assert highest(10) == 12
def test_allresults():
inc = lambda x: x+1
dec = lambda x: x-1
double = lambda x: x*2
# square = lambda x: x**2
assert set(allresults(inc)(3)) == {inc(3)}
assert set(allresults([inc, dec])(3)) == {2, 4}
assert set(allresults((inc, dec))(3)) == {3}
assert set(allresults([inc, (dec, double)])(4)) == {5, 6}
def test_brute():
inc = lambda x: x+1
dec = lambda x: x-1
square = lambda x: x**2
tree = ([inc, dec], square)
fn = brute(tree, lambda x: -x)
assert fn(2) == (2 + 1)**2
assert fn(-2) == (-2 - 1)**2
assert brute(inc)(1) == 2
|
0e55aa5faecc13c9f7f2692567cb019bf8f36f368d0727b9ed99d49cfb919e5e | from sympy import S
from sympy.strategies.core import (null_safe, exhaust, memoize, condition,
chain, tryit, do_one, debug, switch, minimize)
def test_null_safe():
def rl(expr):
if expr == 1:
return 2
safe_rl = null_safe(rl)
assert rl(1) == safe_rl(1)
assert rl(3) == None
assert safe_rl(3) == 3
def posdec(x):
if x > 0:
return x-1
else:
return x
def test_exhaust():
sink = exhaust(posdec)
assert sink(5) == 0
assert sink(10) == 0
def test_memoize():
rl = memoize(posdec)
assert rl(5) == posdec(5)
assert rl(5) == posdec(5)
assert rl(-2) == posdec(-2)
def test_condition():
rl = condition(lambda x: x%2 == 0, posdec)
assert rl(5) == 5
assert rl(4) == 3
def test_chain():
rl = chain(posdec, posdec)
assert rl(5) == 3
assert rl(1) == 0
def test_tryit():
def rl(expr):
assert False
safe_rl = tryit(rl, AssertionError)
assert safe_rl(S(1)) == 1
def test_do_one():
rl = do_one(posdec, posdec)
assert rl(5) == 4
rl1 = lambda x: 2 if x == 1 else x
rl2 = lambda x: 3 if x == 2 else x
rule = do_one(rl1, rl2)
assert rule(1) == 2
assert rule(rule(1)) == 3
def test_debug():
from io import StringIO
file = StringIO()
rl = debug(posdec, file)
rl(5)
log = file.getvalue()
file.close()
assert posdec.__name__ in log
assert '5' in log
assert '4' in log
def test_switch():
inc = lambda x: x + 1
dec = lambda x: x - 1
key = lambda x: x % 3
rl = switch(key, {0: inc, 1: dec})
assert rl(3) == 4
assert rl(4) == 3
assert rl(5) == 5
def test_minimize():
inc = lambda x: x + 1
dec = lambda x: x - 1
rl = minimize(inc, dec)
assert rl(4) == 3
rl = minimize(inc, dec, objective=lambda x: -x)
assert rl(4) == 5
|
30e3f2604122fd48399827d138ee71c1f5a1476daad4a4a4c7a512eb9899cb46 | from sympy.strategies.branch.core import (exhaust, debug, multiplex,
condition, notempty, chain, onaction, sfilter, yieldify, do_one,
identity)
def posdec(x):
if x > 0:
yield x-1
else:
yield x
def branch5(x):
if 0 < x < 5:
yield x-1
elif 5 < x < 10:
yield x+1
elif x == 5:
yield x+1
yield x-1
else:
yield x
even = lambda x: x%2 == 0
def inc(x):
yield x + 1
def one_to_n(n):
yield from range(n)
def test_exhaust():
brl = exhaust(branch5)
assert set(brl(3)) == {0}
assert set(brl(7)) == {10}
assert set(brl(5)) == {0, 10}
def test_debug():
from io import StringIO
file = StringIO()
rl = debug(posdec, file)
list(rl(5))
log = file.getvalue()
file.close()
assert posdec.__name__ in log
assert '5' in log
assert '4' in log
def test_multiplex():
brl = multiplex(posdec, branch5)
assert set(brl(3)) == {2}
assert set(brl(7)) == {6, 8}
assert set(brl(5)) == {4, 6}
def test_condition():
brl = condition(even, branch5)
assert set(brl(4)) == set(branch5(4))
assert set(brl(5)) == set()
def test_sfilter():
brl = sfilter(even, one_to_n)
assert set(brl(10)) == {0, 2, 4, 6, 8}
def test_notempty():
def ident_if_even(x):
if even(x):
yield x
brl = notempty(ident_if_even)
assert set(brl(4)) == {4}
assert set(brl(5)) == {5}
def test_chain():
assert list(chain()(2)) == [2] # identity
assert list(chain(inc, inc)(2)) == [4]
assert list(chain(branch5, inc)(4)) == [4]
assert set(chain(branch5, inc)(5)) == {5, 7}
assert list(chain(inc, branch5)(5)) == [7]
def test_onaction():
L = []
def record(fn, input, output):
L.append((input, output))
list(onaction(inc, record)(2))
assert L == [(2, 3)]
list(onaction(identity, record)(2))
assert L == [(2, 3)]
def test_yieldify():
inc = lambda x: x + 1
yinc = yieldify(inc)
assert list(yinc(3)) == [4]
def test_do_one():
def bad(expr):
raise ValueError()
yield False
assert list(do_one(inc)(3)) == [4]
assert list(do_one(inc, bad)(3)) == [4]
assert list(do_one(inc, posdec)(3)) == [4]
|
d728982735ccf02e4d4695df201a91775c682d0da125016e655f081df2a2137c | # Tests that require installed backends go into
# sympy/test_external/test_autowrap
import os
import tempfile
import shutil
from io import StringIO
from sympy.core import symbols, Eq
from sympy.utilities.autowrap import (autowrap, binary_function,
CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper)
from sympy.utilities.codegen import (
CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine
)
from sympy.testing.pytest import raises
from sympy.testing.tmpfiles import TmpFileManager
def get_string(dump_fn, routines, prefix="file", **kwargs):
"""Wrapper for dump_fn. dump_fn writes its results to a stream object and
this wrapper returns the contents of that stream as a string. This
auxiliary function is used by many tests below.
The header and the empty lines are not generator to facilitate the
testing of the output.
"""
output = StringIO()
dump_fn(routines, output, prefix, **kwargs)
source = output.getvalue()
output.close()
return source
def test_cython_wrapper_scalar_function():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = CythonCodeWrapper(CCodeGen())
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" double test(double x, double y, double z)\n"
"\n"
"def test_c(double x, double y, double z):\n"
"\n"
" return test(x, y, z)")
assert source == expected
def test_cython_wrapper_outarg():
from sympy import Equality
x, y, z = symbols('x,y,z')
code_gen = CythonCodeWrapper(C99CodeGen())
routine = make_routine("test", Equality(z, x + y))
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" void test(double x, double y, double *z)\n"
"\n"
"def test_c(double x, double y):\n"
"\n"
" cdef double z = 0\n"
" test(x, y, &z)\n"
" return z")
assert source == expected
def test_cython_wrapper_inoutarg():
from sympy import Equality
x, y, z = symbols('x,y,z')
code_gen = CythonCodeWrapper(C99CodeGen())
routine = make_routine("test", Equality(z, x + y + z))
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" void test(double x, double y, double *z)\n"
"\n"
"def test_c(double x, double y, double z):\n"
"\n"
" test(x, y, &z)\n"
" return z")
assert source == expected
def test_cython_wrapper_compile_flags():
from sympy import Equality
x, y, z = symbols('x,y,z')
routine = make_routine("test", Equality(z, x + y))
code_gen = CythonCodeWrapper(CCodeGen())
expected = """\
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
cy_opts = {}
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=[],
library_dirs=[],
libraries=[],
extra_compile_args=['-std=c99'],
extra_link_args=[]
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
temp_dir = tempfile.mkdtemp()
TmpFileManager.tmp_folder(temp_dir)
setup_file_path = os.path.join(temp_dir, 'setup.py')
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
code_gen = CythonCodeWrapper(CCodeGen(),
include_dirs=['/usr/local/include', '/opt/booger/include'],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math'],
extra_link_args=['-lswamp', '-ltrident'],
cythonize_options={'compiler_directives': {'boundscheck': False}}
)
expected = """\
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
cy_opts = {'compiler_directives': {'boundscheck': False}}
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=['/usr/local/include', '/opt/booger/include'],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math', '-std=c99'],
extra_link_args=['-lswamp', '-ltrident']
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
expected = """\
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
cy_opts = {'compiler_directives': {'boundscheck': False}}
import numpy as np
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math', '-std=c99'],
extra_link_args=['-lswamp', '-ltrident']
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
code_gen._need_numpy = True
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
TmpFileManager.cleanup()
def test_cython_wrapper_unique_dummyvars():
from sympy import Dummy, Equality
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]]
expr = Equality(z, x + y)
routine = make_routine("test", expr)
code_gen = CythonCodeWrapper(CCodeGen())
source = get_string(code_gen.dump_pyx, [routine])
expected_template = (
"cdef extern from 'file.h':\n"
" void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n"
"\n"
"def test_c(double x_{x_id}, double y_{y_id}):\n"
"\n"
" cdef double z_{z_id} = 0\n"
" test(x_{x_id}, y_{y_id}, &z_{z_id})\n"
" return z_{z_id}")
expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id)
assert source == expected
def test_autowrap_dummy():
x, y, z = symbols('x y z')
# Uses DummyWrapper to test that codegen works as expected
f = autowrap(x + y, backend='dummy')
assert f() == str(x + y)
assert f.args == "x, y"
assert f.returns == "nameless"
f = autowrap(Eq(z, x + y), backend='dummy')
assert f() == str(x + y)
assert f.args == "x, y"
assert f.returns == "z"
f = autowrap(Eq(z, x + y + z), backend='dummy')
assert f() == str(x + y + z)
assert f.args == "x, y, z"
assert f.returns == "z"
def test_autowrap_args():
x, y, z = symbols('x y z')
raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y),
backend='dummy', args=[x]))
f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x])
assert f() == str(x + y)
assert f.args == "y, x"
assert f.returns == "z"
raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z),
backend='dummy', args=[x, y]))
f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z])
assert f() == str(x + y + z)
assert f.args == "y, x, z"
assert f.returns == "z"
f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z))
assert f() == str(x + y + z)
assert f.args == "y, x, z"
assert f.returns == "z"
def test_autowrap_store_files():
x, y = symbols('x y')
tmp = tempfile.mkdtemp()
TmpFileManager.tmp_folder(tmp)
f = autowrap(x + y, backend='dummy', tempdir=tmp)
assert f() == str(x + y)
assert os.access(tmp, os.F_OK)
TmpFileManager.cleanup()
def test_autowrap_store_files_issue_gh12939():
x, y = symbols('x y')
tmp = './tmp'
try:
f = autowrap(x + y, backend='dummy', tempdir=tmp)
assert f() == str(x + y)
assert os.access(tmp, os.F_OK)
finally:
shutil.rmtree(tmp)
def test_binary_function():
x, y = symbols('x y')
f = binary_function('f', x + y, backend='dummy')
assert f._imp_() == str(x + y)
def test_ufuncify_source():
x, y, z = symbols('x,y,z')
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
routine = make_routine("test", x + y + z)
source = get_string(code_wrapper.dump_c, [routine])
expected = """\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include "file.h"
static PyMethodDef wrapper_module_%(num)sMethods[] = {
{NULL, NULL, 0, NULL}
};
static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
{
npy_intp i;
npy_intp n = dimensions[0];
char *in0 = args[0];
char *in1 = args[1];
char *in2 = args[2];
char *out0 = args[3];
npy_intp in0_step = steps[0];
npy_intp in1_step = steps[1];
npy_intp in2_step = steps[2];
npy_intp out0_step = steps[3];
for (i = 0; i < n; i++) {
*((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2);
in0 += in0_step;
in1 += in1_step;
in2 += in2_step;
out0 += out0_step;
}
}
PyUFuncGenericFunction test_funcs[1] = {&test_ufunc};
static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
static void *test_data[1] = {NULL};
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"wrapper_module_%(num)s",
NULL,
-1,
wrapper_module_%(num)sMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "test", ufunc0);
Py_DECREF(ufunc0);
return m;
}
#else
PyMODINIT_FUNC initwrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "test", ufunc0);
Py_DECREF(ufunc0);
}
#endif""" % {'num': CodeWrapper._module_counter}
assert source == expected
def test_ufuncify_source_multioutput():
x, y, z = symbols('x,y,z')
var_symbols = (x, y, z)
expr = x + y**3 + 10*z**2
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))]
source = get_string(code_wrapper.dump_c, routines, funcname='multitest')
expected = """\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include "file.h"
static PyMethodDef wrapper_module_%(num)sMethods[] = {
{NULL, NULL, 0, NULL}
};
static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
{
npy_intp i;
npy_intp n = dimensions[0];
char *in0 = args[0];
char *in1 = args[1];
char *in2 = args[2];
char *out0 = args[3];
char *out1 = args[4];
char *out2 = args[5];
npy_intp in0_step = steps[0];
npy_intp in1_step = steps[1];
npy_intp in2_step = steps[2];
npy_intp out0_step = steps[3];
npy_intp out1_step = steps[4];
npy_intp out2_step = steps[5];
for (i = 0; i < n; i++) {
*((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2);
*((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2);
*((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2);
in0 += in0_step;
in1 += in1_step;
in2 += in2_step;
out0 += out0_step;
out1 += out1_step;
out2 += out2_step;
}
}
PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc};
static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
static void *multitest_data[1] = {NULL};
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"wrapper_module_%(num)s",
NULL,
-1,
wrapper_module_%(num)sMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "multitest", ufunc0);
Py_DECREF(ufunc0);
return m;
}
#else
PyMODINIT_FUNC initwrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "multitest", ufunc0);
Py_DECREF(ufunc0);
}
#endif""" % {'num': CodeWrapper._module_counter}
assert source == expected
|
c8177a5b82c25657889f69b195aa5cf4489d235343402aabd28c3e33678ff2cd | from io import StringIO
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy import Piecewise
from sympy import Equality
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine
from sympy.testing.pytest import raises
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_m_code():
code_gen = OctaveCodeGen()
output = StringIO()
code_gen.dump_m([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_m_simple_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0] == "test.m"
source = result[1]
expected = (
"function out1 = test(x, y, z)\n"
" out1 = z.*(x + y);\n"
"end\n"
)
assert source == expected
def test_m_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Octave", header=True, empty=False)
assert result[0] == "test.m"
source = result[1]
expected = (
"function out1 = test(x, y, z)\n"
" %TEST Autogenerated by sympy\n"
" % Code generated with sympy " + sympy.__version__ + "\n"
" %\n"
" % See http://www.sympy.org/ for more information.\n"
" %\n"
" % This file is part of 'project'\n"
" out1 = z.*(x + y);\n"
"end\n"
)
assert source == expected
def test_m_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function z = test(x, y)\n"
" z = x + y;\n"
"end\n"
)
assert source == expected
def test_m_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = test()\n"
" out1 = pi^%s;\n"
"end\n"
) % Catalan.evalf(17)
assert source == expected
@XFAIL
def test_m_numbersymbol_no_inline():
# FIXME: how to pass inline=False to the OctaveCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Octave", header=False,
empty=False, inline=False)
source = result[1]
expected = (
"function [out1, out2] = test()\n"
" Catalan = 0.915965594177219; % constant\n"
" EulerGamma = 0.5772156649015329; % constant\n"
" out1 = pi^Catalan;\n"
" out2 = EulerGamma;\n"
"end\n"
)
assert source == expected
def test_m_code_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave")
code_gen = OctaveCodeGen()
output = StringIO()
code_gen.dump_m([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"function out1 = test(z, x, y)\n"
" out1 = x + y;\n"
"end\n"
)
assert source == expected
def test_multiple_results_m():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2] = test(x, y, z)\n"
" out1 = z.*(x + y);\n"
" out2 = z.*(x - y);\n"
"end\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [C, A, B] = test(x, y, z)\n"
" C = z.*(x + y);\n"
" A = z.*(x - y);\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Octave", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.m"
source = result[0][1]
expected = (
"function [C, A, B] = test(x, z, y)\n"
" C = z.*(x + y);\n"
" A = z.*(x - y);\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_complicated_m_codegen():
from sympy import sin, cos, tan
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "testlong.m"
source = result[0][1]
expected = (
"function [out1, out2] = testlong(x, y, z)\n"
" out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)"
" + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2"
" + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n"
" out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n"
"end\n"
)
assert source == expected
def test_m_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy import sin, cos
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0] == "foo.m"
source = result[1];
expected = (
'function [out1, y, out3, a] = foo(x)\n'
' out1 = cos(2*x);\n'
' y = sin(x);\n'
' out3 = cos(x);\n'
' a = sin(2*x);\n'
'end\n'
)
assert source == expected
def test_m_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = pwtest(x)\n"
" out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n"
" (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n"
" (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n"
"end\n"
)
assert source == expected
@XFAIL
def test_m_piecewise_no_inline():
# FIXME: how to pass inline=False to the OctaveCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Octave", header=False, empty=False,
inline=False)
source = result[1]
expected = (
"function out1 = pwtest(x)\n"
" if (x < -1)\n"
" out1 = 0;\n"
" elseif (x <= 1)\n"
" out1 = x.^2;\n"
" elseif (x > 1)\n"
" out1 = -x + 2;\n"
" else\n"
" out1 = 1;\n"
" end\n"
"end\n"
)
assert source == expected
def test_m_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "foo.m"
source = result[0][1];
expected = (
"function [out1, out2] = foo(x, y)\n"
" out1 = 2*x;\n"
" out2 = 3*y;\n"
"end\n"
"function [out1, out2] = bar(y)\n"
" out1 = y.^2;\n"
" out2 = 4*y;\n"
"end\n"
)
assert source == expected
def test_m_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Octave", header=True, empty=False)
assert result[0][0] == "foo.m"
source = result[0][1];
expected = (
"function [out1, out2] = foo(x, y)\n"
" %FOO Autogenerated by sympy\n"
" % Code generated with sympy " + sympy.__version__ + "\n"
" %\n"
" % See http://www.sympy.org/ for more information.\n"
" %\n"
" % This file is part of 'project'\n"
" out1 = 2*x;\n"
" out2 = 3*y;\n"
"end\n"
"function [out1, out2] = bar(y)\n"
" out1 = y.^2;\n"
" out2 = 4*y;\n"
"end\n"
)
assert source == expected
def test_m_filename_match_first_fcn():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
raises(ValueError, lambda: codegen(name_expr,
"Octave", prefix="bar", header=False, empty=False))
def test_m_matrix_named():
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "test.m"
source = result[0][1]
expected = (
"function myout1 = test(x, y, z)\n"
" myout1 = [x 2*y pi*z];\n"
"end\n"
)
assert source == expected
def test_m_matrix_named_matsym():
myout1 = MatrixSymbol('myout1', 1, 3)
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(myout1, e2, evaluate=False))
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function myout1 = test(x, y, z)\n"
" myout1 = [x 2*y pi*z];\n"
"end\n"
)
assert source == expected
def test_m_matrix_output_autoname():
expr = Matrix([[x, x+y, 3]])
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = test(x, y)\n"
" out1 = [x x + y 3];\n"
"end\n"
)
assert source == expected
def test_m_matrix_output_autoname_2():
e1 = (x + y)
e2 = Matrix([[2*x, 2*y, 2*z]])
e3 = Matrix([[x], [y], [z]])
e4 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2, e3, e4))
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2, out3, out4] = test(x, y, z)\n"
" out1 = x + y;\n"
" out2 = [2*x 2*y 2*z];\n"
" out3 = [x; y; z];\n"
" out4 = [x y; z 16];\n"
"end\n"
)
assert source == expected
def test_m_results_matrix_named_ordered():
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, Matrix([[1, 2, x]]))
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Octave", header=False, empty=False,
argument_sequence=(x, z, y))
source = result[1]
expected = (
"function [C, A, B] = test(x, z, y)\n"
" C = z.*(x + y);\n"
" A = [1 2 x];\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 2, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C, D] = test(A)\n"
" B = A(1, :);\n"
" C = A(2, :);\n"
" D = A(:, 3);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice2():
A = MatrixSymbol('A', 3, 4)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 2, 2)
name_expr = ("test", [Equality(B, A[0:2, 0:2]),
Equality(C, A[0:2, 1:3])])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C] = test(A)\n"
" B = A(1:2, 1:2);\n"
" C = A(1:2, 2:3);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice3():
A = MatrixSymbol('A', 8, 7)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 4, 2)
name_expr = ("test", [Equality(B, A[6:, 1::3]),
Equality(C, A[::2, ::3])])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C] = test(A)\n"
" B = A(7:end, 2:3:end);\n"
" C = A(1:2:end, 1:3:end);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice_autoname():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, out2, out3, out4] = test(A)\n"
" B = A(1, :);\n"
" out2 = A(2, :);\n"
" out3 = A(:, 1);\n"
" out4 = A(:, 2);\n"
"end\n"
)
assert source == expected
def test_m_loops():
# Note: an Octave programmer would probably vectorize this across one or
# more dimensions. Also, size(A) would be used rather than passing in m
# and n. Perhaps users would expect us to vectorize automatically here?
# Or is it possible to represent such things using IndexedBase?
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Octave",
header=False, empty=False)
source = result[1]
expected = (
'function y = mat_vec_mult(A, m, n, x)\n'
' for i = 1:m\n'
' y(i) = 0;\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' y(i) = %(rhs)s + y(i);\n'
' end\n'
' end\n'
'end\n'
)
assert (source == expected % {'rhs': 'A(%s, %s).*x(j)' % (i, j)} or
source == expected % {'rhs': 'x(j).*A(%s, %s)' % (i, j)})
def test_m_tensor_loops_multiple_contractions():
# see comments in previous test about vectorizing
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A')
B = IndexedBase('B')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
"Octave", header=False, empty=False)
source = result[1]
expected = (
'function y = tensorthing(A, B, m, n, o, p)\n'
' for i = 1:m\n'
' y(i) = 0;\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' for k = 1:o\n'
' for l = 1:p\n'
' y(i) = A(i, j, k, l).*B(j, k, l) + y(i);\n'
' end\n'
' end\n'
' end\n'
' end\n'
'end\n'
)
assert source == expected
def test_m_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function x = mysqr(x)\n"
" x = x.^2;\n"
"end\n"
)
assert source == expected
def test_m_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"function x = test(x, y)\n"
" x = x.^2 + y;\n"
"end\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function x = test(x, y)\n"
" x = x.^2 + y;\n"
"end\n"
)
assert source == expected
def test_m_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2] = test(x)\n"
" % unsupported: Derivative(f(x), x)\n"
" % unsupported: zoo\n"
" out1 = Derivative(f(x), x);\n"
" out2 = zoo;\n"
"end\n"
)
assert source == expected
def test_global_vars_octave():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Octave", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"function out1 = f(x)\n"
" global y\n"
" out1 = x.*y;\n"
"end\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Octave", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"function out1 = f(x, y)\n"
" global t z\n"
" out1 = x.*y + z;\n"
"end\n"
)
assert source == expected
|
57f874f0ad61e23f04bdd591b37e0a84b1789db9353d4f56ee9e56d56fa2966e | from sympy import symbols
from sympy.external import import_module
from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar
matchpy = import_module("matchpy")
x, y, z = symbols("x y z")
def _get_first_match(expr, pattern):
from matchpy import ManyToOneMatcher, Pattern
matcher = ManyToOneMatcher()
matcher.add(Pattern(pattern))
return next(iter(matcher.match(expr)))
def test_matchpy_connector():
if matchpy is None:
return
from multiset import Multiset
from matchpy import Pattern, Substitution
w_ = WildDot("w_")
w__ = WildPlus("w__")
w___ = WildStar("w___")
expr = x + y
pattern = x + w_
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w_': y})
expr = x + y + z
pattern = x + w__
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w__': Multiset([y, z])})
expr = x + y + z
pattern = x + y + z + w___
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w___': Multiset()})
|
9b18f782da034de0378cc1eb20126d633de8f0e922d6e7d61f9f000527d9cf4b | from io import StringIO
from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function
from sympy import Piecewise
from sympy import Equality
from sympy.utilities.codegen import RustCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_rust_code():
code_gen = RustCodeGen()
output = StringIO()
code_gen.dump_rs([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_simple_rust_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0] == "test.rs"
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> f64 {\n"
" let out1 = z*(x + y);\n"
" out1\n"
"}\n"
)
assert source == expected
def test_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Rust", header=True, empty=False)
assert result[0] == "test.rs"
source = result[1]
version_str = "Code generated with sympy %s" % sympy.__version__
version_line = version_str.center(76).rstrip()
expected = (
"/*\n"
" *%(version_line)s\n"
" *\n"
" * See http://www.sympy.org/ for more information.\n"
" *\n"
" * This file is part of 'project'\n"
" */\n"
"fn test(x: f64, y: f64, z: f64) -> f64 {\n"
" let out1 = z*(x + y);\n"
" out1\n"
"}\n"
) % {'version_line': version_line}
assert source == expected
def test_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let z = x + y;\n"
" z\n"
"}\n"
)
assert source == expected
def test_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test() -> f64 {\n"
" const Catalan: f64 = %s;\n"
" let out1 = PI.powf(Catalan);\n"
" out1\n"
"}\n"
) % Catalan.evalf(17)
assert source == expected
@XFAIL
def test_numbersymbol_inline():
# FIXME: how to pass inline to the RustCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Rust", header=False,
empty=False, inline=True)
source = result[1]
expected = (
"fn test() -> (f64, f64) {\n"
" const Catalan: f64 = %s;\n"
" const EulerGamma: f64 = %s;\n"
" let out1 = PI.powf(Catalan);\n"
" let out2 = EulerGamma);\n"
" (out1, out2)\n"
"}\n"
) % (Catalan.evalf(17), EulerGamma.evalf(17))
assert source == expected
def test_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust")
code_gen = RustCodeGen()
output = StringIO()
code_gen.dump_rs([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"fn test(z: f64, x: f64, y: f64) -> f64 {\n"
" let out1 = x + y;\n"
" out1\n"
"}\n"
)
assert source == expected
def test_multiple_results_rust():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
" let out1 = z*(x + y);\n"
" let out2 = z*(x - y);\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n"
" let C = z*(x + y);\n"
" let A = z*(x - y);\n"
" let B = 2*x;\n"
" (C, A, B)\n"
"}\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Rust", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.rs"
source = result[0][1]
expected = (
"fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n"
" let C = z*(x + y);\n"
" let A = z*(x - y);\n"
" let B = 2*x;\n"
" (C, A, B)\n"
"}\n"
)
assert source == expected
def test_complicated_rs_codegen():
from sympy import sin, cos, tan
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0][0] == "testlong.rs"
source = result[0][1]
expected = (
"fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
" let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()"
" + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)"
" + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)"
" + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()"
" + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n"
" let out2 = (x + y + z).cos().cos().cos().cos()"
".cos().cos().cos().cos();\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy import sin, cos
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0] == "foo.rs"
source = result[1];
expected = (
"fn foo(x: f64) -> (f64, f64, f64, f64) {\n"
" let out1 = (2*x).cos();\n"
" let y = x.sin();\n"
" let out3 = x.cos();\n"
" let a = (2*x).sin();\n"
" (out1, y, out3, a)\n"
"}\n"
)
assert source == expected
def test_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn pwtest(x: f64) -> f64 {\n"
" let out1 = if (x < -1) {\n"
" 0\n"
" } else if (x <= 1) {\n"
" x.powi(2)\n"
" } else if (x > 1) {\n"
" 2 - x\n"
" } else {\n"
" 1\n"
" };\n"
" out1\n"
"}\n"
)
assert source == expected
@XFAIL
def test_piecewise_inline():
# FIXME: how to pass inline to the RustCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Rust", header=False, empty=False,
inline=True)
source = result[1]
expected = (
"fn pwtest(x: f64) -> f64 {\n"
" let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }"
" else if (x > 1) { -x + 2 } else { 1 };\n"
" out1\n"
"}\n"
)
assert source == expected
def test_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0][0] == "foo.rs"
source = result[0][1];
expected = (
"fn foo(x: f64, y: f64) -> (f64, f64) {\n"
" let out1 = 2*x;\n"
" let out2 = 3*y;\n"
" (out1, out2)\n"
"}\n"
"fn bar(y: f64) -> (f64, f64) {\n"
" let out1 = y.powi(2);\n"
" let out2 = 4*y;\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Rust", header=True, empty=False)
assert result[0][0] == "foo.rs"
source = result[0][1];
version_str = "Code generated with sympy %s" % sympy.__version__
version_line = version_str.center(76).rstrip()
expected = (
"/*\n"
" *%(version_line)s\n"
" *\n"
" * See http://www.sympy.org/ for more information.\n"
" *\n"
" * This file is part of 'project'\n"
" */\n"
"fn foo(x: f64, y: f64) -> (f64, f64) {\n"
" let out1 = 2*x;\n"
" let out2 = 3*y;\n"
" (out1, out2)\n"
"}\n"
"fn bar(y: f64) -> (f64, f64) {\n"
" let out1 = y.powi(2);\n"
" let out2 = 4*y;\n"
" (out1, out2)\n"
"}\n"
) % {'version_line': version_line}
assert source == expected
def test_filename_match_prefix():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result, = codegen(name_expr, "Rust", prefix="baz", header=False,
empty=False)
assert result[0] == "baz.rs"
def test_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn mysqr(x: f64) -> f64 {\n"
" let x = x.powi(2);\n"
" x\n"
"}\n"
)
assert source == expected
def test_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let x = x.powi(2) + y;\n"
" x\n"
"}\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let x = x.powi(2) + y;\n"
" x\n"
"}\n"
)
assert source == expected
def test_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64) -> (f64, f64) {\n"
" // unsupported: Derivative(f(x), x)\n"
" // unsupported: zoo\n"
" let out1 = Derivative(f(x), x);\n"
" let out2 = zoo;\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_global_vars_rust():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Rust", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"fn f(x: f64) -> f64 {\n"
" let out1 = x*y;\n"
" out1\n"
"}\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Rust", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"fn f(x: f64, y: f64) -> f64 {\n"
" let out1 = x*y + z;\n"
" out1\n"
"}\n"
)
assert source == expected
|
05a3b2bd911ca308722ae194cadf7fea095f308ea30d422947fd519c36e29420 | from textwrap import dedent
from itertools import islice, product
from sympy import (
symbols, Integer, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix,
factorial, true)
from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
from sympy.core.compatibility import iterable
from sympy.utilities.iterables import (
_partition, _set_partitions, binary_partitions, bracelets, capture,
cartes, common_prefix, common_suffix, connected_components, dict_merge,
filter_symbols, flatten, generate_bell, generate_derangements,
generate_involutions, generate_oriented_forest, group, has_dups, ibin,
iproduct, kbins, minlex, multiset, multiset_combinations,
multiset_partitions, multiset_permutations, necklaces, numbered_symbols,
ordered, partitions, permutations, postfixes, postorder_traversal,
prefixes, reshape, rotate_left, rotate_right, runs, sift,
strongly_connected_components, subsets, take, topological_sort, unflatten,
uniq, variations, ordered_partitions, rotations, is_palindromic)
from sympy.utilities.enumerative import (
factoring_visitor, multiset_partitions_taocp )
from sympy.core.singleton import S
from sympy.functions.elementary.piecewise import Piecewise, ExprCondPair
from sympy.testing.pytest import raises
w, x, y, z = symbols('w,x,y,z')
def test_is_palindromic():
assert is_palindromic('')
assert is_palindromic('x')
assert is_palindromic('xx')
assert is_palindromic('xyx')
assert not is_palindromic('xy')
assert not is_palindromic('xyzx')
assert is_palindromic('xxyzzyx', 1)
assert not is_palindromic('xxyzzyx', 2)
assert is_palindromic('xxyzzyx', 2, -1)
assert is_palindromic('xxyzzyx', 2, 6)
assert is_palindromic('xxyzyx', 1)
assert not is_palindromic('xxyzyx', 2)
assert is_palindromic('xxyzyx', 2, 2 + 3)
def test_postorder_traversal():
expr = z + w*(x + y)
expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z]
assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(expr, keys=True)) == expected
expr = Piecewise((x, x < 1), (x**2, True))
expected = [
x, 1, x, x < 1, ExprCondPair(x, x < 1),
2, x, x**2, true,
ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True))
]
assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(
[expr], keys=default_sort_key)) == expected + [[expr]]
assert list(postorder_traversal(Integral(x**2, (x, 0, 1)),
keys=default_sort_key)) == [
2, x, x**2, 0, 1, x, Tuple(x, 0, 1),
Integral(x**2, Tuple(x, 0, 1))
]
assert list(postorder_traversal(('abc', ('d', 'ef')))) == [
'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))]
def test_flatten():
assert flatten((1, (1,))) == [1, 1]
assert flatten((x, (x,))) == [x, x]
ls = [[(-2, -1), (1, 2)], [(0, 0)]]
assert flatten(ls, levels=0) == ls
assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)]
assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0]
assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0]
raises(ValueError, lambda: flatten(ls, levels=-1))
class MyOp(Basic):
pass
assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z]
assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z]
assert flatten({1, 11, 2}) == list({1, 11, 2})
def test_iproduct():
assert list(iproduct()) == [()]
assert list(iproduct([])) == []
assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)]
assert sorted(iproduct([1, 2], [3, 4, 5])) == [
(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
assert sorted(iproduct([0,1],[0,1],[0,1])) == [
(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)]
assert iterable(iproduct(S.Integers)) is True
assert iterable(iproduct(S.Integers, S.Integers)) is True
assert (3,) in iproduct(S.Integers)
assert (4, 5) in iproduct(S.Integers, S.Integers)
assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers)
triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000))
for n1, n2, n3 in triples:
assert isinstance(n1, Integer)
assert isinstance(n2, Integer)
assert isinstance(n3, Integer)
for t in set(product(*([range(-2, 3)]*3))):
assert t in iproduct(S.Integers, S.Integers, S.Integers)
def test_group():
assert group([]) == []
assert group([], multiple=False) == []
assert group([1]) == [[1]]
assert group([1], multiple=False) == [(1, 1)]
assert group([1, 1]) == [[1, 1]]
assert group([1, 1], multiple=False) == [(1, 2)]
assert group([1, 1, 1]) == [[1, 1, 1]]
assert group([1, 1, 1], multiple=False) == [(1, 3)]
assert group([1, 2, 1]) == [[1], [2], [1]]
assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)]
assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]]
assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2),
(2, 3), (1, 1), (3, 2)]
def test_subsets():
# combinations
assert list(subsets([1, 2, 3], 0)) == [()]
assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)]
assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)]
l = list(range(4))
assert list(subsets(l, 0, repetition=True)) == [()]
assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 1), (1, 2),
(1, 3), (2, 2), (2, 3),
(3, 3)]
assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1),
(0, 0, 2), (0, 0, 3),
(0, 1, 1), (0, 1, 2),
(0, 1, 3), (0, 2, 2),
(0, 2, 3), (0, 3, 3),
(1, 1, 1), (1, 1, 2),
(1, 1, 3), (1, 2, 2),
(1, 2, 3), (1, 3, 3),
(2, 2, 2), (2, 2, 3),
(2, 3, 3), (3, 3, 3)]
assert len(list(subsets(l, 4, repetition=True))) == 35
assert list(subsets(l[:2], 3, repetition=False)) == []
assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(1, 1, 1)]
assert list(subsets([1, 2], repetition=True)) == \
[(), (1,), (2,), (1, 1), (1, 2), (2, 2)]
assert list(subsets([1, 2], repetition=False)) == \
[(), (1,), (2,), (1, 2)]
assert list(subsets([1, 2, 3], 2)) == \
[(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 2, repetition=True)) == \
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
def test_variations():
# permutations
l = list(range(4))
assert list(variations(l, 0, repetition=False)) == [()]
assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)]
assert list(variations(l, 0, repetition=True)) == [()]
assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 0), (1, 1),
(1, 2), (1, 3), (2, 0),
(2, 1), (2, 2), (2, 3),
(3, 0), (3, 1), (3, 2),
(3, 3)]
assert len(list(variations(l, 3, repetition=True))) == 64
assert len(list(variations(l, 4, repetition=True))) == 256
assert list(variations(l[:2], 3, repetition=False)) == []
assert list(variations(l[:2], 3, repetition=True)) == [
(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)
]
def test_cartes():
assert list(cartes([1, 2], [3, 4, 5])) == \
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
assert list(cartes()) == [()]
assert list(cartes('a')) == [('a',)]
assert list(cartes('a', repeat=2)) == [('a', 'a')]
assert list(cartes(list(range(2)))) == [(0,), (1,)]
def test_filter_symbols():
s = numbered_symbols()
filtered = filter_symbols(s, symbols("x0 x2 x3"))
assert take(filtered, 3) == list(symbols("x1 x4 x5"))
def test_numbered_symbols():
s = numbered_symbols(cls=Dummy)
assert isinstance(next(s), Dummy)
assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \
symbols('C2')
def test_sift():
assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == (
[1, 3], [0, 2])
assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == (
[1], [0, 2, 3])
raises(ValueError, lambda:
sift([0, 1, 2, 3], lambda x: x % 3, binary=True))
def test_take():
X = numbered_symbols()
assert take(X, 5) == list(symbols('x0:5'))
assert take(X, 5) == list(symbols('x5:10'))
assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_dict_merge():
assert dict_merge({}, {1: x, y: z}) == {1: x, y: z}
assert dict_merge({1: x, y: z}, {}) == {1: x, y: z}
assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z}
def test_prefixes():
assert list(prefixes([])) == []
assert list(prefixes([1])) == [[1]]
assert list(prefixes([1, 2])) == [[1], [1, 2]]
assert list(prefixes([1, 2, 3, 4, 5])) == \
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
def test_postfixes():
assert list(postfixes([])) == []
assert list(postfixes([1])) == [[1]]
assert list(postfixes([1, 2])) == [[2], [1, 2]]
assert list(postfixes([1, 2, 3, 4, 5])) == \
[[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
def test_topological_sort():
V = [2, 3, 5, 7, 8, 9, 10, 11]
E = [(7, 11), (7, 8), (5, 11),
(3, 8), (3, 10), (11, 2),
(11, 9), (11, 10), (8, 9)]
assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10]
assert topological_sort((V, E), key=lambda v: -v) == \
[7, 5, 11, 3, 10, 8, 9, 2]
raises(ValueError, lambda: topological_sort((V, E + [(10, 7)])))
def test_strongly_connected_components():
assert strongly_connected_components(([], [])) == []
assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
V = [1, 2, 3]
E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
assert strongly_connected_components((V, E)) == [[1, 2, 3]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 3), (3, 2), (3, 4)]
assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 1), (3, 4), (4, 3)]
assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]]
def test_connected_components():
assert connected_components(([], [])) == []
assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
V = [1, 2, 3]
E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
assert connected_components((V, E)) == [[1, 2, 3]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 3), (3, 2), (3, 4)]
assert connected_components((V, E)) == [[1, 2, 3, 4]]
V = [1, 2, 3, 4]
E = [(1, 2), (3, 4)]
assert connected_components((V, E)) == [[1, 2], [3, 4]]
def test_rotate():
A = [0, 1, 2, 3, 4]
assert rotate_left(A, 2) == [2, 3, 4, 0, 1]
assert rotate_right(A, 1) == [4, 0, 1, 2, 3]
A = []
B = rotate_right(A, 1)
assert B == []
B.append(1)
assert A == []
B = rotate_left(A, 1)
assert B == []
B.append(1)
assert A == []
def test_multiset_partitions():
A = [0, 1, 2, 3, 4]
assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]]
assert len(list(multiset_partitions(A, 4))) == 10
assert len(list(multiset_partitions(A, 3))) == 25
assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [
[[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]],
[[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]]
assert list(multiset_partitions([1, 1, 2, 2], 2)) == [
[[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]],
[[1, 2], [1, 2]]]
assert list(multiset_partitions([1, 2, 3, 4], 2)) == [
[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
assert list(multiset_partitions([1, 2, 2], 2)) == [
[[1, 2], [2]], [[1], [2, 2]]]
assert list(multiset_partitions(3)) == [
[[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]],
[[0], [1], [2]]]
assert list(multiset_partitions(3, 2)) == [
[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]]
assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]]
assert list(multiset_partitions([1] * 3)) == [
[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
a = [3, 2, 1]
assert list(multiset_partitions(a)) == \
list(multiset_partitions(sorted(a)))
assert list(multiset_partitions(a, 5)) == []
assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]]
assert list(multiset_partitions(a + [4], 5)) == []
assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]]
assert list(multiset_partitions(2, 5)) == []
assert list(multiset_partitions(2, 1)) == [[[0, 1]]]
assert list(multiset_partitions('a')) == [[['a']]]
assert list(multiset_partitions('a', 2)) == []
assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]]
assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]]
assert list(multiset_partitions('aaa', 1)) == [['aaa']]
assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]]
ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'),
('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'),
('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'),
('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'),
('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'),
('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'),
('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'),
('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'),
('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'),
('m', 'py', 's', 'y'), ('m', 'p', 'syy'),
('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'),
('m', 'p', 's', 'y', 'y')]
assert list(tuple("".join(part) for part in p)
for p in multiset_partitions('sympy')) == ans
factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3],
[6, 2, 2], [2, 2, 2, 3]]
assert list(factoring_visitor(p, [2,3]) for
p in multiset_partitions_taocp([3, 1])) == factorings
def test_multiset_combinations():
ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips',
'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss']
assert [''.join(i) for i in
list(multiset_combinations('mississippi', 3))] == ans
M = multiset('mississippi')
assert [''.join(i) for i in
list(multiset_combinations(M, 3))] == ans
assert [''.join(i) for i in multiset_combinations(M, 30)] == []
assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]]
assert len(list(multiset_combinations('a', 3))) == 0
assert len(list(multiset_combinations('a', 0))) == 1
assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']]
def test_multiset_permutations():
ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab',
'byba', 'yabb', 'ybab', 'ybba']
assert [''.join(i) for i in multiset_permutations('baby')] == ans
assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans
assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]]
assert list(multiset_permutations([0, 2, 1], 2)) == [
[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
assert len(list(multiset_permutations('a', 0))) == 1
assert len(list(multiset_permutations('a', 3))) == 0
def test():
for i in range(1, 7):
print(i)
for p in multiset_permutations([0, 0, 1, 0, 1], i):
print(p)
assert capture(lambda: test()) == dedent('''\
1
[0]
[1]
2
[0, 0]
[0, 1]
[1, 0]
[1, 1]
3
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
4
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]
5
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[0, 0, 1, 1, 0]
[0, 1, 0, 0, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 0]
[1, 0, 0, 0, 1]
[1, 0, 0, 1, 0]
[1, 0, 1, 0, 0]
[1, 1, 0, 0, 0]
6\n''')
def test_partitions():
ans = [[{}], [(0, {})]]
for i in range(2):
assert list(partitions(0, size=i)) == ans[i]
assert list(partitions(1, 0, size=i)) == ans[i]
assert list(partitions(6, 2, 2, size=i)) == ans[i]
assert list(partitions(6, 2, None, size=i)) != ans[i]
assert list(partitions(6, None, 2, size=i)) != ans[i]
assert list(partitions(6, 2, 0, size=i)) == ans[i]
assert [p for p in partitions(6, k=2)] == [
{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]
assert [p for p in partitions(6, k=3)] == [
{3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2},
{1: 4, 2: 1}, {1: 6}]
assert [p for p in partitions(8, k=4, m=3)] == [
{4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [
i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i)
and sum(i.values()) <=3]
assert [p for p in partitions(S(3), m=2)] == [
{3: 1}, {1: 1, 2: 1}]
assert [i for i in partitions(4, k=3)] == [
{1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [
i for i in partitions(4) if all(k <= 3 for k in i)]
# Consistency check on output of _partitions and RGS_unrank.
# This provides a sanity test on both routines. Also verifies that
# the total number of partitions is the same in each case.
# (from pkrathmann2)
for n in range(2, 6):
i = 0
for m, q in _set_partitions(n):
assert q == RGS_unrank(i, n)
i += 1
assert i == RGS_enum(n)
def test_binary_partitions():
assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1],
[4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1],
[4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2],
[2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1],
[2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
assert len([j[:] for j in binary_partitions(16)]) == 36
def test_bell_perm():
assert [len(set(generate_bell(i))) for i in range(1, 7)] == [
factorial(i) for i in range(1, 7)]
assert list(generate_bell(3)) == [
(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
# generate_bell and trotterjohnson are advertised to return the same
# permutations; this is not technically necessary so this test could
# be removed
for n in range(1, 5):
p = Permutation(range(n))
b = generate_bell(n)
for bi in b:
assert bi == tuple(p.array_form)
p = p.next_trotterjohnson()
raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms?
def test_involutions():
lengths = [1, 2, 4, 10, 26, 76]
for n, N in enumerate(lengths):
i = list(generate_involutions(n + 1))
assert len(i) == N
assert len({Permutation(j)**2 for j in i}) == 1
def test_derangements():
assert len(list(generate_derangements(list(range(6))))) == 265
assert ''.join(''.join(i) for i in generate_derangements('abcde')) == (
'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd'
'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab'
'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb'
'edbacedbca')
assert list(generate_derangements([0, 1, 2, 3])) == [
[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1],
[2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]]
assert list(generate_derangements([0, 1, 2, 2])) == [
[2, 2, 0, 1], [2, 2, 1, 0]]
assert list(generate_derangements('ba')) == [list('ab')]
def test_necklaces():
def count(n, k, f):
return len(list(necklaces(n, k, f)))
m = []
for i in range(1, 8):
m.append((
i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1)))
assert Matrix(m) == Matrix([
[1, 2, 2, 3],
[2, 3, 3, 6],
[3, 4, 4, 10],
[4, 6, 6, 21],
[5, 8, 8, 39],
[6, 14, 13, 92],
[7, 20, 18, 198]])
def test_bracelets():
bc = [i for i in bracelets(2, 4)]
assert Matrix(bc) == Matrix([
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 3],
[3, 3]
])
bc = [i for i in bracelets(4, 2)]
assert Matrix(bc) == Matrix([
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]
])
def test_generate_oriented_forest():
assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0],
[0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2],
[0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0],
[0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0],
[0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
assert len(list(generate_oriented_forest(10))) == 1842
def test_unflatten():
r = list(range(10))
assert unflatten(r) == list(zip(r[::2], r[1::2]))
assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])]
raises(ValueError, lambda: unflatten(list(range(10)), 3))
raises(ValueError, lambda: unflatten(list(range(10)), -2))
def test_common_prefix_suffix():
assert common_prefix([], [1]) == []
assert common_prefix(list(range(3))) == [0, 1, 2]
assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2]
assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2]
assert common_prefix([1, 2, 3], [1, 3, 5]) == [1]
assert common_suffix([], [1]) == []
assert common_suffix(list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(4))) == []
assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3]
assert common_suffix([1, 2, 3], [9, 7, 3]) == [3]
def test_minlex():
assert minlex([1, 2, 0]) == (0, 1, 2)
assert minlex((1, 2, 0)) == (0, 1, 2)
assert minlex((1, 0, 2)) == (0, 2, 1)
assert minlex((1, 0, 2), directed=False) == (0, 1, 2)
assert minlex('aba') == 'aab'
assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa')
def test_ordered():
assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]]
assert list(ordered((x, y), hash, default=False)) == \
list(ordered((y, x), hash, default=False))
assert list(ordered((x, y))) == [x, y]
seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]],
(lambda x: len(x), lambda x: sum(x))]
assert list(ordered(seq, keys, default=False, warn=False)) == \
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
raises(ValueError, lambda:
list(ordered(seq, keys, default=False, warn=True)))
def test_runs():
assert runs([]) == []
assert runs([1]) == [[1]]
assert runs([1, 1]) == [[1], [1]]
assert runs([1, 1, 2]) == [[1], [1, 2]]
assert runs([1, 2, 1]) == [[1, 2], [1]]
assert runs([2, 1, 1]) == [[2], [1], [1]]
from operator import lt
assert runs([2, 1, 1], lt) == [[2, 1], [1]]
def test_reshape():
seq = list(range(1, 9))
assert reshape(seq, [4]) == \
[[1, 2, 3, 4], [5, 6, 7, 8]]
assert reshape(seq, (4,)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, 2)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, [2])) == \
[(1, 2, [3, 4]), (5, 6, [7, 8])]
assert reshape(seq, ((2,), [2])) == \
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
assert reshape(seq, (1, [2], 1)) == \
[(1, [2, 3], 4), (5, [6, 7], 8)]
assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
assert reshape(tuple(seq), ([1], 1, (2,))) == \
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \
[[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
raises(ValueError, lambda: reshape([0, 1], [-1]))
raises(ValueError, lambda: reshape([0, 1], [3]))
def test_uniq():
assert list(uniq(p for p in partitions(4))) == \
[{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}]
assert list(uniq(x % 2 for x in range(5))) == [0, 1]
assert list(uniq('a')) == ['a']
assert list(uniq('ababc')) == list('abc')
assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]]
assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \
[([1], 2, 2), (2, [1], 2), (2, 2, [1])]
assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \
[2, 3, 4, [2], [1], [3]]
f = [1]
raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
f = [[1]]
raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
def test_kbins():
assert len(list(kbins('1123', 2, ordered=1))) == 24
assert len(list(kbins('1123', 2, ordered=11))) == 36
assert len(list(kbins('1123', 2, ordered=10))) == 10
assert len(list(kbins('1123', 2, ordered=0))) == 5
assert len(list(kbins('1123', 2, ordered=None))) == 3
def test1():
for orderedval in [None, 0, 1, 10, 11]:
print('ordered =', orderedval)
for p in kbins([0, 0, 1], 2, ordered=orderedval):
print(' ', p)
assert capture(lambda : test1()) == dedent('''\
ordered = None
[[0], [0, 1]]
[[0, 0], [1]]
ordered = 0
[[0, 0], [1]]
[[0, 1], [0]]
ordered = 1
[[0], [0, 1]]
[[0], [1, 0]]
[[1], [0, 0]]
ordered = 10
[[0, 0], [1]]
[[1], [0, 0]]
[[0, 1], [0]]
[[0], [0, 1]]
ordered = 11
[[0], [0, 1]]
[[0, 0], [1]]
[[0], [1, 0]]
[[0, 1], [0]]
[[1], [0, 0]]
[[1, 0], [0]]\n''')
def test2():
for orderedval in [None, 0, 1, 10, 11]:
print('ordered =', orderedval)
for p in kbins(list(range(3)), 2, ordered=orderedval):
print(' ', p)
assert capture(lambda : test2()) == dedent('''\
ordered = None
[[0], [1, 2]]
[[0, 1], [2]]
ordered = 0
[[0, 1], [2]]
[[0, 2], [1]]
[[0], [1, 2]]
ordered = 1
[[0], [1, 2]]
[[0], [2, 1]]
[[1], [0, 2]]
[[1], [2, 0]]
[[2], [0, 1]]
[[2], [1, 0]]
ordered = 10
[[0, 1], [2]]
[[2], [0, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[0], [1, 2]]
[[1, 2], [0]]
ordered = 11
[[0], [1, 2]]
[[0, 1], [2]]
[[0], [2, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[1, 0], [2]]
[[1], [2, 0]]
[[1, 2], [0]]
[[2], [0, 1]]
[[2, 0], [1]]
[[2], [1, 0]]
[[2, 1], [0]]\n''')
def test_has_dups():
assert has_dups(set()) is False
assert has_dups(list(range(3))) is False
assert has_dups([1, 2, 1]) is True
def test__partition():
assert _partition('abcde', [1, 0, 1, 2, 0]) == [
['b', 'e'], ['a', 'c'], ['d']]
assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [
['b', 'e'], ['a', 'c'], ['d']]
output = (3, [1, 0, 1, 2, 0])
assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']]
def test_ordered_partitions():
from sympy.functions.combinatorial.numbers import nT
f = ordered_partitions
assert list(f(0, 1)) == [[]]
assert list(f(1, 0)) == [[]]
for i in range(1, 7):
for j in [None] + list(range(1, i)):
assert (
sum(1 for p in f(i, j, 1)) ==
sum(1 for p in f(i, j, 0)) ==
nT(i, j))
def test_rotations():
assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']]
assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]]
assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]]
def test_ibin():
assert ibin(3) == [1, 1]
assert ibin(3, 3) == [0, 1, 1]
assert ibin(3, str=True) == '11'
assert ibin(3, 3, str=True) == '011'
assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)]
assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11']
raises(ValueError, lambda: ibin(-.5))
raises(ValueError, lambda: ibin(2, 1))
|
5a1ab85fecc22c96d539abc2fd5fcc94fd28afd807a75eb3b166f04060a3b674 | from io import StringIO
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy import Piecewise
from sympy import Equality
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_jl_code():
code_gen = JuliaCodeGen()
output = StringIO()
code_gen.dump_jl([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_jl_simple_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0] == "test.jl"
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = z.*(x + y)\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Julia", header=True, empty=False)
assert result[0] == "test.jl"
source = result[1]
expected = (
"# Code generated with sympy " + sympy.__version__ + "\n"
"#\n"
"# See http://www.sympy.org/ for more information.\n"
"#\n"
"# This file is part of 'project'\n"
"function test(x, y, z)\n"
" out1 = z.*(x + y)\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" z = x + y\n"
" return z\n"
"end\n"
)
assert source == expected
def test_jl_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test()\n"
" out1 = pi^catalan\n"
" return out1\n"
"end\n"
)
assert source == expected
@XFAIL
def test_jl_numbersymbol_no_inline():
# FIXME: how to pass inline=False to the JuliaCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Julia", header=False,
empty=False, inline=False)
source = result[1]
expected = (
"function test()\n"
" Catalan = 0.915965594177219\n"
" EulerGamma = 0.5772156649015329\n"
" out1 = pi^Catalan\n"
" out2 = EulerGamma\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_code_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia")
code_gen = JuliaCodeGen()
output = StringIO()
code_gen.dump_jl([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"function test(z, x, y)\n"
" out1 = x + y\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_multiple_results_m():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = z.*(x + y)\n"
" out2 = z.*(x - y)\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" C = z.*(x + y)\n"
" A = z.*(x - y)\n"
" B = 2*x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Julia", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.jl"
source = result[0][1]
expected = (
"function test(x, z, y)\n"
" C = z.*(x + y)\n"
" A = z.*(x - y)\n"
" B = 2*x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_complicated_jl_codegen():
from sympy import sin, cos, tan
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "testlong.jl"
source = result[0][1]
expected = (
"function testlong(x, y, z)\n"
" out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)"
" + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2"
" + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3\n"
" out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy import sin, cos
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0] == "foo.jl"
source = result[1];
expected = (
'function foo(x)\n'
' out1 = cos(2*x)\n'
' y = sin(x)\n'
' out3 = cos(x)\n'
' a = sin(2*x)\n'
' return out1, y, out3, a\n'
'end\n'
)
assert source == expected
def test_jl_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function pwtest(x)\n"
" out1 = ((x < -1) ? (0) :\n"
" (x <= 1) ? (x.^2) :\n"
" (x > 1) ? (2 - x) : (1))\n"
" return out1\n"
"end\n"
)
assert source == expected
@XFAIL
def test_jl_piecewise_no_inline():
# FIXME: how to pass inline=False to the JuliaCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Julia", header=False, empty=False,
inline=False)
source = result[1]
expected = (
"function pwtest(x)\n"
" if (x < -1)\n"
" out1 = 0\n"
" elseif (x <= 1)\n"
" out1 = x.^2\n"
" elseif (x > 1)\n"
" out1 = -x + 2\n"
" else\n"
" out1 = 1\n"
" end\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "foo.jl"
source = result[0][1];
expected = (
"function foo(x, y)\n"
" out1 = 2*x\n"
" out2 = 3*y\n"
" return out1, out2\n"
"end\n"
"function bar(y)\n"
" out1 = y.^2\n"
" out2 = 4*y\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Julia", header=True, empty=False)
assert result[0][0] == "foo.jl"
source = result[0][1];
expected = (
"# Code generated with sympy " + sympy.__version__ + "\n"
"#\n"
"# See http://www.sympy.org/ for more information.\n"
"#\n"
"# This file is part of 'project'\n"
"function foo(x, y)\n"
" out1 = 2*x\n"
" out2 = 3*y\n"
" return out1, out2\n"
"end\n"
"function bar(y)\n"
" out1 = y.^2\n"
" out2 = 4*y\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_filename_match_prefix():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result, = codegen(name_expr, "Julia", prefix="baz", header=False,
empty=False)
assert result[0] == "baz.jl"
def test_jl_matrix_named():
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "test.jl"
source = result[0][1]
expected = (
"function test(x, y, z)\n"
" myout1 = [x 2*y pi*z]\n"
" return myout1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_named_matsym():
myout1 = MatrixSymbol('myout1', 1, 3)
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(myout1, e2, evaluate=False))
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" myout1 = [x 2*y pi*z]\n"
" return myout1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_output_autoname():
expr = Matrix([[x, x+y, 3]])
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" out1 = [x x + y 3]\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_output_autoname_2():
e1 = (x + y)
e2 = Matrix([[2*x, 2*y, 2*z]])
e3 = Matrix([[x], [y], [z]])
e4 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2, e3, e4))
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = x + y\n"
" out2 = [2*x 2*y 2*z]\n"
" out3 = [x, y, z]\n"
" out4 = [x y;\n"
" z 16]\n"
" return out1, out2, out3, out4\n"
"end\n"
)
assert source == expected
def test_jl_results_matrix_named_ordered():
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, Matrix([[1, 2, x]]))
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Julia", header=False, empty=False,
argument_sequence=(x, z, y))
source = result[1]
expected = (
"function test(x, z, y)\n"
" C = z.*(x + y)\n"
" A = [1 2 x]\n"
" B = 2*x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 2, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1,:]\n"
" C = A[2,:]\n"
" D = A[:,3]\n"
" return B, C, D\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice2():
A = MatrixSymbol('A', 3, 4)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 2, 2)
name_expr = ("test", [Equality(B, A[0:2, 0:2]),
Equality(C, A[0:2, 1:3])])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1:2,1:2]\n"
" C = A[1:2,2:3]\n"
" return B, C\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice3():
A = MatrixSymbol('A', 8, 7)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 4, 2)
name_expr = ("test", [Equality(B, A[6:, 1::3]),
Equality(C, A[::2, ::3])])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[7:end,2:3:end]\n"
" C = A[1:2:end,1:3:end]\n"
" return B, C\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice_autoname():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1,:]\n"
" out2 = A[2,:]\n"
" out3 = A[:,1]\n"
" out4 = A[:,2]\n"
" return B, out2, out3, out4\n"
"end\n"
)
assert source == expected
def test_jl_loops():
# Note: an Julia programmer would probably vectorize this across one or
# more dimensions. Also, size(A) would be used rather than passing in m
# and n. Perhaps users would expect us to vectorize automatically here?
# Or is it possible to represent such things using IndexedBase?
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia",
header=False, empty=False)
source = result[1]
expected = (
'function mat_vec_mult(y, A, m, n, x)\n'
' for i = 1:m\n'
' y[i] = 0\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' y[i] = %(rhs)s + y[i]\n'
' end\n'
' end\n'
' return y\n'
'end\n'
)
assert (source == expected % {'rhs': 'A[%s,%s].*x[j]' % (i, j)} or
source == expected % {'rhs': 'x[j].*A[%s,%s]' % (i, j)})
def test_jl_tensor_loops_multiple_contractions():
# see comments in previous test about vectorizing
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A')
B = IndexedBase('B')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
"Julia", header=False, empty=False)
source = result[1]
expected = (
'function tensorthing(y, A, B, m, n, o, p)\n'
' for i = 1:m\n'
' y[i] = 0\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' for k = 1:o\n'
' for l = 1:p\n'
' y[i] = A[i,j,k,l].*B[j,k,l] + y[i]\n'
' end\n'
' end\n'
' end\n'
' end\n'
' return y\n'
'end\n'
)
assert source == expected
def test_jl_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function mysqr(x)\n"
" x = x.^2\n"
" return x\n"
"end\n"
)
assert source == expected
def test_jl_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"function test(x, y)\n"
" x = x.^2 + y\n"
" return x\n"
"end\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" x = x.^2 + y\n"
" return x\n"
"end\n"
)
assert source == expected
def test_jl_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x)\n"
" # unsupported: Derivative(f(x), x)\n"
" # unsupported: zoo\n"
" out1 = Derivative(f(x), x)\n"
" out2 = zoo\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_global_vars_octave():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Julia", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"function f(x)\n"
" out1 = x.*y\n"
" return out1\n"
"end\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Julia", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"function f(x, y)\n"
" out1 = x.*y + z\n"
" return out1\n"
"end\n"
)
assert source == expected
|
3aa79bd10bce186bc244c26d99e5989066c7010ecf8c230adc406e11826786f5 | from io import StringIO
from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy
from sympy import erf, Integral, Symbol
from sympy import Equality
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import (
codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument,
CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument,
InOutArgument)
from sympy.testing.pytest import raises
from sympy.utilities.lambdify import implemented_function
#FIXME: Fails due to circular import in with core
# from sympy import codegen
def get_string(dump_fn, routines, prefix="file", header=False, empty=False):
"""Wrapper for dump_fn. dump_fn writes its results to a stream object and
this wrapper returns the contents of that stream as a string. This
auxiliary function is used by many tests below.
The header and the empty lines are not generated to facilitate the
testing of the output.
"""
output = StringIO()
dump_fn(routines, output, prefix, header, empty)
source = output.getvalue()
output.close()
return source
def test_Routine_argument_order():
a, x, y, z = symbols('a x y z')
expr = (x + y)*z
raises(CodeGenArgumentListError, lambda: make_routine("test", expr,
argument_sequence=[z, x]))
raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a,
expr), argument_sequence=[z, x, y]))
r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
assert [ type(arg) for arg in r.arguments ] == [
InputArgument, InputArgument, OutputArgument, InputArgument ]
r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y])
assert [ type(arg) for arg in r.arguments ] == [
InOutArgument, InputArgument, InputArgument ]
from sympy.tensor import IndexedBase, Idx
A, B = map(IndexedBase, ['A', 'B'])
m = symbols('m', integer=True)
i = Idx('i', m)
r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m])
assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m]
expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3))
r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
def test_empty_c_code():
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [])
assert source == "#include \"file.h\"\n#include <math.h>\n"
def test_empty_c_code_with_comment():
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [], header=True)
assert source[:82] == (
"/******************************************************************************\n *"
)
# " Code generated with sympy 0.7.2-git "
assert source[158:] == ( "*\n"
" * *\n"
" * See http://www.sympy.org/ for more information. *\n"
" * *\n"
" * This file is part of 'project' *\n"
" ******************************************************************************/\n"
"#include \"file.h\"\n"
"#include <math.h>\n"
)
def test_empty_c_header():
code_gen = C99CodeGen()
source = get_string(code_gen.dump_h, [])
assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n"
def test_simple_c_code():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x, double y, double z) {\n"
" double test_result;\n"
" test_result = z*(x + y);\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_c_code_reserved_words():
x, y, z = symbols('if, typedef, while')
expr = (x + y) * z
routine = make_routine("test", expr)
code_gen = C99CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double if_, double typedef_, double while_) {\n"
" double test_result;\n"
" test_result = while_*(if_ + typedef_);\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_numbersymbol_c_code():
routine = make_routine("test", pi**Catalan)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test() {\n"
" double test_result;\n"
" double const Catalan = %s;\n"
" test_result = pow(M_PI, Catalan);\n"
" return test_result;\n"
"}\n"
) % Catalan.evalf(17)
assert source == expected
def test_c_code_argument_order():
x, y, z = symbols('x,y,z')
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y])
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double z, double x, double y) {\n"
" double test_result;\n"
" test_result = x + y;\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_simple_c_header():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_h, [routine])
expected = (
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x, double y, double z);\n"
"#endif\n"
)
assert source == expected
def test_simple_c_codegen():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
expected = [
("file.c",
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x, double y, double z) {\n"
" double test_result;\n"
" test_result = z*(x + y);\n"
" return test_result;\n"
"}\n"),
("file.h",
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x, double y, double z);\n"
"#endif\n")
]
result = codegen(("test", expr), "C", "file", header=False, empty=False)
assert result == expected
def test_multiple_results_c():
x, y, z = symbols('x,y,z')
expr1 = (x + y)*z
expr2 = (x - y)*z
routine = make_routine(
"test",
[expr1, expr2]
)
code_gen = C99CodeGen()
raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
def test_no_results_c():
raises(ValueError, lambda: make_routine("test", []))
def test_ansi_math1_codegen():
# not included: log10
from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln,
sin, sinh, sqrt, tan, tanh, Abs)
x = symbols('x')
name_expr = [
("test_fabs", Abs(x)),
("test_acos", acos(x)),
("test_asin", asin(x)),
("test_atan", atan(x)),
("test_ceil", ceiling(x)),
("test_cos", cos(x)),
("test_cosh", cosh(x)),
("test_floor", floor(x)),
("test_log", log(x)),
("test_ln", ln(x)),
("test_sin", sin(x)),
("test_sinh", sinh(x)),
("test_sqrt", sqrt(x)),
("test_tan", tan(x)),
("test_tanh", tanh(x)),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n'
'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n'
'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n'
'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n'
'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n'
'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n'
'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n'
'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n'
'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n'
'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n'
'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n'
'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n'
'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n'
'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n'
'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
'double test_fabs(double x);\ndouble test_acos(double x);\n'
'double test_asin(double x);\ndouble test_atan(double x);\n'
'double test_ceil(double x);\ndouble test_cos(double x);\n'
'double test_cosh(double x);\ndouble test_floor(double x);\n'
'double test_log(double x);\ndouble test_ln(double x);\n'
'double test_sin(double x);\ndouble test_sinh(double x);\n'
'double test_sqrt(double x);\ndouble test_tan(double x);\n'
'double test_tanh(double x);\n#endif\n'
)
def test_ansi_math2_codegen():
# not included: frexp, ldexp, modf, fmod
from sympy import atan2
x, y = symbols('x,y')
name_expr = [
("test_atan2", atan2(x, y)),
("test_pow", x**y),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n'
'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
'double test_atan2(double x, double y);\n'
'double test_pow(double x, double y);\n'
'#endif\n'
)
def test_complicated_codegen():
from sympy import sin, cos, tan
x, y, z = symbols('x,y,z')
name_expr = [
("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test1(double x, double y, double z) {\n'
' double test1_result;\n'
' test1_result = '
'pow(sin(x), 7) + '
'7*pow(sin(x), 6)*cos(y) + '
'7*pow(sin(x), 6)*tan(z) + '
'21*pow(sin(x), 5)*pow(cos(y), 2) + '
'42*pow(sin(x), 5)*cos(y)*tan(z) + '
'21*pow(sin(x), 5)*pow(tan(z), 2) + '
'35*pow(sin(x), 4)*pow(cos(y), 3) + '
'105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + '
'105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + '
'35*pow(sin(x), 4)*pow(tan(z), 3) + '
'35*pow(sin(x), 3)*pow(cos(y), 4) + '
'140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + '
'210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + '
'140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + '
'35*pow(sin(x), 3)*pow(tan(z), 4) + '
'21*pow(sin(x), 2)*pow(cos(y), 5) + '
'105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + '
'210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + '
'210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + '
'105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + '
'21*pow(sin(x), 2)*pow(tan(z), 5) + '
'7*sin(x)*pow(cos(y), 6) + '
'42*sin(x)*pow(cos(y), 5)*tan(z) + '
'105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + '
'140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + '
'105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + '
'42*sin(x)*cos(y)*pow(tan(z), 5) + '
'7*sin(x)*pow(tan(z), 6) + '
'pow(cos(y), 7) + '
'7*pow(cos(y), 6)*tan(z) + '
'21*pow(cos(y), 5)*pow(tan(z), 2) + '
'35*pow(cos(y), 4)*pow(tan(z), 3) + '
'35*pow(cos(y), 3)*pow(tan(z), 4) + '
'21*pow(cos(y), 2)*pow(tan(z), 5) + '
'7*cos(y)*pow(tan(z), 6) + '
'pow(tan(z), 7);\n'
' return test1_result;\n'
'}\n'
'double test2(double x, double y, double z) {\n'
' double test2_result;\n'
' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n'
' return test2_result;\n'
'}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'double test1(double x, double y, double z);\n'
'double test2(double x, double y, double z);\n'
'#endif\n'
)
def test_loops_c():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False)
assert f1 == 'file.c'
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n'
' for (int i=0; i<m; i++){\n'
' y[i] = 0;\n'
' }\n'
' for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = %(rhs)s + y[i];\n'
' }\n'
' }\n'
'}\n'
)
assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*n + j)} or
code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*n)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (i*n + j)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*n)})
assert f2 == 'file.h'
assert interface == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'void matrix_vector(double *A, int m, int n, double *x, double *y);\n'
'#endif\n'
)
def test_dummy_loops_c():
from sympy.tensor import IndexedBase, Idx
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void test_dummies(int m_%(mno)i, double *x, double *y) {\n'
' for (int i_%(ino)i=0; i_%(ino)i<m_%(mno)i; i_%(ino)i++){\n'
' y[i_%(ino)i] = x[i_%(ino)i];\n'
' }\n'
'}\n'
) % {'ino': i.label.dummy_index, 'mno': m.dummy_index}
r = make_routine('test_dummies', Eq(y[i], x[i]))
c89 = C89CodeGen()
c99 = C99CodeGen()
code = get_string(c99.dump_c, [r])
assert code == expected
with raises(NotImplementedError):
get_string(c89.dump_c, [r])
def test_partial_loops_c():
# check that loop boundaries are determined by Idx, and array strides
# determined by shape of IndexedBase object.
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A', shape=(m, p))
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', (o, m - 5)) # Note: bounds are inclusive
j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False)
assert f1 == 'file.c'
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n'
' for (int i=o; i<%(upperi)s; i++){\n'
' y[i] = 0;\n'
' }\n'
' for (int i=o; i<%(upperi)s; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = %(rhs)s + y[i];\n'
' }\n'
' }\n'
'}\n'
) % {'upperi': m - 4, 'rhs': '%(rhs)s'}
assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*p + j)} or
code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*p)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (i*p + j)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*p)})
assert f2 == 'file.h'
assert interface == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y);\n'
'#endif\n'
)
def test_output_arg_c():
from sympy import sin, cos, Equality
x, y, z = symbols("x,y,z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = C89CodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.c"
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double foo(double x, double *y) {\n'
' (*y) = sin(x);\n'
' double foo_result;\n'
' foo_result = cos(x);\n'
' return foo_result;\n'
'}\n'
)
assert result[0][1] == expected
def test_output_arg_c_reserved_words():
from sympy import sin, cos, Equality
x, y, z = symbols("if, while, z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = C89CodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.c"
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double foo(double if_, double *while_) {\n'
' (*while_) = sin(if_);\n'
' double foo_result;\n'
' foo_result = cos(if_);\n'
' return foo_result;\n'
'}\n'
)
assert result[0][1] == expected
def test_ccode_results_named_ordered():
x, y, z = symbols('x,y,z')
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(A, Matrix([[1, 2, x]]))
expr2 = Equality(C, (x + y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double x, double *C, double z, double y, double *A, double *B) {\n'
' (*C) = z*(x + y);\n'
' A[0] = 1;\n'
' A[1] = 2;\n'
' A[2] = x;\n'
' (*B) = 2*x;\n'
'}\n'
)
result = codegen(name_expr, "c", "test", header=False, empty=False,
argument_sequence=(x, C, z, y, A, B))
source = result[0][1]
assert source == expected
def test_ccode_matrixsymbol_slice():
A = MatrixSymbol('A', 5, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 5, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result = codegen(name_expr, "c99", "test", header=False, empty=False)
source = result[0][1]
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double *A, double *B, double *C, double *D) {\n'
' B[0] = A[0];\n'
' B[1] = A[1];\n'
' B[2] = A[2];\n'
' C[0] = A[3];\n'
' C[1] = A[4];\n'
' C[2] = A[5];\n'
' D[0] = A[2];\n'
' D[1] = A[5];\n'
' D[2] = A[8];\n'
' D[3] = A[11];\n'
' D[4] = A[14];\n'
'}\n'
)
assert source == expected
def test_ccode_cse():
a, b, c, d = symbols('a b c d')
e = MatrixSymbol('e', 3, 1)
name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))])
generator = CCodeGen(cse=True)
result = codegen(name_expr, code_gen=generator, header=False, empty=False)
source = result[0][1]
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double a, double b, double c, double d, double *e) {\n'
' const double x0 = a*b;\n'
' const double x1 = c*d;\n'
' e[0] = x0;\n'
' e[1] = x0 + x1;\n'
' e[2] = x0*x1;\n'
'}\n'
)
assert source == expected
def test_ccode_unused_array_arg():
x = MatrixSymbol('x', 2, 1)
# x does not appear in output
name_expr = ("test", 1.0)
generator = CCodeGen()
result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,))
source = result[0][1]
# note: x should appear as (double *)
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double test(double *x) {\n'
' double test_result;\n'
' test_result = 1.0;\n'
' return test_result;\n'
'}\n'
)
assert source == expected
def test_empty_f_code():
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [])
assert source == ""
def test_empty_f_code_with_header():
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [], header=True)
assert source[:82] == (
"!******************************************************************************\n!*"
)
# " Code generated with sympy 0.7.2-git "
assert source[158:] == ( "*\n"
"!* *\n"
"!* See http://www.sympy.org/ for more information. *\n"
"!* *\n"
"!* This file is part of 'project' *\n"
"!******************************************************************************\n"
)
def test_empty_f_header():
code_gen = FCodeGen()
source = get_string(code_gen.dump_h, [])
assert source == ""
def test_simple_f_code():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"test = z*(x + y)\n"
"end function\n"
)
assert source == expected
def test_numbersymbol_f_code():
routine = make_routine("test", pi**Catalan)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test()\n"
"implicit none\n"
"REAL*8, parameter :: Catalan = %sd0\n"
"REAL*8, parameter :: pi = %sd0\n"
"test = pi**Catalan\n"
"end function\n"
) % (Catalan.evalf(17), pi.evalf(17))
assert source == expected
def test_erf_f_code():
x = symbols('x')
routine = make_routine("test", erf(x) - erf(-2 * x))
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(x)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"test = erf(x) + erf(2.0d0*x)\n"
"end function\n"
)
assert source == expected, source
def test_f_code_argument_order():
x, y, z = symbols('x,y,z')
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y])
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(z, x, y)\n"
"implicit none\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n"
)
assert source == expected
def test_simple_f_header():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_h, [routine])
expected = (
"interface\n"
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"end function\n"
"end interface\n"
)
assert source == expected
def test_simple_f_codegen():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
result = codegen(
("test", expr), "F95", "file", header=False, empty=False)
expected = [
("file.f90",
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"test = z*(x + y)\n"
"end function\n"),
("file.h",
"interface\n"
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"end function\n"
"end interface\n")
]
assert result == expected
def test_multiple_results_f():
x, y, z = symbols('x,y,z')
expr1 = (x + y)*z
expr2 = (x - y)*z
routine = make_routine(
"test",
[expr1, expr2]
)
code_gen = FCodeGen()
raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
def test_no_results_f():
raises(ValueError, lambda: make_routine("test", []))
def test_intrinsic_math_codegen():
# not included: log10
from sympy import (acos, asin, atan, cos, cosh, log, ln, sin, sinh, sqrt,
tan, tanh, Abs)
x = symbols('x')
name_expr = [
("test_abs", Abs(x)),
("test_acos", acos(x)),
("test_asin", asin(x)),
("test_atan", atan(x)),
("test_cos", cos(x)),
("test_cosh", cosh(x)),
("test_log", log(x)),
("test_ln", ln(x)),
("test_sin", sin(x)),
("test_sinh", sinh(x)),
("test_sqrt", sqrt(x)),
("test_tan", tan(x)),
("test_tanh", tanh(x)),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test_abs(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_abs = abs(x)\n'
'end function\n'
'REAL*8 function test_acos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_acos = acos(x)\n'
'end function\n'
'REAL*8 function test_asin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_asin = asin(x)\n'
'end function\n'
'REAL*8 function test_atan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_atan = atan(x)\n'
'end function\n'
'REAL*8 function test_cos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_cos = cos(x)\n'
'end function\n'
'REAL*8 function test_cosh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_cosh = cosh(x)\n'
'end function\n'
'REAL*8 function test_log(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_log = log(x)\n'
'end function\n'
'REAL*8 function test_ln(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_ln = log(x)\n'
'end function\n'
'REAL*8 function test_sin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sin = sin(x)\n'
'end function\n'
'REAL*8 function test_sinh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sinh = sinh(x)\n'
'end function\n'
'REAL*8 function test_sqrt(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sqrt = sqrt(x)\n'
'end function\n'
'REAL*8 function test_tan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_tan = tan(x)\n'
'end function\n'
'REAL*8 function test_tanh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_tanh = tanh(x)\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test_abs(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_acos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_asin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_atan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_cos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_cosh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_log(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_ln(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sinh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sqrt(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_tan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_tanh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_intrinsic_math2_codegen():
# not included: frexp, ldexp, modf, fmod
from sympy import atan2
x, y = symbols('x,y')
name_expr = [
("test_atan2", atan2(x, y)),
("test_pow", x**y),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test_atan2(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'test_atan2 = atan2(x, y)\n'
'end function\n'
'REAL*8 function test_pow(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'test_pow = x**y\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test_atan2(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_pow(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_complicated_codegen_f95():
from sympy import sin, cos, tan
x, y, z = symbols('x,y,z')
name_expr = [
("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test1(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n'
' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n'
' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n'
' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n'
' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n'
' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n'
' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n'
' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n'
' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n'
' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n'
' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n'
' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n'
' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n'
' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n'
' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n'
'end function\n'
'REAL*8 function test2(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test1(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test2(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_loops():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n,m', integer=True)
A, x, y = map(IndexedBase, 'Axy')
i = Idx('i', m)
j = Idx('j', n)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
assert f1 == 'file.f90'
expected = (
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = 1, m\n'
' y(i) = 0\n'
'end do\n'
'do i = 1, m\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
)
assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
code == expected % {'rhs': 'x(j)*A(i, j)'}
assert f2 == 'file.h'
assert interface == (
'interface\n'
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'end subroutine\n'
'end interface\n'
)
def test_dummy_loops_f95():
from sympy.tensor import IndexedBase, Idx
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'subroutine test_dummies(m_%(mcount)i, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m_%(mcount)i\n'
'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n'
'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n'
'INTEGER*4 :: i_%(icount)i\n'
'do i_%(icount)i = 1, m_%(mcount)i\n'
' y(i_%(icount)i) = x(i_%(icount)i)\n'
'end do\n'
'end subroutine\n'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
r = make_routine('test_dummies', Eq(y[i], x[i]))
c = FCodeGen()
code = get_string(c.dump_f95, [r])
assert code == expected
def test_loops_InOut():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
i, j, n, m = symbols('i,j,n,m', integer=True)
A, x, y = symbols('A,x,y')
A = IndexedBase(A)[Idx(i, m), Idx(j, n)]
x = IndexedBase(x)[Idx(j, n)]
y = IndexedBase(y)[Idx(i, m)]
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False)
assert f1 == 'file.f90'
expected = (
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(inout), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = 1, m\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
)
assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or
code == expected % {'rhs': 'x(j)*A(i, j)'})
assert f2 == 'file.h'
assert interface == (
'interface\n'
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(inout), dimension(1:m) :: y\n'
'end subroutine\n'
'end interface\n'
)
def test_partial_loops_f():
# check that loop boundaries are determined by Idx, and array strides
# determined by shape of IndexedBase object.
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A', shape=(m, p))
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', (o, m - 5)) # Note: bounds are inclusive
j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
expected = (
'subroutine matrix_vector(A, m, n, o, p, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'INTEGER*4, intent(in) :: o\n'
'INTEGER*4, intent(in) :: p\n'
'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = %(ilow)s, %(iup)s\n'
' y(i) = 0\n'
'end do\n'
'do i = %(ilow)s, %(iup)s\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
) % {
'rhs': '%(rhs)s',
'iup': str(m - 4),
'ilow': str(1 + o),
'iup-ilow': str(m - 4 - o)
}
assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
code == expected % {'rhs': 'x(j)*A(i, j)'}
def test_output_arg_f():
from sympy import sin, cos, Equality
x, y, z = symbols("x,y,z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = FCodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.f90"
assert result[0][1] == (
'REAL*8 function foo(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(out) :: y\n'
'y = sin(x)\n'
'foo = cos(x)\n'
'end function\n'
)
def test_inline_function():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A, x, y = map(IndexedBase, 'Axy')
i = Idx('i', m)
p = FCodeGen()
func = implemented_function('func', Lambda(n, n*(n + 1)))
routine = make_routine('test_inline', Eq(y[i], func(x[i])))
code = get_string(p.dump_f95, [routine])
expected = (
'subroutine test_inline(m, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'REAL*8, intent(in), dimension(1:m) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'do i = 1, m\n'
' y(i) = %s*%s\n'
'end do\n'
'end subroutine\n'
)
args = ('x(i)', '(x(i) + 1)')
assert code == expected % args or\
code == expected % args[::-1]
def test_f_code_call_signature_wrap():
# Issue #7934
x = symbols('x:20')
expr = 0
for sym in x:
expr += sym
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = """\
REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, &
x19, x2, x3, x4, x5, x6, x7, x8, x9)
implicit none
REAL*8, intent(in) :: x0
REAL*8, intent(in) :: x1
REAL*8, intent(in) :: x10
REAL*8, intent(in) :: x11
REAL*8, intent(in) :: x12
REAL*8, intent(in) :: x13
REAL*8, intent(in) :: x14
REAL*8, intent(in) :: x15
REAL*8, intent(in) :: x16
REAL*8, intent(in) :: x17
REAL*8, intent(in) :: x18
REAL*8, intent(in) :: x19
REAL*8, intent(in) :: x2
REAL*8, intent(in) :: x3
REAL*8, intent(in) :: x4
REAL*8, intent(in) :: x5
REAL*8, intent(in) :: x6
REAL*8, intent(in) :: x7
REAL*8, intent(in) :: x8
REAL*8, intent(in) :: x9
test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + &
x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
end function
"""
assert source == expected
def test_check_case():
x, X = symbols('x,X')
raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix'))
def test_check_case_false_positive():
# The upper case/lower case exception should not be triggered by SymPy
# objects that differ only because of assumptions. (It may be useful to
# have a check for that as well, but here we only want to test against
# false positives with respect to case checking.)
x1 = symbols('x')
x2 = symbols('x', my_assumption=True)
try:
codegen(('test', x1*x2), 'f95', 'prefix')
except CodeGenError as e:
if e.args[0].startswith("Fortran ignores case."):
raise AssertionError("This exception should not be raised!")
def test_c_fortran_omit_routine_name():
x, y = symbols("x,y")
name_expr = [("foo", 2*x)]
result = codegen(name_expr, "F95", header=False, empty=False)
expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
name_expr = ("foo", x*y)
result = codegen(name_expr, "F95", header=False, empty=False)
expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
name_expr = ("foo", Matrix([[x, y], [x+y, x-y]]))
result = codegen(name_expr, "C89", header=False, empty=False)
expresult = codegen(name_expr, "C89", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
def test_fcode_matrix_output():
x, y, z = symbols('x,y,z')
e1 = x + y
e2 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2))
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"REAL*8 function test(x, y, z, out_%(hash)s)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n"
"out_%(hash)s(1, 1) = x\n"
"out_%(hash)s(2, 1) = z\n"
"out_%(hash)s(1, 2) = y\n"
"out_%(hash)s(2, 2) = 16\n"
"test = x + y\n"
"end function\n"
)
# look for the magic number
a = source.splitlines()[5]
b = a.split('_')
out = b[1]
expected = expected % {'hash': out}
assert source == expected
def test_fcode_results_named_ordered():
x, y, z = symbols('x,y,z')
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(A, Matrix([[1, 2, x]]))
expr2 = Equality(C, (x + y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "f95", "test", header=False, empty=False,
argument_sequence=(x, z, y, C, A, B))
source = result[0][1]
expected = (
"subroutine test(x, z, y, C, A, B)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(out) :: C\n"
"REAL*8, intent(out) :: B\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: A\n"
"C = z*(x + y)\n"
"A(1, 1) = 1\n"
"A(1, 2) = 2\n"
"A(1, 3) = x\n"
"B = 2*x\n"
"end subroutine\n"
)
assert source == expected
def test_fcode_matrixsymbol_slice():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 2, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"subroutine test(A, B, C, D)\n"
"implicit none\n"
"REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: B\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: C\n"
"REAL*8, intent(out), dimension(1:2, 1:1) :: D\n"
"B(1, 1) = A(1, 1)\n"
"B(1, 2) = A(1, 2)\n"
"B(1, 3) = A(1, 3)\n"
"C(1, 1) = A(2, 1)\n"
"C(1, 2) = A(2, 2)\n"
"C(1, 3) = A(2, 3)\n"
"D(1, 1) = A(1, 3)\n"
"D(2, 1) = A(2, 3)\n"
"end subroutine\n"
)
assert source == expected
def test_fcode_matrixsymbol_slice_autoname():
# see issue #8093
A = MatrixSymbol('A', 2, 3)
name_expr = ("test", A[:, 1])
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"subroutine test(A, out_%(hash)s)\n"
"implicit none\n"
"REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
"REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n"
"out_%(hash)s(1, 1) = A(1, 2)\n"
"out_%(hash)s(2, 1) = A(2, 2)\n"
"end subroutine\n"
)
# look for the magic number
a = source.splitlines()[3]
b = a.split('_')
out = b[1]
expected = expected % {'hash': out}
assert source == expected
def test_global_vars():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "F95", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"REAL*8 function f(x)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"f = x*y\n"
"end function\n"
)
assert source == expected
expected = (
'#include "f.h"\n'
'#include <math.h>\n'
'double f(double x, double y) {\n'
' double f_result;\n'
' f_result = x*y + z;\n'
' return f_result;\n'
'}\n'
)
result = codegen(('f', x*y+z), "C", header=False, empty=False,
global_vars=(z, t))
source = result[0][1]
assert source == expected
def test_custom_codegen():
from sympy.printing.c import C99CodePrinter
from sympy.functions.elementary.exponential import exp
printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}})
x, y = symbols('x y')
expr = exp(x + y)
# replace math.h with a different header
gen = C99CodeGen(printer=printer,
preprocessor_statements=['#include "fastexp.h"'])
expected = (
'#include "expr.h"\n'
'#include "fastexp.h"\n'
'double expr(double x, double y) {\n'
' double expr_result;\n'
' expr_result = fastexp(x + y);\n'
' return expr_result;\n'
'}\n'
)
result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
source = result[0][1]
assert source == expected
# use both math.h and an external header
gen = C99CodeGen(printer=printer)
gen.preprocessor_statements.append('#include "fastexp.h"')
expected = (
'#include "expr.h"\n'
'#include <math.h>\n'
'#include "fastexp.h"\n'
'double expr(double x, double y) {\n'
' double expr_result;\n'
' expr_result = fastexp(x + y);\n'
' return expr_result;\n'
'}\n'
)
result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
source = result[0][1]
assert source == expected
def test_c_with_printer():
#issue 13586
from sympy.printing.c import C99CodePrinter
class CustomPrinter(C99CodePrinter):
def _print_Pow(self, expr):
return "fastpow({}, {})".format(self._print(expr.base),
self._print(expr.exp))
x = symbols('x')
expr = x**3
expected =[
("file.c",
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x) {\n"
" double test_result;\n"
" test_result = fastpow(x, 3);\n"
" return test_result;\n"
"}\n"),
("file.h",
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x);\n"
"#endif\n")
]
result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter())
assert result == expected
def test_fcode_complex():
import sympy.utilities.codegen
sympy.utilities.codegen.COMPLEX_ALLOWED = True
x = Symbol('x', real=True)
y = Symbol('y',real=True)
result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
source = (result[0][1])
expected = (
"REAL*8 function test(x, y)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n")
assert source == expected
x = Symbol('x')
y = Symbol('y',real=True)
result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
source = (result[0][1])
expected = (
"COMPLEX*16 function test(x, y)\n"
"implicit none\n"
"COMPLEX*16, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n"
)
assert source==expected
sympy.utilities.codegen.COMPLEX_ALLOWED = False
|
3b89436a7710e57205d2d1eb48403115b85e9dba792d6a1b2d4bbe399c2feda9 | """Symbolic primitives + unicode/ASCII abstraction for pretty.py"""
import sys
import warnings
from string import ascii_lowercase, ascii_uppercase
import unicodedata
unicode_warnings = ''
def U(name):
"""
Get a unicode character by name or, None if not found.
This exists because older versions of python use older unicode databases.
"""
try:
return unicodedata.lookup(name)
except KeyError:
global unicode_warnings
unicode_warnings += 'No \'%s\' in unicodedata\n' % name
return None
from sympy.printing.conventions import split_super_sub
from sympy.core.alphabets import greeks
from sympy.utilities.exceptions import SymPyDeprecationWarning
# prefix conventions when constructing tables
# L - LATIN i
# G - GREEK beta
# D - DIGIT 0
# S - SYMBOL +
__all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol',
'annotated']
_use_unicode = False
def pretty_use_unicode(flag=None):
"""Set whether pretty-printer should use unicode by default"""
global _use_unicode
global unicode_warnings
if flag is None:
return _use_unicode
if flag and unicode_warnings:
# print warnings (if any) on first unicode usage
warnings.warn(unicode_warnings)
unicode_warnings = ''
use_unicode_prev = _use_unicode
_use_unicode = flag
return use_unicode_prev
def pretty_try_use_unicode():
"""See if unicode output is available and leverage it if possible"""
encoding = getattr(sys.stdout, 'encoding', None)
# this happens when e.g. stdout is redirected through a pipe, or is
# e.g. a cStringIO.StringO
if encoding is None:
return # sys.stdout has no encoding
symbols = []
# see if we can represent greek alphabet
symbols += greek_unicode.values()
# and atoms
symbols += atoms_table.values()
for s in symbols:
if s is None:
return # common symbols not present!
try:
s.encode(encoding)
except UnicodeEncodeError:
return
# all the characters were present and encodable
pretty_use_unicode(True)
def xstr(*args):
SymPyDeprecationWarning(
feature="``xstr`` function",
useinstead="``str``",
deprecated_since_version="1.7").warn()
return str(*args)
# GREEK
g = lambda l: U('GREEK SMALL LETTER %s' % l.upper())
G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper())
greek_letters = list(greeks) # make a copy
# deal with Unicode's funny spelling of lambda
greek_letters[greek_letters.index('lambda')] = 'lamda'
# {} greek letter -> (g,G)
greek_unicode = {L: g(L) for L in greek_letters}
greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters)
# aliases
greek_unicode['lambda'] = greek_unicode['lamda']
greek_unicode['Lambda'] = greek_unicode['Lamda']
greek_unicode['varsigma'] = '\N{GREEK SMALL LETTER FINAL SIGMA}'
# BOLD
b = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
B = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
bold_unicode = {l: b(l) for l in ascii_lowercase}
bold_unicode.update((L, B(L)) for L in ascii_uppercase)
# GREEK BOLD
gb = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
GB = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
greek_bold_letters = list(greeks) # make a copy, not strictly required here
# deal with Unicode's funny spelling of lambda
greek_bold_letters[greek_bold_letters.index('lambda')] = 'lamda'
# {} greek letter -> (g,G)
greek_bold_unicode = {L: g(L) for L in greek_bold_letters}
greek_bold_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_bold_letters)
greek_bold_unicode['lambda'] = greek_unicode['lamda']
greek_bold_unicode['Lambda'] = greek_unicode['Lamda']
greek_bold_unicode['varsigma'] = '\N{MATHEMATICAL BOLD SMALL FINAL SIGMA}'
digit_2txt = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE',
}
symb_2txt = {
'+': 'PLUS SIGN',
'-': 'MINUS',
'=': 'EQUALS SIGN',
'(': 'LEFT PARENTHESIS',
')': 'RIGHT PARENTHESIS',
'[': 'LEFT SQUARE BRACKET',
']': 'RIGHT SQUARE BRACKET',
'{': 'LEFT CURLY BRACKET',
'}': 'RIGHT CURLY BRACKET',
# non-std
'{}': 'CURLY BRACKET',
'sum': 'SUMMATION',
'int': 'INTEGRAL',
}
# SUBSCRIPT & SUPERSCRIPT
LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper())
GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper())
DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit])
SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb])
LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper())
DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit])
SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb])
sub = {} # symb -> subscript symbol
sup = {} # symb -> superscript symbol
# latin subscripts
for l in 'aeioruvxhklmnpst':
sub[l] = LSUB(l)
for l in 'in':
sup[l] = LSUP(l)
for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']:
sub[gl] = GSUB(gl)
for d in [str(i) for i in range(10)]:
sub[d] = DSUB(d)
sup[d] = DSUP(d)
for s in '+-=()':
sub[s] = SSUB(s)
sup[s] = SSUP(s)
# Variable modifiers
# TODO: Make brackets adjust to height of contents
modifier_dict = {
# Accents
'mathring': lambda s: center_accent(s, '\N{COMBINING RING ABOVE}'),
'ddddot': lambda s: center_accent(s, '\N{COMBINING FOUR DOTS ABOVE}'),
'dddot': lambda s: center_accent(s, '\N{COMBINING THREE DOTS ABOVE}'),
'ddot': lambda s: center_accent(s, '\N{COMBINING DIAERESIS}'),
'dot': lambda s: center_accent(s, '\N{COMBINING DOT ABOVE}'),
'check': lambda s: center_accent(s, '\N{COMBINING CARON}'),
'breve': lambda s: center_accent(s, '\N{COMBINING BREVE}'),
'acute': lambda s: center_accent(s, '\N{COMBINING ACUTE ACCENT}'),
'grave': lambda s: center_accent(s, '\N{COMBINING GRAVE ACCENT}'),
'tilde': lambda s: center_accent(s, '\N{COMBINING TILDE}'),
'hat': lambda s: center_accent(s, '\N{COMBINING CIRCUMFLEX ACCENT}'),
'bar': lambda s: center_accent(s, '\N{COMBINING OVERLINE}'),
'vec': lambda s: center_accent(s, '\N{COMBINING RIGHT ARROW ABOVE}'),
'prime': lambda s: s+'\N{PRIME}',
'prm': lambda s: s+'\N{PRIME}',
# # Faces -- these are here for some compatibility with latex printing
# 'bold': lambda s: s,
# 'bm': lambda s: s,
# 'cal': lambda s: s,
# 'scr': lambda s: s,
# 'frak': lambda s: s,
# Brackets
'norm': lambda s: '\N{DOUBLE VERTICAL LINE}'+s+'\N{DOUBLE VERTICAL LINE}',
'avg': lambda s: '\N{MATHEMATICAL LEFT ANGLE BRACKET}'+s+'\N{MATHEMATICAL RIGHT ANGLE BRACKET}',
'abs': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
'mag': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
}
# VERTICAL OBJECTS
HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb])
CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb])
MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb])
EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb])
HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb])
CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb])
TOP = lambda symb: U('%s TOP' % symb_2txt[symb])
BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb])
# {} '(' -> (extension, start, end, middle) 1-character
_xobj_unicode = {
# vertical symbols
# (( ext, top, bot, mid ), c1)
'(': (( EXT('('), HUP('('), HLO('(') ), '('),
')': (( EXT(')'), HUP(')'), HLO(')') ), ')'),
'[': (( EXT('['), CUP('['), CLO('[') ), '['),
']': (( EXT(']'), CUP(']'), CLO(']') ), ']'),
'{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'),
'}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'),
'|': U('BOX DRAWINGS LIGHT VERTICAL'),
'<': ((U('BOX DRAWINGS LIGHT VERTICAL'),
U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'),
'>': ((U('BOX DRAWINGS LIGHT VERTICAL'),
U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'),
'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')),
'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')),
'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')),
'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')),
'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')),
'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')),
# horizontal objects
#'-': '-',
'-': U('BOX DRAWINGS LIGHT HORIZONTAL'),
'_': U('LOW LINE'),
# We used to use this, but LOW LINE looks better for roots, as it's a
# little lower (i.e., it lines up with the / perfectly. But perhaps this
# one would still be wanted for some cases?
# '_': U('HORIZONTAL SCAN LINE-9'),
# diagonal objects '\' & '/' ?
'/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
'\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
}
_xobj_ascii = {
# vertical symbols
# (( ext, top, bot, mid ), c1)
'(': (( '|', '/', '\\' ), '('),
')': (( '|', '\\', '/' ), ')'),
# XXX this looks ugly
# '[': (( '|', '-', '-' ), '['),
# ']': (( '|', '-', '-' ), ']'),
# XXX not so ugly :(
'[': (( '[', '[', '[' ), '['),
']': (( ']', ']', ']' ), ']'),
'{': (( '|', '/', '\\', '<' ), '{'),
'}': (( '|', '\\', '/', '>' ), '}'),
'|': '|',
'<': (( '|', '/', '\\' ), '<'),
'>': (( '|', '\\', '/' ), '>'),
'int': ( ' | ', ' /', '/ ' ),
# horizontal objects
'-': '-',
'_': '_',
# diagonal objects '\' & '/' ?
'/': '/',
'\\': '\\',
}
def xobj(symb, length):
"""Construct spatial object of given length.
return: [] of equal-length strings
"""
if length <= 0:
raise ValueError("Length should be greater than 0")
# TODO robustify when no unicodedat available
if _use_unicode:
_xobj = _xobj_unicode
else:
_xobj = _xobj_ascii
vinfo = _xobj[symb]
c1 = top = bot = mid = None
if not isinstance(vinfo, tuple): # 1 entry
ext = vinfo
else:
if isinstance(vinfo[0], tuple): # (vlong), c1
vlong = vinfo[0]
c1 = vinfo[1]
else: # (vlong), c1
vlong = vinfo
ext = vlong[0]
try:
top = vlong[1]
bot = vlong[2]
mid = vlong[3]
except IndexError:
pass
if c1 is None:
c1 = ext
if top is None:
top = ext
if bot is None:
bot = ext
if mid is not None:
if (length % 2) == 0:
# even height, but we have to print it somehow anyway...
# XXX is it ok?
length += 1
else:
mid = ext
if length == 1:
return c1
res = []
next = (length - 2)//2
nmid = (length - 2) - next*2
res += [top]
res += [ext]*next
res += [mid]*nmid
res += [ext]*next
res += [bot]
return res
def vobj(symb, height):
"""Construct vertical object of a given height
see: xobj
"""
return '\n'.join( xobj(symb, height) )
def hobj(symb, width):
"""Construct horizontal object of a given width
see: xobj
"""
return ''.join( xobj(symb, width) )
# RADICAL
# n -> symbol
root = {
2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM')
3: U('CUBE ROOT'),
4: U('FOURTH ROOT'),
}
# RATIONAL
VF = lambda txt: U('VULGAR FRACTION %s' % txt)
# (p,q) -> symbol
frac = {
(1, 2): VF('ONE HALF'),
(1, 3): VF('ONE THIRD'),
(2, 3): VF('TWO THIRDS'),
(1, 4): VF('ONE QUARTER'),
(3, 4): VF('THREE QUARTERS'),
(1, 5): VF('ONE FIFTH'),
(2, 5): VF('TWO FIFTHS'),
(3, 5): VF('THREE FIFTHS'),
(4, 5): VF('FOUR FIFTHS'),
(1, 6): VF('ONE SIXTH'),
(5, 6): VF('FIVE SIXTHS'),
(1, 8): VF('ONE EIGHTH'),
(3, 8): VF('THREE EIGHTHS'),
(5, 8): VF('FIVE EIGHTHS'),
(7, 8): VF('SEVEN EIGHTHS'),
}
# atom symbols
_xsym = {
'==': ('=', '='),
'<': ('<', '<'),
'>': ('>', '>'),
'<=': ('<=', U('LESS-THAN OR EQUAL TO')),
'>=': ('>=', U('GREATER-THAN OR EQUAL TO')),
'!=': ('!=', U('NOT EQUAL TO')),
':=': (':=', ':='),
'+=': ('+=', '+='),
'-=': ('-=', '-='),
'*=': ('*=', '*='),
'/=': ('/=', '/='),
'%=': ('%=', '%='),
'*': ('*', U('DOT OPERATOR')),
'-->': ('-->', U('EM DASH') + U('EM DASH') +
U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH')
and U('BLACK RIGHT-POINTING TRIANGLE') else None),
'==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') +
U('BOX DRAWINGS DOUBLE HORIZONTAL') +
U('BLACK RIGHT-POINTING TRIANGLE') if
U('BOX DRAWINGS DOUBLE HORIZONTAL') and
U('BOX DRAWINGS DOUBLE HORIZONTAL') and
U('BLACK RIGHT-POINTING TRIANGLE') else None),
'.': ('*', U('RING OPERATOR')),
}
def xsym(sym):
"""get symbology for a 'character'"""
op = _xsym[sym]
if _use_unicode:
return op[1]
else:
return op[0]
# SYMBOLS
atoms_table = {
# class how-to-display
'Exp1': U('SCRIPT SMALL E'),
'Pi': U('GREEK SMALL LETTER PI'),
'Infinity': U('INFINITY'),
'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here
#'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'),
#'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'),
'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'),
'EmptySet': U('EMPTY SET'),
'Naturals': U('DOUBLE-STRUCK CAPITAL N'),
'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and
(U('DOUBLE-STRUCK CAPITAL N') +
U('SUBSCRIPT ZERO'))),
'Integers': U('DOUBLE-STRUCK CAPITAL Z'),
'Rationals': U('DOUBLE-STRUCK CAPITAL Q'),
'Reals': U('DOUBLE-STRUCK CAPITAL R'),
'Complexes': U('DOUBLE-STRUCK CAPITAL C'),
'Union': U('UNION'),
'SymmetricDifference': U('INCREMENT'),
'Intersection': U('INTERSECTION'),
'Ring': U('RING OPERATOR'),
'Modifier Letter Low Ring':U('Modifier Letter Low Ring'),
'EmptySequence': 'EmptySequence',
}
def pretty_atom(atom_name, default=None, printer=None):
"""return pretty representation of an atom"""
if _use_unicode:
if printer is not None and atom_name == 'ImaginaryUnit' and printer._settings['imaginary_unit'] == 'j':
return U('DOUBLE-STRUCK ITALIC SMALL J')
else:
return atoms_table[atom_name]
else:
if default is not None:
return default
raise KeyError('only unicode') # send it default printer
def pretty_symbol(symb_name, bold_name=False):
"""return pretty representation of a symbol"""
# let's split symb_name into symbol + index
# UC: beta1
# UC: f_beta
if not _use_unicode:
return symb_name
name, sups, subs = split_super_sub(symb_name)
def translate(s, bold_name) :
if bold_name:
gG = greek_bold_unicode.get(s)
else:
gG = greek_unicode.get(s)
if gG is not None:
return gG
for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) :
if s.lower().endswith(key) and len(s)>len(key):
return modifier_dict[key](translate(s[:-len(key)], bold_name))
if bold_name:
return ''.join([bold_unicode[c] for c in s])
return s
name = translate(name, bold_name)
# Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
# not used at all.
def pretty_list(l, mapping):
result = []
for s in l:
pretty = mapping.get(s)
if pretty is None:
try: # match by separate characters
pretty = ''.join([mapping[c] for c in s])
except (TypeError, KeyError):
return None
result.append(pretty)
return result
pretty_sups = pretty_list(sups, sup)
if pretty_sups is not None:
pretty_subs = pretty_list(subs, sub)
else:
pretty_subs = None
# glue the results into one string
if pretty_subs is None: # nice formatting of sups/subs did not work
if subs:
name += '_'+'_'.join([translate(s, bold_name) for s in subs])
if sups:
name += '__'+'__'.join([translate(s, bold_name) for s in sups])
return name
else:
sups_result = ' '.join(pretty_sups)
subs_result = ' '.join(pretty_subs)
return ''.join([name, sups_result, subs_result])
def annotated(letter):
"""
Return a stylised drawing of the letter ``letter``, together with
information on how to put annotations (super- and subscripts to the
left and to the right) on it.
See pretty.py functions _print_meijerg, _print_hyper on how to use this
information.
"""
ucode_pics = {
'F': (2, 0, 2, 0, '\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
'\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
'\N{BOX DRAWINGS LIGHT UP}'),
'G': (3, 0, 3, 1, '\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n'
'\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n'
'\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}')
}
ascii_pics = {
'F': (3, 0, 3, 0, ' _\n|_\n|\n'),
'G': (3, 0, 3, 1, ' __\n/__\n\\_|')
}
if _use_unicode:
return ucode_pics[letter]
else:
return ascii_pics[letter]
_remove_combining = dict.fromkeys(list(range(ord('\N{COMBINING GRAVE ACCENT}'), ord('\N{COMBINING LATIN SMALL LETTER X}')))
+ list(range(ord('\N{COMBINING LEFT HARPOON ABOVE}'), ord('\N{COMBINING ASTERISK ABOVE}'))))
def is_combining(sym):
"""Check whether symbol is a unicode modifier. """
return ord(sym) in _remove_combining
def center_accent(string, accent):
"""
Returns a string with accent inserted on the middle character. Useful to
put combining accents on symbol names, including multi-character names.
Parameters
==========
string : string
The string to place the accent in.
accent : string
The combining accent to insert
References
==========
.. [1] https://en.wikipedia.org/wiki/Combining_character
.. [2] https://en.wikipedia.org/wiki/Combining_Diacritical_Marks
"""
# Accent is placed on the previous character, although it may not always look
# like that depending on console
midpoint = len(string) // 2 + 1
firstpart = string[:midpoint]
secondpart = string[midpoint:]
return firstpart + accent + secondpart
def line_width(line):
"""Unicode combining symbols (modifiers) are not ever displayed as
separate symbols and thus shouldn't be counted
"""
return len(line.translate(_remove_combining))
|
dc5c84636dac71dc11dc0d47d2b1d6a4f3836ca2b96ef7d9203e35bafe3ce61d | from typing import Any, Dict
from sympy.testing.pytest import raises
from sympy import (symbols, sympify, Function, Integer, Matrix, Abs,
Rational, Float, S, WildFunction, ImmutableDenseMatrix, sin, true, false, ones,
sqrt, root, AlgebraicNumber, Symbol, Dummy, Wild, MatrixSymbol)
from sympy.combinatorics import Cycle, Permutation
from sympy.core.symbol import Str
from sympy.geometry import Point, Ellipse
from sympy.printing import srepr
from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly
from sympy.polys.polyclasses import DMP
from sympy.polys.agca.extensions import FiniteExtension
x, y = symbols('x,y')
# eval(srepr(expr)) == expr has to succeed in the right environment. The right
# environment is the scope of "from sympy import *" for most cases.
ENV = {"Str": Str} # type: Dict[str, Any]
exec("from sympy import *", ENV)
def sT(expr, string, import_stmt=None):
"""
sT := sreprTest
Tests that srepr delivers the expected string and that
the condition eval(srepr(expr))==expr holds.
"""
if import_stmt is None:
ENV2 = ENV
else:
ENV2 = ENV.copy()
exec(import_stmt, ENV2)
assert srepr(expr) == string
assert eval(string, ENV2) == expr
def test_printmethod():
class R(Abs):
def _sympyrepr(self, printer):
return "foo(%s)" % printer._print(self.args[0])
assert srepr(R(x)) == "foo(Symbol('x'))"
def test_Add():
sT(x + y, "Add(Symbol('x'), Symbol('y'))")
assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))"
assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))"
assert srepr(sympify('x + 3 - 2', evaluate=False), order='none') == "Add(Symbol('x'), Integer(3), Mul(Integer(-1), Integer(2)))"
def test_more_than_255_args_issue_10259():
from sympy import Add, Mul
for op in (Add, Mul):
expr = op(*symbols('x:256'))
assert eval(srepr(expr)) == expr
def test_Function():
sT(Function("f")(x), "Function('f')(Symbol('x'))")
# test unapplied Function
sT(Function('f'), "Function('f')")
sT(sin(x), "sin(Symbol('x'))")
sT(sin, "sin")
def test_Geometry():
sT(Point(0, 0), "Point2D(Integer(0), Integer(0))")
sT(Ellipse(Point(0, 0), 5, 1),
"Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))")
# TODO more tests
def test_Singletons():
sT(S.Catalan, 'Catalan')
sT(S.ComplexInfinity, 'zoo')
sT(S.EulerGamma, 'EulerGamma')
sT(S.Exp1, 'E')
sT(S.GoldenRatio, 'GoldenRatio')
sT(S.TribonacciConstant, 'TribonacciConstant')
sT(S.Half, 'Rational(1, 2)')
sT(S.ImaginaryUnit, 'I')
sT(S.Infinity, 'oo')
sT(S.NaN, 'nan')
sT(S.NegativeInfinity, '-oo')
sT(S.NegativeOne, 'Integer(-1)')
sT(S.One, 'Integer(1)')
sT(S.Pi, 'pi')
sT(S.Zero, 'Integer(0)')
def test_Integer():
sT(Integer(4), "Integer(4)")
def test_list():
sT([x, Integer(4)], "[Symbol('x'), Integer(4)]")
def test_Matrix():
for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]:
sT(cls([[x**+1, 1], [y, x + y]]),
"%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
sT(cls(), "%s([])" % name)
sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
def test_empty_Matrix():
sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])")
sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])")
sT(ones(0, 0), "MutableDenseMatrix([])")
def test_Rational():
sT(Rational(1, 3), "Rational(1, 3)")
sT(Rational(-1, 3), "Rational(-1, 3)")
def test_Float():
sT(Float('1.23', dps=3), "Float('1.22998', precision=13)")
sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)")
sT(Float('1.234567890123456789', dps=19),
"Float('1.234567890123456789013', precision=66)")
sT(Float('0.60038617995049726', dps=15),
"Float('0.60038617995049726', precision=53)")
sT(Float('1.23', precision=13), "Float('1.22998', precision=13)")
sT(Float('1.23456789', precision=33),
"Float('1.23456788994', precision=33)")
sT(Float('1.234567890123456789', precision=66),
"Float('1.234567890123456789013', precision=66)")
sT(Float('0.60038617995049726', precision=53),
"Float('0.60038617995049726', precision=53)")
sT(Float('0.60038617995049726', 15),
"Float('0.60038617995049726', precision=53)")
def test_Symbol():
sT(x, "Symbol('x')")
sT(y, "Symbol('y')")
sT(Symbol('x', negative=True), "Symbol('x', negative=True)")
def test_Symbol_two_assumptions():
x = Symbol('x', negative=0, integer=1)
# order could vary
s1 = "Symbol('x', integer=True, negative=False)"
s2 = "Symbol('x', negative=False, integer=True)"
assert srepr(x) in (s1, s2)
assert eval(srepr(x), ENV) == x
def test_Symbol_no_special_commutative_treatment():
sT(Symbol('x'), "Symbol('x')")
sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)")
sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)")
sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)")
sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)")
def test_Wild():
sT(Wild('x', even=True), "Wild('x', even=True)")
def test_Dummy():
d = Dummy('d')
sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index))
def test_Dummy_assumption():
d = Dummy('d', nonzero=True)
assert d == eval(srepr(d))
s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index)
s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index)
assert srepr(d) in (s1, s2)
def test_Dummy_from_Symbol():
# should not get the full dictionary of assumptions
n = Symbol('n', integer=True)
d = n.as_dummy()
assert srepr(d
) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index)
def test_tuple():
sT((x,), "(Symbol('x'),)")
sT((x, y), "(Symbol('x'), Symbol('y'))")
def test_WildFunction():
sT(WildFunction('w'), "WildFunction('w')")
def test_settins():
raises(TypeError, lambda: srepr(x, method="garbage"))
def test_Mul():
sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))")
assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))"
assert srepr(sympify('(x+4)*2*x*7', evaluate=False), order='none') == "Mul(Add(Symbol('x'), Integer(4)), Integer(2), Symbol('x'), Integer(7))"
def test_AlgebraicNumber():
a = AlgebraicNumber(sqrt(2))
sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])")
a = AlgebraicNumber(root(-2, 3))
sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])")
def test_PolyRing():
assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)"
assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)"
assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
def test_FracField():
assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)"
assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)"
assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
def test_PolyElement():
R, x, y = ring("x,y", ZZ)
assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])"
def test_FracElement():
F, x, y = field("x,y", ZZ)
assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])"
def test_FractionField():
assert srepr(QQ.frac_field(x)) == \
"FractionField(FracField((Symbol('x'),), QQ, lex))"
assert srepr(QQ.frac_field(x, y, order=grlex)) == \
"FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))"
def test_PolynomialRingBase():
assert srepr(ZZ.old_poly_ring(x)) == \
"GlobalPolynomialRing(ZZ, Symbol('x'))"
assert srepr(ZZ[x].old_poly_ring(y)) == \
"GlobalPolynomialRing(ZZ[x], Symbol('y'))"
assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \
"GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))"
def test_DMP():
assert srepr(DMP([1, 2], ZZ)) == 'DMP([1, 2], ZZ)'
assert srepr(ZZ.old_poly_ring(x)([1, 2])) == \
"DMP([1, 2], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x')))"
def test_FiniteExtension():
assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \
"FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))"
def test_ExtensionElement():
A = FiniteExtension(Poly(x**2 + 1, x))
assert srepr(A.generator) == \
"ExtElem(DMP([1, 0], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x'))), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))"
def test_BooleanAtom():
assert srepr(true) == "true"
assert srepr(false) == "false"
def test_Integers():
sT(S.Integers, "Integers")
def test_Naturals():
sT(S.Naturals, "Naturals")
def test_Naturals0():
sT(S.Naturals0, "Naturals0")
def test_Reals():
sT(S.Reals, "Reals")
def test_matrix_expressions():
n = symbols('n', integer=True)
A = MatrixSymbol("A", n, n)
B = MatrixSymbol("B", n, n)
sT(A, "MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True))")
sT(A*B, "MatMul(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
sT(A + B, "MatAdd(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
def test_Cycle():
# FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2))
# adds keys to the Cycle dict (GH-17661)
#import_stmt = "from sympy.combinatorics import Cycle"
#sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt)
assert srepr(Cycle(1, 2)) == "Cycle(1, 2)"
def test_Permutation():
import_stmt = "from sympy.combinatorics import Permutation"
sT(Permutation(1, 2), "Permutation(1, 2)", import_stmt)
def test_dict():
from sympy import srepr
from sympy.abc import x, y, z
d = {}
assert srepr(d) == "{}"
d = {x: y}
assert srepr(d) == "{Symbol('x'): Symbol('y')}"
d = {x: y, y: z}
assert srepr(d) in (
"{Symbol('x'): Symbol('y'), Symbol('y'): Symbol('z')}",
"{Symbol('y'): Symbol('z'), Symbol('x'): Symbol('y')}",
)
d = {x: {y: z}}
assert srepr(d) == "{Symbol('x'): {Symbol('y'): Symbol('z')}}"
def test_set():
from sympy import srepr
from sympy.abc import x, y
s = set()
assert srepr(s) == "set()"
s = {x, y}
assert srepr(s) in ("{Symbol('x'), Symbol('y')}", "{Symbol('y'), Symbol('x')}")
|
78dc15baf0f5850965a6d97f921b18fb5486b360aac3b51b516195314bc27f8f | from sympy import symbols
from sympy.functions import beta, Ei, zeta, Max, Min, sqrt
from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode
from sympy.codegen.cfunctions import log1p
from sympy.testing.pytest import warns_deprecated_sympy
x, y, u, v = symbols('x y u v')
def test_CXX98CodePrinter():
assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)')
assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))'
cxx98printer = CXX98CodePrinter()
assert cxx98printer.language == 'C++'
assert cxx98printer.standard == 'C++98'
assert 'template' in cxx98printer.reserved_words
assert 'alignas' not in cxx98printer.reserved_words
def test_CXX11CodePrinter():
assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)'
cxx11printer = CXX11CodePrinter()
assert cxx11printer.language == 'C++'
assert cxx11printer.standard == 'C++11'
assert 'operator' in cxx11printer.reserved_words
assert 'noexcept' in cxx11printer.reserved_words
assert 'concept' not in cxx11printer.reserved_words
def test_subclass_print_method():
class MyPrinter(CXX11CodePrinter):
def _print_log1p(self, expr):
return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args))
assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)'
def test_subclass_print_method__ns():
class MyPrinter(CXX11CodePrinter):
_ns = 'my_library::'
p = CXX11CodePrinter()
myp = MyPrinter()
assert p.doprint(log1p(x)) == 'std::log1p(x)'
assert myp.doprint(log1p(x)) == 'my_library::log1p(x)'
def test_CXX17CodePrinter():
assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)'
assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)'
assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)'
def test_cxxcode():
assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)'])
def test_cxxcode_submodule():
# Test the compatibility sympy.printing.cxxcode module imports
with warns_deprecated_sympy():
import sympy.printing.cxxcode # noqa:F401
def test_cxxcode_nested_minmax():
assert cxxcode(Max(Min(x, y), Min(u, v))) \
== 'std::max(std::min(u, v), std::min(x, y))'
assert cxxcode(Min(Max(x, y), Max(u, v))) \
== 'std::min(std::max(u, v), std::max(x, y))'
|
4edb0f7e331818cd790473585248cc4a6a52a5ce4a8a24a09049226a5e6e732d | from sympy import (Add, Abs, Catalan, cos, Derivative, E, EulerGamma, exp,
factorial, factorial2, Function, GoldenRatio, TribonacciConstant, I,
Integer, Integral, Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Pow,
Rational, Float, Rel, S, sin, SparseMatrix, sqrt, summation, Sum, Symbol,
symbols, Wild, WildFunction, zeta, zoo, Dummy, Dict, Tuple, FiniteSet, factor,
subfactorial, true, false, Equivalent, Xor, Complement, SymmetricDifference,
AccumBounds, UnevaluatedExpr, Eq, Ne, Quaternion, Subs, MatrixSymbol, MatrixSlice)
from sympy.core import Expr, Mul
from sympy.external import import_module
from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback
from sympy.physics.units import second, joule
from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ,
ZZ_I, QQ_I, lex, grlex)
from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle
from sympy.tensor import NDimArray
from sympy.testing.pytest import raises
from sympy.printing import sstr, sstrrepr, StrPrinter
from sympy.core.trace import Tr
x, y, z, w, t = symbols('x,y,z,w,t')
d = Dummy('d')
def test_printmethod():
class R(Abs):
def _sympystr(self, printer):
return "foo(%s)" % printer._print(self.args[0])
assert sstr(R(x)) == "foo(x)"
class R(Abs):
def _sympystr(self, printer):
return "foo"
assert sstr(R(x)) == "foo"
def test_Abs():
assert str(Abs(x)) == "Abs(x)"
assert str(Abs(Rational(1, 6))) == "1/6"
assert str(Abs(Rational(-1, 6))) == "1/6"
def test_Add():
assert str(x + y) == "x + y"
assert str(x + 1) == "x + 1"
assert str(x + x**2) == "x**2 + x"
assert str(Add(0, 1, evaluate=False)) == "0 + 1"
assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1"
assert str(1.0*x) == "1.0*x"
assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5"
assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1"
assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2"
assert str(x - y) == "x - y"
assert str(2 - x) == "2 - x"
assert str(x - 2) == "x - 2"
assert str(x - y - z - w) == "-w + x - y - z"
assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x"
assert str(x - 1*y*x*y) == "-x*y**2 + x"
assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)"
def test_Catalan():
assert str(Catalan) == "Catalan"
def test_ComplexInfinity():
assert str(zoo) == "zoo"
def test_Derivative():
assert str(Derivative(x, y)) == "Derivative(x, y)"
assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)"
assert str(Derivative(
x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)"
def test_dict():
assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}"
assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}"
def test_Dict():
assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}"
assert str(Dict({1: x**2, 2: y*x})) in (
"{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}"
def test_Dummy():
assert str(d) == "_d"
assert str(d + x) == "_d + x"
def test_EulerGamma():
assert str(EulerGamma) == "EulerGamma"
def test_Exp():
assert str(E) == "E"
def test_factorial():
n = Symbol('n', integer=True)
assert str(factorial(-2)) == "zoo"
assert str(factorial(0)) == "1"
assert str(factorial(7)) == "5040"
assert str(factorial(n)) == "factorial(n)"
assert str(factorial(2*n)) == "factorial(2*n)"
assert str(factorial(factorial(n))) == 'factorial(factorial(n))'
assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))'
assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))'
assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))'
assert str(subfactorial(3)) == "2"
assert str(subfactorial(n)) == "subfactorial(n)"
assert str(subfactorial(2*n)) == "subfactorial(2*n)"
def test_Function():
f = Function('f')
fx = f(x)
w = WildFunction('w')
assert str(f) == "f"
assert str(fx) == "f(x)"
assert str(w) == "w_"
def test_Geometry():
assert sstr(Point(0, 0)) == 'Point2D(0, 0)'
assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)'
assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)'
assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \
'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))'
assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \
'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))'
assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \
'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))'
assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \
'Ellipse(Point2D(S(1), S(2)), S(3), S(4))'
def test_GoldenRatio():
assert str(GoldenRatio) == "GoldenRatio"
def test_TribonacciConstant():
assert str(TribonacciConstant) == "TribonacciConstant"
def test_ImaginaryUnit():
assert str(I) == "I"
def test_Infinity():
assert str(oo) == "oo"
assert str(oo*I) == "oo*I"
def test_Integer():
assert str(Integer(-1)) == "-1"
assert str(Integer(1)) == "1"
assert str(Integer(-3)) == "-3"
assert str(Integer(0)) == "0"
assert str(Integer(25)) == "25"
def test_Integral():
assert str(Integral(sin(x), y)) == "Integral(sin(x), y)"
assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))"
def test_Interval():
n = (S.NegativeInfinity, 1, 2, S.Infinity)
for i in range(len(n)):
for j in range(i + 1, len(n)):
for l in (True, False):
for r in (True, False):
ival = Interval(n[i], n[j], l, r)
assert S(str(ival)) == ival
def test_AccumBounds():
a = Symbol('a', real=True)
assert str(AccumBounds(0, a)) == "AccumBounds(0, a)"
assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)"
def test_Lambda():
assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)"
# issue 2908
assert str(Lambda((), 1)) == "Lambda((), 1)"
assert str(Lambda((), x)) == "Lambda((), x)"
assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)"
assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)"
def test_Limit():
assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)"
assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)"
assert str(
Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')"
def test_list():
assert str([x]) == sstr([x]) == "[x]"
assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]"
assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]"
def test_Matrix_str():
M = Matrix([[x**+1, 1], [y, x + y]])
assert str(M) == "Matrix([[x, 1], [y, x + y]])"
assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])"
M = Matrix([[1]])
assert str(M) == sstr(M) == "Matrix([[1]])"
M = Matrix([[1, 2]])
assert str(M) == sstr(M) == "Matrix([[1, 2]])"
M = Matrix()
assert str(M) == sstr(M) == "Matrix(0, 0, [])"
M = Matrix(0, 1, lambda i, j: 0)
assert str(M) == sstr(M) == "Matrix(0, 1, [])"
def test_Mul():
assert str(x/y) == "x/y"
assert str(y/x) == "y/x"
assert str(x/y/z) == "x/(y*z)"
assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)"
assert str(2*x/3) == '2*x/3'
assert str(-2*x/3) == '-2*x/3'
assert str(-1.0*x) == '-1.0*x'
assert str(1.0*x) == '1.0*x'
assert str(Mul(0, 1, evaluate=False)) == '0*1'
assert str(Mul(1, 0, evaluate=False)) == '1*0'
assert str(Mul(1, 1, evaluate=False)) == '1*1'
assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1'
assert str(Mul(1, 2, evaluate=False)) == '1*2'
assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)'
assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)'
assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x'
assert str(Mul(1, -1, evaluate=False)) == '1*(-1)'
assert str(Mul(-1, 1, evaluate=False)) == '(-1)*1'
assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x'
assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x'
assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)'
# For issue 14160
assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
evaluate=False)) == '-2*x/(y*y)'
class CustomClass1(Expr):
is_commutative = True
class CustomClass2(Expr):
is_commutative = True
cc1 = CustomClass1()
cc2 = CustomClass2()
assert str(Rational(2)*cc1) == '2*CustomClass1()'
assert str(cc1*Rational(2)) == '2*CustomClass1()'
assert str(cc1*Float("1.5")) == '1.5*CustomClass1()'
assert str(cc2*Rational(2)) == '2*CustomClass2()'
assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()'
assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()'
def test_NaN():
assert str(nan) == "nan"
def test_NegativeInfinity():
assert str(-oo) == "-oo"
def test_Order():
assert str(O(x)) == "O(x)"
assert str(O(x**2)) == "O(x**2)"
assert str(O(x*y)) == "O(x*y, x, y)"
assert str(O(x, x)) == "O(x)"
assert str(O(x, (x, 0))) == "O(x)"
assert str(O(x, (x, oo))) == "O(x, (x, oo))"
assert str(O(x, x, y)) == "O(x, x, y)"
assert str(O(x, x, y)) == "O(x, x, y)"
assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))"
def test_Permutation_Cycle():
from sympy.combinatorics import Permutation, Cycle
# general principle: economically, canonically show all moved elements
# and the size of the permutation.
for p, s in [
(Cycle(),
'()'),
(Cycle(2),
'(2)'),
(Cycle(2, 1),
'(1 2)'),
(Cycle(1, 2)(5)(6, 7)(10),
'(1 2)(6 7)(10)'),
(Cycle(3, 4)(1, 2)(3, 4),
'(1 2)(4)'),
]:
assert sstr(p) == s
for p, s in [
(Permutation([]),
'Permutation([])'),
(Permutation([], size=1),
'Permutation([0])'),
(Permutation([], size=2),
'Permutation([0, 1])'),
(Permutation([], size=10),
'Permutation([], size=10)'),
(Permutation([1, 0, 2]),
'Permutation([1, 0, 2])'),
(Permutation([1, 0, 2, 3, 4, 5]),
'Permutation([1, 0], size=6)'),
(Permutation([1, 0, 2, 3, 4, 5], size=10),
'Permutation([1, 0], size=10)'),
]:
assert sstr(p, perm_cyclic=False) == s
for p, s in [
(Permutation([]),
'()'),
(Permutation([], size=1),
'(0)'),
(Permutation([], size=2),
'(1)'),
(Permutation([], size=10),
'(9)'),
(Permutation([1, 0, 2]),
'(2)(0 1)'),
(Permutation([1, 0, 2, 3, 4, 5]),
'(5)(0 1)'),
(Permutation([1, 0, 2, 3, 4, 5], size=10),
'(9)(0 1)'),
(Permutation([0, 1, 3, 2, 4, 5], size=10),
'(9)(2 3)'),
]:
assert sstr(p) == s
def test_Pi():
assert str(pi) == "pi"
def test_Poly():
assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')"
assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')"
assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')"
assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')"
assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')"
assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')"
assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')"
assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')"
assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')"
assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')"
assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')"
assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')"
assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')"
assert str(Poly((x + y)**3, (x + y), expand=False)
) == "Poly((x + y)**3, x + y, domain='ZZ')"
assert str(Poly((x - 1)**2, (x - 1), expand=False)
) == "Poly((x - 1)**2, x - 1, domain='ZZ')"
assert str(
Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')"
assert str(
Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')"
assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')"
assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')"
assert str(Poly(-x*y*z + x*y - 1, x, y, z)
) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')"
assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \
"Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')"
assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)"
assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)"
def test_PolyRing():
assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order"
assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order"
assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order"
def test_FracField():
assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order"
assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order"
assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order"
def test_PolyElement():
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
Rx_zzi, xz = ring("x", ZZ_I)
assert str(x - x) == "0"
assert str(x - 1) == "x - 1"
assert str(x + 1) == "x + 1"
assert str(x**2) == "x**2"
assert str(x**(-2)) == "x**(-2)"
assert str(x**QQ(1, 2)) == "x**(1/2)"
assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1"
assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x"
assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1"
assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1"
assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1"
assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1"
assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)"
def test_FracElement():
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
Rx_zzi, xz = field("x", QQ_I)
i = QQ_I(0, 1)
assert str(x - x) == "0"
assert str(x - 1) == "x - 1"
assert str(x + 1) == "x + 1"
assert str(x/3) == "x/3"
assert str(x/z) == "x/z"
assert str(x*y/z) == "x*y/z"
assert str(x/(z*t)) == "x/(z*t)"
assert str(x*y/(z*t)) == "x*y/(z*t)"
assert str((x - 1)/y) == "(x - 1)/y"
assert str((x + 1)/y) == "(x + 1)/y"
assert str((-x - 1)/y) == "(-x - 1)/y"
assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)"
assert str(-y/(x + 1)) == "-y/(x + 1)"
assert str(y*z/(x + 1)) == "y*z/(x + 1)"
assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)"
assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)"
assert str((1+i)/xz) == "(1 + 1*I)/x"
assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x"
def test_GaussianInteger():
assert str(ZZ_I(1, 0)) == "1"
assert str(ZZ_I(-1, 0)) == "-1"
assert str(ZZ_I(0, 1)) == "I"
assert str(ZZ_I(0, -1)) == "-I"
assert str(ZZ_I(0, 2)) == "2*I"
assert str(ZZ_I(0, -2)) == "-2*I"
assert str(ZZ_I(1, 1)) == "1 + I"
assert str(ZZ_I(-1, -1)) == "-1 - I"
assert str(ZZ_I(-1, -2)) == "-1 - 2*I"
def test_GaussianRational():
assert str(QQ_I(1, 0)) == "1"
assert str(QQ_I(QQ(2, 3), 0)) == "2/3"
assert str(QQ_I(0, QQ(2, 3))) == "2*I/3"
assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3"
def test_Pow():
assert str(x**-1) == "1/x"
assert str(x**-2) == "x**(-2)"
assert str(x**2) == "x**2"
assert str((x + y)**-1) == "1/(x + y)"
assert str((x + y)**-2) == "(x + y)**(-2)"
assert str((x + y)**2) == "(x + y)**2"
assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)"
assert str(x**Rational(1, 3)) == "x**(1/3)"
assert str(1/x**Rational(1, 3)) == "x**(-1/3)"
assert str(sqrt(sqrt(x))) == "x**(1/4)"
# not the same as x**-1
assert str(x**-1.0) == 'x**(-1.0)'
# see issue #2860
assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)'
def test_sqrt():
assert str(sqrt(x)) == "sqrt(x)"
assert str(sqrt(x**2)) == "sqrt(x**2)"
assert str(1/sqrt(x)) == "1/sqrt(x)"
assert str(1/sqrt(x**2)) == "1/sqrt(x**2)"
assert str(y/sqrt(x)) == "y/sqrt(x)"
assert str(x**0.5) == "x**0.5"
assert str(1/x**0.5) == "x**(-0.5)"
def test_Rational():
n1 = Rational(1, 4)
n2 = Rational(1, 3)
n3 = Rational(2, 4)
n4 = Rational(2, -4)
n5 = Rational(0)
n7 = Rational(3)
n8 = Rational(-3)
assert str(n1*n2) == "1/12"
assert str(n1*n2) == "1/12"
assert str(n3) == "1/2"
assert str(n1*n3) == "1/8"
assert str(n1 + n3) == "3/4"
assert str(n1 + n2) == "7/12"
assert str(n1 + n4) == "-1/4"
assert str(n4*n4) == "1/4"
assert str(n4 + n2) == "-1/6"
assert str(n4 + n5) == "-1/2"
assert str(n4*n5) == "0"
assert str(n3 + n4) == "0"
assert str(n1**n7) == "1/64"
assert str(n2**n7) == "1/27"
assert str(n2**n8) == "27"
assert str(n7**n8) == "1/27"
assert str(Rational("-25")) == "-25"
assert str(Rational("1.25")) == "5/4"
assert str(Rational("-2.6e-2")) == "-13/500"
assert str(S("25/7")) == "25/7"
assert str(S("-123/569")) == "-123/569"
assert str(S("0.1[23]", rational=1)) == "61/495"
assert str(S("5.1[666]", rational=1)) == "31/6"
assert str(S("-5.1[666]", rational=1)) == "-31/6"
assert str(S("0.[9]", rational=1)) == "1"
assert str(S("-0.[9]", rational=1)) == "-1"
assert str(sqrt(Rational(1, 4))) == "1/2"
assert str(sqrt(Rational(1, 36))) == "1/6"
assert str((123**25) ** Rational(1, 25)) == "123"
assert str((123**25 + 1)**Rational(1, 25)) != "123"
assert str((123**25 - 1)**Rational(1, 25)) != "123"
assert str((123**25 - 1)**Rational(1, 25)) != "122"
assert str(sqrt(Rational(81, 36))**3) == "27/8"
assert str(1/sqrt(Rational(81, 36))**3) == "8/27"
assert str(sqrt(-4)) == str(2*I)
assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)"
assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3"
x = Symbol("x")
assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)"
assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)"
assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \
"Limit(x, x, S(7)/2)"
def test_Float():
# NOTE dps is the whole number of decimal digits
assert str(Float('1.23', dps=1 + 2)) == '1.23'
assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789'
assert str(
Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789'
assert str(pi.evalf(1 + 2)) == '3.14'
assert str(pi.evalf(1 + 14)) == '3.14159265358979'
assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279'
'5028841971693993751058209749445923')
assert str(pi.round(-1)) == '0.0'
assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88'
assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2'
assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0'
assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1'
assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2'
def test_Relational():
assert str(Rel(x, y, "<")) == "x < y"
assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)"
assert str(Rel(x, y, "!=")) == "Ne(x, y)"
assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)"
assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)"
def test_CRootOf():
assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)"
def test_RootSum():
f = x**5 + 2*x - 1
assert str(
RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)"
assert str(RootSum(f, Lambda(
z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))"
def test_GroebnerBasis():
assert str(groebner(
[], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')"
F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
assert str(groebner(F, order='grlex')) == \
"GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')"
assert str(groebner(F, order='lex')) == \
"GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')"
def test_set():
assert sstr(set()) == 'set()'
assert sstr(frozenset()) == 'frozenset()'
assert sstr({1}) == '{1}'
assert sstr(frozenset([1])) == 'frozenset({1})'
assert sstr({1, 2, 3}) == '{1, 2, 3}'
assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})'
assert sstr(
{1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}'
assert sstr(
frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})'
def test_SparseMatrix():
M = SparseMatrix([[x**+1, 1], [y, x + y]])
assert str(M) == "Matrix([[x, 1], [y, x + y]])"
assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])"
def test_Sum():
assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))"
assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
"Sum(x*y**2, (x, -2, 2), (y, -5, 5))"
def test_Symbol():
assert str(y) == "y"
assert str(x) == "x"
e = x
assert str(e) == "x"
def test_tuple():
assert str((x,)) == sstr((x,)) == "(x,)"
assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)"
assert str((x + y, (
1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))"
def test_Series_str():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert str(Series(tf1, tf2)) == \
"Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))"
assert str(Series(tf1, tf2, tf3)) == \
"Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))"
assert str(Series(-tf2, tf1)) == \
"Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))"
def test_TransferFunction_str():
tf1 = TransferFunction(x - 1, x + 1, x)
assert str(tf1) == "TransferFunction(x - 1, x + 1, x)"
tf2 = TransferFunction(x + 1, 2 - y, x)
assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)"
tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)"
def test_Parallel_str():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert str(Parallel(tf1, tf2)) == \
"Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))"
assert str(Parallel(tf1, tf2, tf3)) == \
"Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))"
assert str(Parallel(-tf2, tf1)) == \
"Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))"
def test_Feedback_str():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert str(Feedback(tf1*tf2, tf3)) == \
"Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), TransferFunction(t*x**2 - t**w*x + w, t - y, y))"
assert str(Feedback(tf1, TransferFunction(1, 1, y))) == \
"Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y))"
def test_Quaternion_str_printer():
q = Quaternion(x, y, z, t)
assert str(q) == "x + y*i + z*j + t*k"
q = Quaternion(x,y,z,x*t)
assert str(q) == "x + y*i + z*j + t*x*k"
q = Quaternion(x,y,z,x+t)
assert str(q) == "x + y*i + z*j + (t + x)*k"
def test_Quantity_str():
assert sstr(second, abbrev=True) == "s"
assert sstr(joule, abbrev=True) == "J"
assert str(second) == "second"
assert str(joule) == "joule"
def test_wild_str():
# Check expressions containing Wild not causing infinite recursion
w = Wild('x')
assert str(w + 1) == 'x_ + 1'
assert str(exp(2**w) + 5) == 'exp(2**x_) + 5'
assert str(3*w + 1) == '3*x_ + 1'
assert str(1/w + 1) == '1 + 1/x_'
assert str(w**2 + 1) == 'x_**2 + 1'
assert str(1/(1 - w)) == '1/(1 - x_)'
def test_wild_matchpy():
from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar
matchpy = import_module("matchpy")
if matchpy is None:
return
wd = WildDot('w')
wp = WildPlus('w')
ws = WildStar('w')
assert str(wd) == 'w_'
assert str(wp) == 'w__'
assert str(ws) == 'w___'
assert str(wp/ws + 2**wd) == '2**w_ + w__/w___'
assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)'
def test_zeta():
assert str(zeta(3)) == "zeta(3)"
def test_issue_3101():
e = x - y
a = str(e)
b = str(e)
assert a == b
def test_issue_3103():
e = -2*sqrt(x) - y/sqrt(x)/2
assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y",
"-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"]
assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))"
def test_issue_4021():
e = Integral(x, x) + 1
assert str(e) == 'Integral(x, x) + 1'
def test_sstrrepr():
assert sstr('abc') == 'abc'
assert sstrrepr('abc') == "'abc'"
e = ['a', 'b', 'c', x]
assert sstr(e) == "[a, b, c, x]"
assert sstrrepr(e) == "['a', 'b', 'c', x]"
def test_infinity():
assert sstr(oo*I) == "oo*I"
def test_full_prec():
assert sstr(S("0.3"), full_prec=True) == "0.300000000000000"
assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000"
assert sstr(S("0.3"), full_prec=False) == "0.3"
assert sstr(S("0.3")*x, full_prec=True) in [
"0.300000000000000*x",
"x*0.300000000000000"
]
assert sstr(S("0.3")*x, full_prec="auto") in [
"0.3*x",
"x*0.3"
]
assert sstr(S("0.3")*x, full_prec=False) in [
"0.3*x",
"x*0.3"
]
def test_noncommutative():
A, B, C = symbols('A,B,C', commutative=False)
assert sstr(A*B*C**-1) == "A*B*C**(-1)"
assert sstr(C**-1*A*B) == "C**(-1)*A*B"
assert sstr(A*C**-1*B) == "A*C**(-1)*B"
assert sstr(sqrt(A)) == "sqrt(A)"
assert sstr(1/sqrt(A)) == "A**(-1/2)"
def test_empty_printer():
str_printer = StrPrinter()
assert str_printer.emptyPrinter("foo") == "foo"
assert str_printer.emptyPrinter(x*y) == "x*y"
assert str_printer.emptyPrinter(32) == "32"
def test_settings():
raises(TypeError, lambda: sstr(S(4), method="garbage"))
def test_RandomDomain():
from sympy.stats import Normal, Die, Exponential, pspace, where
X = Normal('x1', 0, 1)
assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)"
D = Die('d1', 6)
assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)"
A = Exponential('a', 1)
B = Exponential('b', 1)
assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)"
def test_FiniteSet():
assert str(FiniteSet(*range(1, 51))) == (
'FiniteSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,'
' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,'
' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)'
)
assert str(FiniteSet(*range(1, 6))) == 'FiniteSet(1, 2, 3, 4, 5)'
def test_UniversalSet():
assert str(S.UniversalSet) == 'UniversalSet'
def test_PrettyPoly():
from sympy.polys.domains import QQ
F = QQ.frac_field(x, y)
R = QQ[x, y]
assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y))
assert sstr(R.convert(x + y)) == sstr(x + y)
def test_categories():
from sympy.categories import (Object, NamedMorphism,
IdentityMorphism, Category)
A = Object("A")
B = Object("B")
f = NamedMorphism(A, B, "f")
id_A = IdentityMorphism(A)
K = Category("K")
assert str(A) == 'Object("A")'
assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")'
assert str(id_A) == 'IdentityMorphism(Object("A"))'
assert str(K) == 'Category("K")'
def test_Tr():
A, B = symbols('A B', commutative=False)
t = Tr(A*B)
assert str(t) == 'Tr(A*B)'
def test_issue_6387():
assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)'
def test_MatMul_MatAdd():
from sympy import MatrixSymbol
X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2)
assert str(2*(X + Y)) == "2*(X + Y)"
assert str(I*X) == "I*X"
assert str(-I*X) == "-I*X"
assert str((1 + I)*X) == '(1 + I)*X'
assert str(-(1 + I)*X) == '(-1 - I)*X'
def test_MatrixSlice():
n = Symbol('n', integer=True)
X = MatrixSymbol('X', n, n)
Y = MatrixSymbol('Y', 10, 10)
Z = MatrixSymbol('Z', 10, 10)
assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]'
assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]'
assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]'
assert str(X[:x, y:]) == 'X[:x, y:]'
assert str(X[:x, y:]) == 'X[:x, y:]'
assert str(X[x:, :y]) == 'X[x:, :y]'
assert str(X[x:y, z:w]) == 'X[x:y, z:w]'
assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]'
assert str(X[x::y, t::w]) == 'X[x::y, t::w]'
assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]'
assert str(X[::x, ::y]) == 'X[::x, ::y]'
assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]'
assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]'
assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]'
assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]'
assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]'
assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]'
assert str(X[1:10:2]) == 'X[1:10:2, :]'
assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]'
assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]'
assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]'
assert str(X[0:1, 0:1]) == 'X[:1, :1]'
assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]'
assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]'
def test_true_false():
assert str(true) == repr(true) == sstr(true) == "True"
assert str(false) == repr(false) == sstr(false) == "False"
def test_Equivalent():
assert str(Equivalent(y, x)) == "Equivalent(x, y)"
def test_Xor():
assert str(Xor(y, x, evaluate=False)) == "x ^ y"
def test_Complement():
assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)'
def test_SymmetricDifference():
assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \
'SymmetricDifference(Interval(2, 3), Interval(3, 4))'
def test_UnevaluatedExpr():
a, b = symbols("a b")
expr1 = 2*UnevaluatedExpr(a+b)
assert str(expr1) == "2*(a + b)"
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert(str(A[0, 0]) == "A[0, 0]")
assert(str(3 * A[0, 0]) == "3*A[0, 0]")
F = C[0, 0].subs(C, A - B)
assert str(F) == "(A - B)[0, 0]"
def test_MatrixSymbol_printing():
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
assert str(A - A*B - B) == "A - A*B - B"
assert str(A*B - (A+B)) == "-(A + B) + A*B"
assert str(A**(-1)) == "A**(-1)"
assert str(A**3) == "A**3"
def test_MatrixExpressions():
n = Symbol('n', integer=True)
X = MatrixSymbol('X', n, n)
assert str(X) == "X"
# Apply function elementwise (`ElementwiseApplyFunc`):
expr = (X.T*X).applyfunc(sin)
assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)'
lamda = Lambda(x, 1/x)
expr = (n*X).applyfunc(lamda)
assert str(expr) == 'Lambda(x, 1/x).(n*X)'
def test_Subs_printing():
assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)'
assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))'
def test_issue_15716():
e = Integral(factorial(x), (x, -oo, oo))
assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e])
def test_str_special_matrices():
from sympy.matrices import Identity, ZeroMatrix, OneMatrix
assert str(Identity(4)) == 'I'
assert str(ZeroMatrix(2, 2)) == '0'
assert str(OneMatrix(2, 2)) == '1'
def test_issue_14567():
assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error
def test_Str():
from sympy.core.symbol import Str
assert str(Str('x')) == 'x'
assert sstrrepr(Str('x')) == "Str('x')"
def test_diffgeom():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
x,y = symbols('x y', real=True)
m = Manifold('M', 2)
assert str(m) == "M"
p = Patch('P', m)
assert str(p) == "P"
rect = CoordSystem('rect', p, [x, y])
assert str(rect) == "rect"
b = BaseScalarField(rect, 0)
assert str(b) == "x"
def test_NDimArray():
assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000'
assert sstr(NDimArray(1.0), full_prec=False) == '1.0'
assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]'
assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]'
|
0a409b1c3fe6c6d0c82a5d45cc4ee276a072bdedaccf4c6a1997409c974041bc | from sympy.tensor.toperators import PartialDerivative
from sympy import (
Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial,
FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral,
Interval, InverseCosineTransform, InverseFourierTransform, Derivative,
InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform,
Lambda, LaplaceTransform, Limit, Matrix, Max, MellinTransform, Min, Mul,
Order, Piecewise, Poly, ring, field, ZZ, Pow, Product, Range, Rational,
RisingFactorial, rootof, RootSum, S, Shi, Si, SineTransform, Subs,
Sum, Symbol, ImageSet, Tuple, Ynm, Znm, arg, asin, acsc, asinh, Mod,
assoc_laguerre, assoc_legendre, beta, binomial, catalan, ceiling,
chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, euler,
exp, expint, factorial, factorial2, floor, gamma, gegenbauer, hermite,
hyper, im, jacobi, laguerre, legendre, lerchphi, log, frac,
meijerg, oo, polar_lift, polylog, re, root, sin, sqrt, symbols,
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not,
Contains, divisor_sigma, SeqPer, SeqFormula, MatrixSlice,
SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps,
AccumBounds, reduced_totient, primenu, primeomega, SingularityFunction,
stieltjes, mathieuc, mathieus, mathieucprime, mathieusprime,
UnevaluatedExpr, Quaternion, I, KroneckerProduct, LambertW)
from sympy.ntheory.factor_ import udivisor_sigma
from sympy.abc import mu, tau
from sympy.printing.latex import (latex, translate, greek_letters_set,
tex_greek_dictionary, multiline_latex,
latex_escape, LatexPrinter)
from sympy.tensor.array import (ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableSparseNDimArray,
MutableDenseNDimArray,
tensorproduct)
from sympy.testing.pytest import XFAIL, raises
from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita
from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \
fibonacci, tribonacci
from sympy.logic import Implies
from sympy.logic.boolalg import And, Or, Xor
from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback
from sympy.physics.quantum import Commutator, Operator
from sympy.physics.units import meter, gibibyte, microgram, second
from sympy.core.trace import Tr
from sympy.combinatorics.permutations import \
Cycle, Permutation, AppliedPermutation
from sympy.matrices.expressions.permutation import PermutationMatrix
from sympy import MatrixSymbol, ln
from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
from sympy.sets.setexpr import SetExpr
from sympy.sets.sets import \
Union, Intersection, Complement, SymmetricDifference, ProductSet
import sympy as sym
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p')
k, m, n = symbols('k m n', integer=True)
def test_printmethod():
class R(Abs):
def _latex(self, printer):
return "foo(%s)" % printer._print(self.args[0])
assert latex(R(x)) == "foo(x)"
class R(Abs):
def _latex(self, printer):
return "foo"
assert latex(R(x)) == "foo"
def test_latex_basic():
assert latex(1 + x) == "x + 1"
assert latex(x**2) == "x^{2}"
assert latex(x**(1 + x)) == "x^{x + 1}"
assert latex(x**3 + x + 1 + x**2) == "x^{3} + x^{2} + x + 1"
assert latex(2*x*y) == "2 x y"
assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y"
assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y"
assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}"
assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1'
assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0'
assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1'
assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1'
assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1'
assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2'
assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \frac{1}{2}'
assert latex(Mul(1, 1, S.Half, evaluate=False)) == \
r'1 \cdot 1 \frac{1}{2}'
assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \
r'1 \cdot 1 \cdot 2 \cdot 3 x'
assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)'
assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x'
assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x'
assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \
r'\frac{2}{3} \frac{5}{7}'
assert latex(1/x) == r"\frac{1}{x}"
assert latex(1/x, fold_short_frac=True) == "1 / x"
assert latex(-S(3)/2) == r"- \frac{3}{2}"
assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2"
assert latex(1/x**2) == r"\frac{1}{x^{2}}"
assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}"
assert latex(x/2) == r"\frac{x}{2}"
assert latex(x/2, fold_short_frac=True) == "x / 2"
assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}"
assert latex((x + y)/(2*x), fold_short_frac=True) == \
r"\left(x + y\right) / 2 x"
assert latex((x + y)/(2*x), long_frac_ratio=0) == \
r"\frac{1}{2 x} \left(x + y\right)"
assert latex((x + y)/x) == r"\frac{x + y}{x}"
assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}"
assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}"
assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \
r"\frac{2 x}{3} \sqrt{2}"
assert latex(binomial(x, y)) == r"{\binom{x}{y}}"
x_star = Symbol('x^*')
f = Function('f')
assert latex(x_star**2) == r"\left(x^{*}\right)^{2}"
assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}"
assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}"
assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}"
assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}"
assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \
r"\left(2 \int x\, dx\right) / 3"
assert latex(sqrt(x)) == r"\sqrt{x}"
assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}"
assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}"
assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}"
assert latex(sqrt(x), itex=True) == r"\sqrt{x}"
assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}"
assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}"
assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}"
assert latex(x**Rational(3, 4), fold_frac_powers=True) == "x^{3/4}"
assert latex((x + 1)**Rational(3, 4)) == \
r"\left(x + 1\right)^{\frac{3}{4}}"
assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \
r"\left(x + 1\right)^{3/4}"
assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x"
assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x"
assert latex(1.5e20*x, mul_symbol='times') == \
r"1.5 \times 10^{20} \times x"
assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}"
assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}"
assert latex(sin(x)**Rational(3, 2)) == \
r"\sin^{\frac{3}{2}}{\left(x \right)}"
assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \
r"\sin^{3/2}{\left(x \right)}"
assert latex(~x) == r"\neg x"
assert latex(x & y) == r"x \wedge y"
assert latex(x & y & z) == r"x \wedge y \wedge z"
assert latex(x | y) == r"x \vee y"
assert latex(x | y | z) == r"x \vee y \vee z"
assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)"
assert latex(Implies(x, y)) == r"x \Rightarrow y"
assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y"
assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z"
assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)"
assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)"
assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i"
assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \
r"x_i \wedge y_i"
assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"x_i \wedge y_i \wedge z_i"
assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i"
assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"x_i \vee y_i \vee z_i"
assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"z_i \vee \left(x_i \wedge y_i\right)"
assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \
r"x_i \Rightarrow y_i"
p = Symbol('p', positive=True)
assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}"
def test_latex_builtins():
assert latex(True) == r"\text{True}"
assert latex(False) == r"\text{False}"
assert latex(None) == r"\text{None}"
assert latex(true) == r"\text{True}"
assert latex(false) == r'\text{False}'
def test_latex_SingularityFunction():
assert latex(SingularityFunction(x, 4, 5)) == \
r"{\left\langle x - 4 \right\rangle}^{5}"
assert latex(SingularityFunction(x, -3, 4)) == \
r"{\left\langle x + 3 \right\rangle}^{4}"
assert latex(SingularityFunction(x, 0, 4)) == \
r"{\left\langle x \right\rangle}^{4}"
assert latex(SingularityFunction(x, a, n)) == \
r"{\left\langle - a + x \right\rangle}^{n}"
assert latex(SingularityFunction(x, 4, -2)) == \
r"{\left\langle x - 4 \right\rangle}^{-2}"
assert latex(SingularityFunction(x, 4, -1)) == \
r"{\left\langle x - 4 \right\rangle}^{-1}"
def test_latex_cycle():
assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
assert latex(Cycle(1, 2)(4, 5, 6)) == \
r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
assert latex(Cycle()) == r"\left( \right)"
def test_latex_permutation():
assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
assert latex(Permutation(1, 2)(4, 5, 6)) == \
r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
assert latex(Permutation()) == r"\left( \right)"
assert latex(Permutation(2, 4)*Permutation(5)) == \
r"\left( 2\; 4\right)\left( 5\right)"
assert latex(Permutation(5)) == r"\left( 5\right)"
assert latex(Permutation(0, 1), perm_cyclic=False) == \
r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}"
assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \
r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
assert latex(Permutation(), perm_cyclic=False) == \
r"\left( \right)"
def test_latex_Float():
assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}"
assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}"
assert latex(Float(1.0e-100), mul_symbol="times") == \
r"1.0 \times 10^{-100}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \
r"1.0 \cdot 10^{4}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \
r"1.0 \cdot 10^{4}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \
r"10000.0"
assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \
r"9.99990000000000 \cdot 10^{-2}"
def test_latex_vector_expressions():
A = CoordSys3D('A')
assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \
r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
assert latex(Cross(A.i, A.j)) == \
r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}"
assert latex(x*Cross(A.i, A.j)) == \
r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)"
assert latex(Cross(x*A.i, A.j)) == \
r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)'
assert latex(Curl(3*A.x*A.j)) == \
r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*A.x*A.j+A.i)) == \
r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*x*A.x*A.j)) == \
r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Curl(3*A.x*A.j)) == \
r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Divergence(3*A.x*A.j+A.i)) == \
r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Divergence(3*A.x*A.j)) == \
r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Divergence(3*A.x*A.j)) == \
r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \
r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
assert latex(Dot(A.i, A.j)) == \
r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}"
assert latex(Dot(x*A.i, A.j)) == \
r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)"
assert latex(x*Dot(A.i, A.j)) == \
r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)"
assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}"
assert latex(Gradient(A.x + 3*A.y)) == \
r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)"
assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)"
assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}"
assert latex(Laplacian(A.x + 3*A.y)) == \
r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)"
assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)"
def test_latex_symbols():
Gamma, lmbda, rho = symbols('Gamma, lambda, rho')
tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU')
assert latex(tau) == r"\tau"
assert latex(Tau) == "T"
assert latex(TAU) == r"\tau"
assert latex(taU) == r"\tau"
# Check that all capitalized greek letters are handled explicitly
capitalized_letters = {l.capitalize() for l in greek_letters_set}
assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0
assert latex(Gamma + lmbda) == r"\Gamma + \lambda"
assert latex(Gamma * lmbda) == r"\Gamma \lambda"
assert latex(Symbol('q1')) == r"q_{1}"
assert latex(Symbol('q21')) == r"q_{21}"
assert latex(Symbol('epsilon0')) == r"\epsilon_{0}"
assert latex(Symbol('omega1')) == r"\omega_{1}"
assert latex(Symbol('91')) == r"91"
assert latex(Symbol('alpha_new')) == r"\alpha_{new}"
assert latex(Symbol('C^orig')) == r"C^{orig}"
assert latex(Symbol('x^alpha')) == r"x^{\alpha}"
assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}"
assert latex(Symbol('e^Alpha')) == r"e^{A}"
assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}"
assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}"
@XFAIL
def test_latex_symbols_failing():
rho, mass, volume = symbols('rho, mass, volume')
assert latex(
volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}"
assert latex(volume / mass * rho == 1) == \
r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1"
assert latex(mass**3 * volume**3) == \
r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}"
def test_latex_functions():
assert latex(exp(x)) == "e^{x}"
assert latex(exp(1) + exp(2)) == "e + e^{2}"
f = Function('f')
assert latex(f(x)) == r'f{\left(x \right)}'
assert latex(f) == r'f'
g = Function('g')
assert latex(g(x, y)) == r'g{\left(x,y \right)}'
assert latex(g) == r'g'
h = Function('h')
assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}'
assert latex(h) == r'h'
Li = Function('Li')
assert latex(Li) == r'\operatorname{Li}'
assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}'
mybeta = Function('beta')
# not to be confused with the beta function
assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}"
assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)'
assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)'
assert latex(mybeta(x)) == r"\beta{\left(x \right)}"
assert latex(mybeta) == r"\beta"
g = Function('gamma')
# not to be confused with the gamma function
assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}"
assert latex(g(x)) == r"\gamma{\left(x \right)}"
assert latex(g) == r"\gamma"
a1 = Function('a_1')
assert latex(a1) == r"\operatorname{a_{1}}"
assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}"
# issue 5868
omega1 = Function('omega1')
assert latex(omega1) == r"\omega_{1}"
assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}"
assert latex(sin(x)) == r"\sin{\left(x \right)}"
assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
assert latex(sin(2*x**2), fold_func_brackets=True) == \
r"\sin {2 x^{2}}"
assert latex(sin(x**2), fold_func_brackets=True) == \
r"\sin {x^{2}}"
assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}"
assert latex(asin(x)**2, inv_trig_style="full") == \
r"\arcsin^{2}{\left(x \right)}"
assert latex(asin(x)**2, inv_trig_style="power") == \
r"\sin^{-1}{\left(x \right)}^{2}"
assert latex(asin(x**2), inv_trig_style="power",
fold_func_brackets=True) == \
r"\sin^{-1} {x^{2}}"
assert latex(acsc(x), inv_trig_style="full") == \
r"\operatorname{arccsc}{\left(x \right)}"
assert latex(asinh(x), inv_trig_style="full") == \
r"\operatorname{arcsinh}{\left(x \right)}"
assert latex(factorial(k)) == r"k!"
assert latex(factorial(-k)) == r"\left(- k\right)!"
assert latex(factorial(k)**2) == r"k!^{2}"
assert latex(subfactorial(k)) == r"!k"
assert latex(subfactorial(-k)) == r"!\left(- k\right)"
assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}"
assert latex(factorial2(k)) == r"k!!"
assert latex(factorial2(-k)) == r"\left(- k\right)!!"
assert latex(factorial2(k)**2) == r"k!!^{2}"
assert latex(binomial(2, k)) == r"{\binom{2}{k}}"
assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}"
assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}"
assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}"
assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor"
assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil"
assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}"
assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}"
assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}"
assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}"
assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
assert latex(Abs(x)) == r"\left|{x}\right|"
assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}"
assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}"
assert latex(re(x + y)) == \
r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}"
assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}"
assert latex(conjugate(x)) == r"\overline{x}"
assert latex(conjugate(x)**2) == r"\overline{x}^{2}"
assert latex(conjugate(x**2)) == r"\overline{x}^{2}"
assert latex(gamma(x)) == r"\Gamma\left(x\right)"
w = Wild('w')
assert latex(gamma(w)) == r"\Gamma\left(w\right)"
assert latex(Order(x)) == r"O\left(x\right)"
assert latex(Order(x, x)) == r"O\left(x\right)"
assert latex(Order(x, (x, 0))) == r"O\left(x\right)"
assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)"
assert latex(Order(x - y, (x, y))) == \
r"O\left(x - y; x\rightarrow y\right)"
assert latex(Order(x, x, y)) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)"
assert latex(Order(x, x, y)) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)"
assert latex(Order(x, (x, oo), (y, oo))) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)"
assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)'
assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'
assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)'
assert latex(cot(x)) == r'\cot{\left(x \right)}'
assert latex(coth(x)) == r'\coth{\left(x \right)}'
assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}'
assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}'
assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
assert latex(arg(x)) == r'\arg{\left(x \right)}'
assert latex(zeta(x)) == r"\zeta\left(x\right)"
assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
assert latex(
polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"
assert latex(stieltjes(x)) == r"\gamma_{x}"
assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}"
assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)"
assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}"
assert latex(elliptic_k(z)) == r"K\left(z\right)"
assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)"
assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)"
assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)"
assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)"
assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)"
assert latex(elliptic_e(z)) == r"E\left(z\right)"
assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)"
assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)"
assert latex(elliptic_pi(x, y, z)**2) == \
r"\Pi^{2}\left(x; y\middle| z\right)"
assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)"
assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)"
assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}'
assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}'
assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)'
assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}'
assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}'
assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}'
assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)'
assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)'
assert latex(jacobi(n, a, b, x)) == \
r'P_{n}^{\left(a,b\right)}\left(x\right)'
assert latex(jacobi(n, a, b, x)**2) == \
r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
assert latex(gegenbauer(n, a, x)) == \
r'C_{n}^{\left(a\right)}\left(x\right)'
assert latex(gegenbauer(n, a, x)**2) == \
r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
assert latex(chebyshevt(n, x)**2) == \
r'\left(T_{n}\left(x\right)\right)^{2}'
assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
assert latex(chebyshevu(n, x)**2) == \
r'\left(U_{n}\left(x\right)\right)^{2}'
assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
assert latex(assoc_legendre(n, a, x)) == \
r'P_{n}^{\left(a\right)}\left(x\right)'
assert latex(assoc_legendre(n, a, x)**2) == \
r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
assert latex(assoc_laguerre(n, a, x)) == \
r'L_{n}^{\left(a\right)}\left(x\right)'
assert latex(assoc_laguerre(n, a, x)**2) == \
r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'
theta = Symbol("theta", real=True)
phi = Symbol("phi", real=True)
assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)'
assert latex(Ynm(n, m, theta, phi)**3) == \
r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)'
assert latex(Znm(n, m, theta, phi)**3) == \
r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
# Test latex printing of function names with "_"
assert latex(polar_lift(0)) == \
r"\operatorname{polar\_lift}{\left(0 \right)}"
assert latex(polar_lift(0)**3) == \
r"\operatorname{polar\_lift}^{3}{\left(0 \right)}"
assert latex(totient(n)) == r'\phi\left(n\right)'
assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}'
assert latex(reduced_totient(n)) == r'\lambda\left(n\right)'
assert latex(reduced_totient(n) ** 2) == \
r'\left(\lambda\left(n\right)\right)^{2}'
assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)"
assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)"
assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)"
assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)"
assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)"
assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)"
assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)"
assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)"
assert latex(primenu(n)) == r'\nu\left(n\right)'
assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}'
assert latex(primeomega(n)) == r'\Omega\left(n\right)'
assert latex(primeomega(n) ** 2) == \
r'\left(\Omega\left(n\right)\right)^{2}'
assert latex(LambertW(n)) == r'W\left(n\right)'
assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)'
assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)'
assert latex(Mod(x, 7)) == r'x\bmod{7}'
assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right)\bmod{7}'
assert latex(Mod(2 * x, 7)) == r'2 x\bmod{7}'
assert latex(Mod(x, 7) + 1) == r'\left(x\bmod{7}\right) + 1'
assert latex(2 * Mod(x, 7)) == r'2 \left(x\bmod{7}\right)'
# some unknown function name should get rendered with \operatorname
fjlkd = Function('fjlkd')
assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}'
# even when it is referred to without an argument
assert latex(fjlkd) == r'\operatorname{fjlkd}'
# test that notation passes to subclasses of the same name only
def test_function_subclass_different_name():
class mygamma(gamma):
pass
assert latex(mygamma) == r"\operatorname{mygamma}"
assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}"
def test_hyper_printing():
from sympy import pi
from sympy.abc import x, z
assert latex(meijerg(Tuple(pi, pi, x), Tuple(1),
(0, 1), Tuple(1, 2, 3/pi), z)) == \
r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\
r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}'
assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \
r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}'
assert latex(hyper((x, 2), (3,), z)) == \
r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \
r'\\ 3 \end{matrix}\middle| {z} \right)}'
assert latex(hyper(Tuple(), Tuple(1), z)) == \
r'{{}_{0}F_{1}\left(\begin{matrix} ' \
r'\\ 1 \end{matrix}\middle| {z} \right)}'
def test_latex_bessel():
from sympy.functions.special.bessel import (besselj, bessely, besseli,
besselk, hankel1, hankel2,
jn, yn, hn1, hn2)
from sympy.abc import z
assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)'
assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)'
assert latex(besseli(n, z)) == r'I_{n}\left(z\right)'
assert latex(besselk(n, z)) == r'K_{n}\left(z\right)'
assert latex(hankel1(n, z**2)**2) == \
r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}'
assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)'
assert latex(jn(n, z)) == r'j_{n}\left(z\right)'
assert latex(yn(n, z)) == r'y_{n}\left(z\right)'
assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)'
assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)'
def test_latex_fresnel():
from sympy.functions.special.error_functions import (fresnels, fresnelc)
from sympy.abc import z
assert latex(fresnels(z)) == r'S\left(z\right)'
assert latex(fresnelc(z)) == r'C\left(z\right)'
assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)'
assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)'
def test_latex_brackets():
assert latex((-1)**x) == r"\left(-1\right)^{x}"
def test_latex_indexed():
Psi_symbol = Symbol('Psi_0', complex=True, real=False)
Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False))
symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol))
indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0]))
# \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}}
assert symbol_latex == '\\Psi_{0} \\overline{\\Psi_{0}}'
assert indexed_latex == '\\overline{{\\Psi}_{0}} {\\Psi}_{0}'
# Symbol('gamma') gives r'\gamma'
assert latex(Indexed('x1', Symbol('i'))) == '{x_{1}}_{i}'
assert latex(IndexedBase('gamma')) == r'\gamma'
assert latex(IndexedBase('a b')) == 'a b'
assert latex(IndexedBase('a_b')) == 'a_{b}'
def test_latex_derivatives():
# regular "d" for ordinary derivatives
assert latex(diff(x**3, x, evaluate=False)) == \
r"\frac{d}{d x} x^{3}"
assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \
r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)"
assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\
== \
r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)"
assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \
r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)"
# \partial for partial derivatives
assert latex(diff(sin(x * y), x, evaluate=False)) == \
r"\frac{\partial}{\partial x} \sin{\left(x y \right)}"
assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \
r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)"
assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \
r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)"
assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \
r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)"
# mixed partial derivatives
f = Function("f")
assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \
r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y))
assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \
r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y))
# for negative nested Derivative
assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)'
assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \
r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)'
# use ordinary d when one of the variables has been integrated out
assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \
r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx"
# Derivative wrapped in power:
assert latex(diff(x, x, evaluate=False)**2) == \
r"\left(\frac{d}{d x} x\right)^{2}"
assert latex(diff(f(x), x)**2) == \
r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}"
assert latex(diff(f(x), (x, n))) == \
r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}"
x1 = Symbol('x1')
x2 = Symbol('x2')
assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}'
n1 = Symbol('n1')
assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}'
n2 = Symbol('n2')
assert latex(diff(f(x), (x, Max(n1, n2)))) == \
r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}'
def test_latex_subs():
assert latex(Subs(x*y, (
x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}'
def test_latex_integrals():
assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx"
assert latex(Integral(x**2, (x, 0, 1))) == \
r"\int\limits_{0}^{1} x^{2}\, dx"
assert latex(Integral(x**2, (x, 10, 20))) == \
r"\int\limits_{10}^{20} x^{2}\, dx"
assert latex(Integral(y*x**2, (x, 0, 1), y)) == \
r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy"
assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \
r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}"
assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \
== r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$"
assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx"
assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy"
assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz"
assert latex(Integral(x*y*z*t, x, y, z, t)) == \
r"\iiiint t x y z\, dx\, dy\, dz\, dt"
assert latex(Integral(x, x, x, x, x, x, x)) == \
r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx"
assert latex(Integral(x, x, y, (z, 0, 1))) == \
r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz"
# for negative nested Integral
assert latex(Integral(-Integral(y**2,x),x)) == \
r'\int \left(- \int y^{2}\, dx\right)\, dx'
assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \
r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx'
# fix issue #10806
assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}"
assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz"
assert latex(Integral(x+z/2, z)) == \
r"\int \left(x + \frac{z}{2}\right)\, dz"
assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz"
def test_latex_sets():
for s in (frozenset, set):
assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
assert latex(s(range(1, 13))) == \
r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
s = FiniteSet
assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
assert latex(s(*range(1, 13))) == \
r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
def test_latex_SetExpr():
iv = Interval(1, 3)
se = SetExpr(iv)
assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)"
def test_latex_Range():
assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}'
assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}'
assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}'
assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}'
assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}'
assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}'
assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}'
assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}'
assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}'
assert latex(Range(oo, -oo, -1)) == \
r'\left\{\ldots, 1, 0, -1, \ldots\right\}'
a, b, c = symbols('a:c')
assert latex(Range(a, b, c)) == r'Range\left(a, b, c\right)'
assert latex(Range(a, 10, 1)) == r'Range\left(a, 10, 1\right)'
assert latex(Range(0, b, 1)) == r'Range\left(0, b, 1\right)'
assert latex(Range(0, 10, c)) == r'Range\left(0, 10, c\right)'
def test_latex_sequences():
s1 = SeqFormula(a**2, (0, oo))
s2 = SeqPer((1, 2))
latex_str = r'\left[0, 1, 4, 9, \ldots\right]'
assert latex(s1) == latex_str
latex_str = r'\left[1, 2, 1, 2, \ldots\right]'
assert latex(s2) == latex_str
s3 = SeqFormula(a**2, (0, 2))
s4 = SeqPer((1, 2), (0, 2))
latex_str = r'\left[0, 1, 4\right]'
assert latex(s3) == latex_str
latex_str = r'\left[1, 2, 1\right]'
assert latex(s4) == latex_str
s5 = SeqFormula(a**2, (-oo, 0))
s6 = SeqPer((1, 2), (-oo, 0))
latex_str = r'\left[\ldots, 9, 4, 1, 0\right]'
assert latex(s5) == latex_str
latex_str = r'\left[\ldots, 2, 1, 2, 1\right]'
assert latex(s6) == latex_str
latex_str = r'\left[1, 3, 5, 11, \ldots\right]'
assert latex(SeqAdd(s1, s2)) == latex_str
latex_str = r'\left[1, 3, 5\right]'
assert latex(SeqAdd(s3, s4)) == latex_str
latex_str = r'\left[\ldots, 11, 5, 3, 1\right]'
assert latex(SeqAdd(s5, s6)) == latex_str
latex_str = r'\left[0, 2, 4, 18, \ldots\right]'
assert latex(SeqMul(s1, s2)) == latex_str
latex_str = r'\left[0, 2, 4\right]'
assert latex(SeqMul(s3, s4)) == latex_str
latex_str = r'\left[\ldots, 18, 4, 2, 0\right]'
assert latex(SeqMul(s5, s6)) == latex_str
# Sequences with symbolic limits, issue 12629
s7 = SeqFormula(a**2, (a, 0, x))
latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}'
assert latex(s7) == latex_str
b = Symbol('b')
s8 = SeqFormula(b*a**2, (a, 0, 2))
latex_str = r'\left[0, b, 4 b\right]'
assert latex(s8) == latex_str
def test_latex_FourierSeries():
latex_str = \
r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots'
assert latex(fourier_series(x, (x, -pi, pi))) == latex_str
def test_latex_FormalPowerSeries():
latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}'
assert latex(fps(log(1 + x))) == latex_str
def test_latex_intervals():
a = Symbol('a', real=True)
assert latex(Interval(0, 0)) == r"\left\{0\right\}"
assert latex(Interval(0, a)) == r"\left[0, a\right]"
assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]"
assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]"
assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)"
assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)"
def test_latex_AccumuBounds():
a = Symbol('a', real=True)
assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle"
assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle"
assert latex(AccumBounds(a + 1, a + 2)) == \
r"\left\langle a + 1, a + 2\right\rangle"
def test_latex_emptyset():
assert latex(S.EmptySet) == r"\emptyset"
def test_latex_universalset():
assert latex(S.UniversalSet) == r"\mathbb{U}"
def test_latex_commutator():
A = Operator('A')
B = Operator('B')
comm = Commutator(B, A)
assert latex(comm.doit()) == r"- (A B - B A)"
def test_latex_union():
assert latex(Union(Interval(0, 1), Interval(2, 3))) == \
r"\left[0, 1\right] \cup \left[2, 3\right]"
assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \
r"\left\{1, 2\right\} \cup \left[3, 4\right]"
def test_latex_intersection():
assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \
r"\left[0, 1\right] \cap \left[x, y\right]"
def test_latex_symmetric_difference():
assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7),
evaluate=False)) == \
r'\left[2, 5\right] \triangle \left[4, 7\right]'
def test_latex_Complement():
assert latex(Complement(S.Reals, S.Naturals)) == \
r"\mathbb{R} \setminus \mathbb{N}"
def test_latex_productset():
line = Interval(0, 1)
bigline = Interval(0, 10)
fset = FiniteSet(1, 2, 3)
assert latex(line**2) == r"%s^{2}" % latex(line)
assert latex(line**10) == r"%s^{10}" % latex(line)
assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % (
latex(line), latex(bigline), latex(fset))
def test_set_operators_parenthesis():
a, b, c, d = symbols('a:d')
A = FiniteSet(a)
B = FiniteSet(b)
C = FiniteSet(c)
D = FiniteSet(d)
U1 = Union(A, B, evaluate=False)
U2 = Union(C, D, evaluate=False)
I1 = Intersection(A, B, evaluate=False)
I2 = Intersection(C, D, evaluate=False)
C1 = Complement(A, B, evaluate=False)
C2 = Complement(C, D, evaluate=False)
D1 = SymmetricDifference(A, B, evaluate=False)
D2 = SymmetricDifference(C, D, evaluate=False)
# XXX ProductSet does not support evaluate keyword
P1 = ProductSet(A, B)
P2 = ProductSet(C, D)
assert latex(Intersection(A, U2, evaluate=False)) == \
'\\left\\{a\\right\\} \\cap ' \
'\\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)'
assert latex(Intersection(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\cap \\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)'
assert latex(Intersection(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Intersection(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(Intersection(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\cap \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Union(A, I2, evaluate=False)) == \
'\\left\\{a\\right\\} \\cup ' \
'\\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)'
assert latex(Union(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap ''\\left\\{b\\right\\}\\right) ' \
'\\cup \\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)'
assert latex(Union(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Union(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(Union(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\cup \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(A, C2, evaluate=False)) == \
'\\left\\{a\\right\\} \\setminus \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Complement(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\setminus \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\setminus \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\setminus ' \
'\\left(\\left\\{c\\right\\} \\triangle \\left\\{d\\right\\}\\right)'
assert latex(Complement(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) '\
'\\setminus \\left(\\left\\{c\\right\\} \\times '\
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(A, D2, evaluate=False)) == \
'\\left\\{a\\right\\} \\triangle \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\triangle ' \
'\\left(\\left\\{c\\right\\} \\setminus \\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
# XXX This can be incorrect since cartesian product is not associative
assert latex(ProductSet(A, P2).flatten()) == \
'\\left\\{a\\right\\} \\times \\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}'
assert latex(ProductSet(U1, U2)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\times \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(ProductSet(I1, I2)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\times \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(ProductSet(C1, C2)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(ProductSet(D1, D2)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
def test_latex_Complexes():
assert latex(S.Complexes) == r"\mathbb{C}"
def test_latex_Naturals():
assert latex(S.Naturals) == r"\mathbb{N}"
def test_latex_Naturals0():
assert latex(S.Naturals0) == r"\mathbb{N}_0"
def test_latex_Integers():
assert latex(S.Integers) == r"\mathbb{Z}"
def test_latex_ImageSet():
x = Symbol('x')
assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \
r"\left\{x^{2}\; |\; x \in \mathbb{N}\right\}"
y = Symbol('y')
imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
assert latex(imgset) == \
r"\left\{x + y\; |\; x \in \left\{1, 2, 3\right\} , y \in \left\{3, 4\right\}\right\}"
imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
assert latex(imgset) == \
r"\left\{x + y\; |\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}"
def test_latex_ConditionSet():
x = Symbol('x')
assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \
r"\left\{x \mid x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
r"\left\{x \mid x^{2} = 1 \right\}"
def test_latex_ComplexRegion():
assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\
r"\right)}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
def test_latex_Contains():
x = Symbol('x')
assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
def test_latex_sum():
assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Sum(x**2, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} x^{2}"
assert latex(Sum(x**2 + y, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \
r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}"
def test_latex_product():
assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Product(x**2, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} x^{2}"
assert latex(Product(x**2 + y, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Product(x, (x, -2, 2))**2) == \
r"\left(\prod_{x=-2}^{2} x\right)^{2}"
def test_latex_limits():
assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x"
# issue 8175
f = Function('f')
assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}"
assert latex(Limit(f(x), x, 0, "-")) == \
r"\lim_{x \to 0^-} f{\left(x \right)}"
# issue #10806
assert latex(Limit(f(x), x, 0)**2) == \
r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}"
# bi-directional limit
assert latex(Limit(f(x), x, 0, dir='+-')) == \
r"\lim_{x \to 0} f{\left(x \right)}"
def test_latex_log():
assert latex(log(x)) == r"\log{\left(x \right)}"
assert latex(ln(x)) == r"\log{\left(x \right)}"
assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}"
assert latex(log(x)+log(y)) == \
r"\log{\left(x \right)} + \log{\left(y \right)}"
assert latex(log(x)+log(y), ln_notation=True) == \
r"\ln{\left(x \right)} + \ln{\left(y \right)}"
assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}"
assert latex(pow(log(x), x), ln_notation=True) == \
r"\ln{\left(x \right)}^{x}"
def test_issue_3568():
beta = Symbol(r'\beta')
y = beta + x
assert latex(y) in [r'\beta + x', r'x + \beta']
beta = Symbol(r'beta')
y = beta + x
assert latex(y) in [r'\beta + x', r'x + \beta']
def test_latex():
assert latex((2*tau)**Rational(7, 2)) == "8 \\sqrt{2} \\tau^{\\frac{7}{2}}"
assert latex((2*mu)**Rational(7, 2), mode='equation*') == \
"\\begin{equation*}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation*}"
assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \
"$$8 \\sqrt{2} \\mu^{\\frac{7}{2}}$$"
assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]"
def test_latex_dict():
d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4}
assert latex(d) == \
r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}'
D = Dict(d)
assert latex(D) == \
r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}'
def test_latex_list():
ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')]
assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]'
def test_latex_rational():
# tests issue 3973
assert latex(-Rational(1, 2)) == "- \\frac{1}{2}"
assert latex(Rational(-1, 2)) == "- \\frac{1}{2}"
assert latex(Rational(1, -2)) == "- \\frac{1}{2}"
assert latex(-Rational(-1, 2)) == "\\frac{1}{2}"
assert latex(-Rational(1, 2)*x) == "- \\frac{x}{2}"
assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \
"- \\frac{x}{2} - \\frac{2 y}{3}"
def test_latex_inverse():
# tests issue 4129
assert latex(1/x) == "\\frac{1}{x}"
assert latex(1/(x + y)) == "\\frac{1}{x + y}"
def test_latex_DiracDelta():
assert latex(DiracDelta(x)) == r"\delta\left(x\right)"
assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}"
assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)"
assert latex(DiracDelta(x, 5)) == \
r"\delta^{\left( 5 \right)}\left( x \right)"
assert latex(DiracDelta(x, 5)**2) == \
r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}"
def test_latex_Heaviside():
assert latex(Heaviside(x)) == r"\theta\left(x\right)"
assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}"
def test_latex_KroneckerDelta():
assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}"
assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}"
# issue 6578
assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}"
assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \
r"\left(\delta_{x y}\right)^{2}"
def test_latex_LeviCivita():
assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}"
assert latex(LeviCivita(x, y, z)**2) == \
r"\left(\varepsilon_{x y z}\right)^{2}"
assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}"
assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}"
assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}"
def test_mode():
expr = x + y
assert latex(expr) == 'x + y'
assert latex(expr, mode='plain') == 'x + y'
assert latex(expr, mode='inline') == '$x + y$'
assert latex(
expr, mode='equation*') == '\\begin{equation*}x + y\\end{equation*}'
assert latex(
expr, mode='equation') == '\\begin{equation}x + y\\end{equation}'
raises(ValueError, lambda: latex(expr, mode='foo'))
def test_latex_mathieu():
assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)"
assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)"
assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}"
assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}"
assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)"
assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)"
assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}"
assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}"
def test_latex_Piecewise():
p = Piecewise((x, x < 1), (x**2, True))
assert latex(p) == "\\begin{cases} x & \\text{for}\\: x < 1 \\\\x^{2} &" \
" \\text{otherwise} \\end{cases}"
assert latex(p, itex=True) == \
"\\begin{cases} x & \\text{for}\\: x \\lt 1 \\\\x^{2} &" \
" \\text{otherwise} \\end{cases}"
p = Piecewise((x, x < 0), (0, x >= 0))
assert latex(p) == '\\begin{cases} x & \\text{for}\\: x < 0 \\\\0 &' \
' \\text{otherwise} \\end{cases}'
A, B = symbols("A B", commutative=False)
p = Piecewise((A**2, Eq(A, B)), (A*B, True))
s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}"
assert latex(p) == s
assert latex(A*p) == r"A \left(%s\right)" % s
assert latex(p*A) == r"\left(%s\right) A" % s
assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \
'\\begin{cases} x & ' \
'\\text{for}\\: x < 1 \\\\x^{2} & \\text{for}\\: x < 2 \\end{cases}'
def test_latex_Matrix():
M = Matrix([[1 + x, y], [y, x - 1]])
assert latex(M) == \
r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]'
assert latex(M, mode='inline') == \
r'$\left[\begin{smallmatrix}x + 1 & y\\' \
r'y & x - 1\end{smallmatrix}\right]$'
assert latex(M, mat_str='array') == \
r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]'
assert latex(M, mat_str='bmatrix') == \
r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]'
assert latex(M, mat_delim=None, mat_str='bmatrix') == \
r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}'
M2 = Matrix(1, 11, range(11))
assert latex(M2) == \
r'\left[\begin{array}{ccccccccccc}' \
r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
def test_latex_matrix_with_functions():
t = symbols('t')
theta1 = symbols('theta1', cls=Function)
M = Matrix([[sin(theta1(t)), cos(theta1(t))],
[cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]])
expected = (r'\left[\begin{matrix}\sin{\left('
r'\theta_{1}{\left(t \right)} \right)} & '
r'\cos{\left(\theta_{1}{\left(t \right)} \right)'
r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t '
r'\right)} \right)} & \sin{\left(\frac{d}{d t} '
r'\theta_{1}{\left(t \right)} \right'
r')}\end{matrix}\right]')
assert latex(M) == expected
def test_latex_NDimArray():
x, y, z, w = symbols("x y z w")
for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray):
# Basic: scalar array
M = ArrayType(x)
assert latex(M) == "x"
M = ArrayType([[1 / x, y], [z, w]])
M1 = ArrayType([1 / x, y, z])
M2 = tensorproduct(M1, M)
M3 = tensorproduct(M, M)
assert latex(M) == \
'\\left[\\begin{matrix}\\frac{1}{x} & y\\\\z & w\\end{matrix}\\right]'
assert latex(M1) == \
"\\left[\\begin{matrix}\\frac{1}{x} & y & z\\end{matrix}\\right]"
assert latex(M2) == \
r"\left[\begin{matrix}" \
r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \
r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \
r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \
r"\end{matrix}\right]"
assert latex(M3) == \
r"""\left[\begin{matrix}"""\
r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\
r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\
r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\
r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\
r"""\end{matrix}\right]"""
Mrow = ArrayType([[x, y, 1/z]])
Mcolumn = ArrayType([[x], [y], [1/z]])
Mcol2 = ArrayType([Mcolumn.tolist()])
assert latex(Mrow) == \
r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]"
assert latex(Mcolumn) == \
r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]"
assert latex(Mcol2) == \
r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]'
def test_latex_mul_symbol():
assert latex(4*4**x, mul_symbol='times') == "4 \\times 4^{x}"
assert latex(4*4**x, mul_symbol='dot') == "4 \\cdot 4^{x}"
assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}"
assert latex(4*x, mul_symbol='times') == "4 \\times x"
assert latex(4*x, mul_symbol='dot') == "4 \\cdot x"
assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x"
def test_latex_issue_4381():
y = 4*4**log(2)
assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}'
assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}'
def test_latex_issue_4576():
assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}"
assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}"
assert latex(Symbol("beta_13")) == r"\beta_{13}"
assert latex(Symbol("x_a_b")) == r"x_{a b}"
assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}"
assert latex(Symbol("x_a_b1")) == r"x_{a b1}"
assert latex(Symbol("x_a_1")) == r"x_{a 1}"
assert latex(Symbol("x_1_a")) == r"x_{1 a}"
assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}"
assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}"
assert latex(Symbol("x_11^a")) == r"x^{a}_{11}"
assert latex(Symbol("x_11__a")) == r"x^{a}_{11}"
assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}"
assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}"
assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}"
assert latex(Symbol("alpha_11")) == r"\alpha_{11}"
assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}"
assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}"
assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}"
assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}"
def test_latex_pow_fraction():
x = Symbol('x')
# Testing exp
assert 'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace
# Testing e^{-x} in case future changes alter behavior of muls or fracs
# In particular current output is \frac{1}{2}e^{- x} but perhaps this will
# change to \frac{e^{-x}}{2}
# Testing general, non-exp, power
assert '3^{-x}' in latex(3**-x/2).replace(' ', '')
def test_noncommutative():
A, B, C = symbols('A,B,C', commutative=False)
assert latex(A*B*C**-1) == "A B C^{-1}"
assert latex(C**-1*A*B) == "C^{-1} A B"
assert latex(A*C**-1*B) == "A C^{-1} B"
def test_latex_order():
expr = x**3 + x**2*y + y**4 + 3*x*y**3
assert latex(expr, order='lex') == "x^{3} + x^{2} y + 3 x y^{3} + y^{4}"
assert latex(
expr, order='rev-lex') == "y^{4} + 3 x y^{3} + x^{2} y + x^{3}"
assert latex(expr, order='none') == "x^{3} + y^{4} + y x^{2} + 3 x y^{3}"
def test_latex_Lambda():
assert latex(Lambda(x, x + 1)) == \
r"\left( x \mapsto x + 1 \right)"
assert latex(Lambda((x, y), x + 1)) == \
r"\left( \left( x, \ y\right) \mapsto x + 1 \right)"
assert latex(Lambda(x, x)) == \
r"\left( x \mapsto x \right)"
def test_latex_PolyElement():
Ruv, u, v = ring("u,v", ZZ)
Rxyz, x, y, z = ring("x,y,z", Ruv)
assert latex(x - x) == r"0"
assert latex(x - 1) == r"x - 1"
assert latex(x + 1) == r"x + 1"
assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1"
assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x"
assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1"
assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \
r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1"
assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \
r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1"
assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \
r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1"
def test_latex_FracElement():
Fuv, u, v = field("u,v", ZZ)
Fxyzt, x, y, z, t = field("x,y,z,t", Fuv)
assert latex(x - x) == r"0"
assert latex(x - 1) == r"x - 1"
assert latex(x + 1) == r"x + 1"
assert latex(x/3) == r"\frac{x}{3}"
assert latex(x/z) == r"\frac{x}{z}"
assert latex(x*y/z) == r"\frac{x y}{z}"
assert latex(x/(z*t)) == r"\frac{x}{z t}"
assert latex(x*y/(z*t)) == r"\frac{x y}{z t}"
assert latex((x - 1)/y) == r"\frac{x - 1}{y}"
assert latex((x + 1)/y) == r"\frac{x + 1}{y}"
assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}"
assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}"
assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}"
assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}"
assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \
r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}"
assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \
r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}"
def test_latex_Poly():
assert latex(Poly(x**2 + 2 * x, x)) == \
r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}"
assert latex(Poly(x/y, x)) == \
r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}"
assert latex(Poly(2.0*x + y)) == \
r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}"
def test_latex_Poly_order():
assert latex(Poly([a, 1, b, 2, c, 3], x)) == \
'\\operatorname{Poly}{\\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\
' x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}'
assert latex(Poly([a, 1, b+c, 2, 3], x)) == \
'\\operatorname{Poly}{\\left( a x^{4} + x^{3} + \\left(b + c\\right) '\
'x^{2} + 2 x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}'
assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b,
(x, y))) == \
'\\operatorname{Poly}{\\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\
'a x - c y^{3} + y + b, x, y, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}'
def test_latex_ComplexRootOf():
assert latex(rootof(x**5 + x + 3, 0)) == \
r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}"
def test_latex_RootSum():
assert latex(RootSum(x**5 + x + 3, sin)) == \
r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}"
def test_settings():
raises(TypeError, lambda: latex(x*y, method="garbage"))
def test_latex_numbers():
assert latex(catalan(n)) == r"C_{n}"
assert latex(catalan(n)**2) == r"C_{n}^{2}"
assert latex(bernoulli(n)) == r"B_{n}"
assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)"
assert latex(bernoulli(n)**2) == r"B_{n}^{2}"
assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)"
assert latex(bell(n)) == r"B_{n}"
assert latex(bell(n, x)) == r"B_{n}\left(x\right)"
assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)"
assert latex(bell(n)**2) == r"B_{n}^{2}"
assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)"
assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)"
assert latex(fibonacci(n)) == r"F_{n}"
assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)"
assert latex(fibonacci(n)**2) == r"F_{n}^{2}"
assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)"
assert latex(lucas(n)) == r"L_{n}"
assert latex(lucas(n)**2) == r"L_{n}^{2}"
assert latex(tribonacci(n)) == r"T_{n}"
assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)"
assert latex(tribonacci(n)**2) == r"T_{n}^{2}"
assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)"
def test_latex_euler():
assert latex(euler(n)) == r"E_{n}"
assert latex(euler(n, x)) == r"E_{n}\left(x\right)"
assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)"
def test_lamda():
assert latex(Symbol('lamda')) == r"\lambda"
assert latex(Symbol('Lamda')) == r"\Lambda"
def test_custom_symbol_names():
x = Symbol('x')
y = Symbol('y')
assert latex(x) == "x"
assert latex(x, symbol_names={x: "x_i"}) == "x_i"
assert latex(x + y, symbol_names={x: "x_i"}) == "x_i + y"
assert latex(x**2, symbol_names={x: "x_i"}) == "x_i^{2}"
assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == "x_i + y_j"
def test_matAdd():
from sympy import MatrixSymbol
from sympy.printing.latex import LatexPrinter
C = MatrixSymbol('C', 5, 5)
B = MatrixSymbol('B', 5, 5)
l = LatexPrinter()
assert l._print(C - 2*B) in ['- 2 B + C', 'C -2 B']
assert l._print(C + 2*B) in ['2 B + C', 'C + 2 B']
assert l._print(B - 2*C) in ['B - 2 C', '- 2 C + B']
assert l._print(B + 2*C) in ['B + 2 C', '2 C + B']
def test_matMul():
from sympy import MatrixSymbol
from sympy.printing.latex import LatexPrinter
A = MatrixSymbol('A', 5, 5)
B = MatrixSymbol('B', 5, 5)
x = Symbol('x')
lp = LatexPrinter()
assert lp._print_MatMul(2*A) == '2 A'
assert lp._print_MatMul(2*x*A) == '2 x A'
assert lp._print_MatMul(-2*A) == '- 2 A'
assert lp._print_MatMul(1.5*A) == '1.5 A'
assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A'
assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A'
assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A'
assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)',
r'- 2 A \left(2 B + A\right)']
def test_latex_MatrixSlice():
n = Symbol('n', integer=True)
x, y, z, w, t, = symbols('x y z w t')
X = MatrixSymbol('X', n, n)
Y = MatrixSymbol('Y', 10, 10)
Z = MatrixSymbol('Z', 10, 10)
assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]'
assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]'
assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[x:, :y]) == r'X\left[x:, :y\right]'
assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]'
assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]'
assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]'
assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]'
assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]'
assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]'
assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]'
assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]'
assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]'
assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]'
assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]'
assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]'
assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]'
assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]'
assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]'
def test_latex_RandomDomain():
from sympy.stats import Normal, Die, Exponential, pspace, where
from sympy.stats.rv import RandomDomain
X = Normal('x1', 0, 1)
assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty"
D = Die('d1', 6)
assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6"
A = Exponential('a', 1)
B = Exponential('b', 1)
assert latex(
pspace(Tuple(A, B)).domain) == \
r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty"
assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \
r'\text{Domain: }\left\{x\right\}\text{ in }\left\{1, 2\right\}'
def test_PrettyPoly():
from sympy.polys.domains import QQ
F = QQ.frac_field(x, y)
R = QQ[x, y]
assert latex(F.convert(x/(x + y))) == latex(x/(x + y))
assert latex(R.convert(x + y)) == latex(x + y)
def test_integral_transforms():
x = Symbol("x")
k = Symbol("k")
f = Function("f")
a = Symbol("a")
b = Symbol("b")
assert latex(MellinTransform(f(x), x, k)) == \
r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \
r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(LaplaceTransform(f(x), x, k)) == \
r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \
r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(FourierTransform(f(x), x, k)) == \
r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseFourierTransform(f(k), k, x)) == \
r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(CosineTransform(f(x), x, k)) == \
r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseCosineTransform(f(k), k, x)) == \
r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(SineTransform(f(x), x, k)) == \
r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseSineTransform(f(k), k, x)) == \
r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
def test_PolynomialRingBase():
from sympy.polys.domains import QQ
assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]"
assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \
r"S_<^{-1}\mathbb{Q}\left[x, y\right]"
def test_categories():
from sympy.categories import (Object, IdentityMorphism,
NamedMorphism, Category, Diagram,
DiagramGrid)
A1 = Object("A1")
A2 = Object("A2")
A3 = Object("A3")
f1 = NamedMorphism(A1, A2, "f1")
f2 = NamedMorphism(A2, A3, "f2")
id_A1 = IdentityMorphism(A1)
K1 = Category("K1")
assert latex(A1) == "A_{1}"
assert latex(f1) == "f_{1}:A_{1}\\rightarrow A_{2}"
assert latex(id_A1) == "id:A_{1}\\rightarrow A_{1}"
assert latex(f2*f1) == "f_{2}\\circ f_{1}:A_{1}\\rightarrow A_{3}"
assert latex(K1) == r"\mathbf{K_{1}}"
d = Diagram()
assert latex(d) == r"\emptyset"
d = Diagram({f1: "unique", f2: S.EmptySet})
assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \
r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \
r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \
r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \
r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}"
d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \
r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \
r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \
r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \
r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \
r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \left\{unique\right\}\right\}"
# A linear diagram.
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d = Diagram([f, g])
grid = DiagramGrid(d)
assert latex(grid) == "\\begin{array}{cc}\n" \
"A & B \\\\\n" \
" & C \n" \
"\\end{array}\n"
def test_Modules():
from sympy.polys.domains import QQ
from sympy.polys.agca import homomorphism
R = QQ.old_poly_ring(x, y)
F = R.free_module(2)
M = F.submodule([x, y], [1, x**2])
assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}"
assert latex(M) == \
r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle"
I = R.ideal(x**2, y)
assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle"
Q = F / M
assert latex(Q) == \
r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\
r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}"
assert latex(Q.submodule([1, x**3/2], [2, y])) == \
r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\
r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\
r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\
r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle"
h = homomorphism(QQ.old_poly_ring(x).free_module(2),
QQ.old_poly_ring(x).free_module(2), [0, 0])
assert latex(h) == \
r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\
r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}"
def test_QuotientRing():
from sympy.polys.domains import QQ
R = QQ.old_poly_ring(x)/[x**2 + 1]
assert latex(R) == \
r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}"
assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}"
def test_Tr():
#TODO: Handle indices
A, B = symbols('A B', commutative=False)
t = Tr(A*B)
assert latex(t) == r'\operatorname{tr}\left(A B\right)'
def test_Adjoint():
from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(Adjoint(X)) == r'X^{\dagger}'
assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}'
assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}'
assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}'
assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}'
assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}'
assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}'
assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}'
assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}'
assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}'
assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}'
assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}'
def test_Transpose():
from sympy.matrices import Transpose, MatPow, HadamardPower
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(Transpose(X)) == r'X^{T}'
assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}'
assert latex(Transpose(HadamardPower(X, 2))) == \
r'\left(X^{\circ {2}}\right)^{T}'
assert latex(HadamardPower(Transpose(X), 2)) == \
r'\left(X^{T}\right)^{\circ {2}}'
assert latex(Transpose(MatPow(X, 2))) == \
r'\left(X^{2}\right)^{T}'
assert latex(MatPow(Transpose(X), 2)) == \
r'\left(X^{T}\right)^{2}'
def test_Hadamard():
from sympy.matrices import MatrixSymbol, HadamardProduct, HadamardPower
from sympy.matrices.expressions import MatAdd, MatMul, MatPow
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}'
assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y'
assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}'
assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}'
assert latex(HadamardPower(MatAdd(X, Y), 2)) == \
r'\left(X + Y\right)^{\circ {2}}'
assert latex(HadamardPower(MatMul(X, Y), 2)) == \
r'\left(X Y\right)^{\circ {2}}'
assert latex(HadamardPower(MatPow(X, -1), -1)) == \
r'\left(X^{-1}\right)^{\circ \left({-1}\right)}'
assert latex(MatPow(HadamardPower(X, -1), -1)) == \
r'\left(X^{\circ \left({-1}\right)}\right)^{-1}'
assert latex(HadamardPower(X, n+1)) == \
r'X^{\circ \left({n + 1}\right)}'
def test_ElementwiseApplyFunction():
from sympy.matrices import MatrixSymbol
X = MatrixSymbol('X', 2, 2)
expr = (X.T*X).applyfunc(sin)
assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)"
expr = X.applyfunc(Lambda(x, 1/x))
assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)'
def test_ZeroMatrix():
from sympy import ZeroMatrix
assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"\mathbb{0}"
assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}"
def test_OneMatrix():
from sympy import OneMatrix
assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"\mathbb{1}"
assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}"
def test_Identity():
from sympy import Identity
assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}"
assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}"
def test_boolean_args_order():
syms = symbols('a:f')
expr = And(*syms)
assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f'
expr = Or(*syms)
assert latex(expr) == 'a \\vee b \\vee c \\vee d \\vee e \\vee f'
expr = Equivalent(*syms)
assert latex(expr) == \
'a \\Leftrightarrow b \\Leftrightarrow c \\Leftrightarrow d \\Leftrightarrow e \\Leftrightarrow f'
expr = Xor(*syms)
assert latex(expr) == \
'a \\veebar b \\veebar c \\veebar d \\veebar e \\veebar f'
def test_imaginary():
i = sqrt(-1)
assert latex(i) == r'i'
def test_builtins_without_args():
assert latex(sin) == r'\sin'
assert latex(cos) == r'\cos'
assert latex(tan) == r'\tan'
assert latex(log) == r'\log'
assert latex(Ei) == r'\operatorname{Ei}'
assert latex(zeta) == r'\zeta'
def test_latex_greek_functions():
# bug because capital greeks that have roman equivalents should not use
# \Alpha, \Beta, \Eta, etc.
s = Function('Alpha')
assert latex(s) == r'A'
assert latex(s(x)) == r'A{\left(x \right)}'
s = Function('Beta')
assert latex(s) == r'B'
s = Function('Eta')
assert latex(s) == r'H'
assert latex(s(x)) == r'H{\left(x \right)}'
# bug because sympy.core.numbers.Pi is special
p = Function('Pi')
# assert latex(p(x)) == r'\Pi{\left(x \right)}'
assert latex(p) == r'\Pi'
# bug because not all greeks are included
c = Function('chi')
assert latex(c(x)) == r'\chi{\left(x \right)}'
assert latex(c) == r'\chi'
def test_translate():
s = 'Alpha'
assert translate(s) == 'A'
s = 'Beta'
assert translate(s) == 'B'
s = 'Eta'
assert translate(s) == 'H'
s = 'omicron'
assert translate(s) == 'o'
s = 'Pi'
assert translate(s) == r'\Pi'
s = 'pi'
assert translate(s) == r'\pi'
s = 'LamdaHatDOT'
assert translate(s) == r'\dot{\hat{\Lambda}}'
def test_other_symbols():
from sympy.printing.latex import other_symbols
for s in other_symbols:
assert latex(symbols(s)) == "\\"+s
def test_modifiers():
# Test each modifier individually in the simplest case
# (with funny capitalizations)
assert latex(symbols("xMathring")) == r"\mathring{x}"
assert latex(symbols("xCheck")) == r"\check{x}"
assert latex(symbols("xBreve")) == r"\breve{x}"
assert latex(symbols("xAcute")) == r"\acute{x}"
assert latex(symbols("xGrave")) == r"\grave{x}"
assert latex(symbols("xTilde")) == r"\tilde{x}"
assert latex(symbols("xPrime")) == r"{x}'"
assert latex(symbols("xddDDot")) == r"\ddddot{x}"
assert latex(symbols("xDdDot")) == r"\dddot{x}"
assert latex(symbols("xDDot")) == r"\ddot{x}"
assert latex(symbols("xBold")) == r"\boldsymbol{x}"
assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|"
assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle"
assert latex(symbols("xHat")) == r"\hat{x}"
assert latex(symbols("xDot")) == r"\dot{x}"
assert latex(symbols("xBar")) == r"\bar{x}"
assert latex(symbols("xVec")) == r"\vec{x}"
assert latex(symbols("xAbs")) == r"\left|{x}\right|"
assert latex(symbols("xMag")) == r"\left|{x}\right|"
assert latex(symbols("xPrM")) == r"{x}'"
assert latex(symbols("xBM")) == r"\boldsymbol{x}"
# Test strings that are *only* the names of modifiers
assert latex(symbols("Mathring")) == r"Mathring"
assert latex(symbols("Check")) == r"Check"
assert latex(symbols("Breve")) == r"Breve"
assert latex(symbols("Acute")) == r"Acute"
assert latex(symbols("Grave")) == r"Grave"
assert latex(symbols("Tilde")) == r"Tilde"
assert latex(symbols("Prime")) == r"Prime"
assert latex(symbols("DDot")) == r"\dot{D}"
assert latex(symbols("Bold")) == r"Bold"
assert latex(symbols("NORm")) == r"NORm"
assert latex(symbols("AVG")) == r"AVG"
assert latex(symbols("Hat")) == r"Hat"
assert latex(symbols("Dot")) == r"Dot"
assert latex(symbols("Bar")) == r"Bar"
assert latex(symbols("Vec")) == r"Vec"
assert latex(symbols("Abs")) == r"Abs"
assert latex(symbols("Mag")) == r"Mag"
assert latex(symbols("PrM")) == r"PrM"
assert latex(symbols("BM")) == r"BM"
assert latex(symbols("hbar")) == r"\hbar"
# Check a few combinations
assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}"
assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|"
# Check a couple big, ugly combinations
assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \
r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \
r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
def test_greek_symbols():
assert latex(Symbol('alpha')) == r'\alpha'
assert latex(Symbol('beta')) == r'\beta'
assert latex(Symbol('gamma')) == r'\gamma'
assert latex(Symbol('delta')) == r'\delta'
assert latex(Symbol('epsilon')) == r'\epsilon'
assert latex(Symbol('zeta')) == r'\zeta'
assert latex(Symbol('eta')) == r'\eta'
assert latex(Symbol('theta')) == r'\theta'
assert latex(Symbol('iota')) == r'\iota'
assert latex(Symbol('kappa')) == r'\kappa'
assert latex(Symbol('lambda')) == r'\lambda'
assert latex(Symbol('mu')) == r'\mu'
assert latex(Symbol('nu')) == r'\nu'
assert latex(Symbol('xi')) == r'\xi'
assert latex(Symbol('omicron')) == r'o'
assert latex(Symbol('pi')) == r'\pi'
assert latex(Symbol('rho')) == r'\rho'
assert latex(Symbol('sigma')) == r'\sigma'
assert latex(Symbol('tau')) == r'\tau'
assert latex(Symbol('upsilon')) == r'\upsilon'
assert latex(Symbol('phi')) == r'\phi'
assert latex(Symbol('chi')) == r'\chi'
assert latex(Symbol('psi')) == r'\psi'
assert latex(Symbol('omega')) == r'\omega'
assert latex(Symbol('Alpha')) == r'A'
assert latex(Symbol('Beta')) == r'B'
assert latex(Symbol('Gamma')) == r'\Gamma'
assert latex(Symbol('Delta')) == r'\Delta'
assert latex(Symbol('Epsilon')) == r'E'
assert latex(Symbol('Zeta')) == r'Z'
assert latex(Symbol('Eta')) == r'H'
assert latex(Symbol('Theta')) == r'\Theta'
assert latex(Symbol('Iota')) == r'I'
assert latex(Symbol('Kappa')) == r'K'
assert latex(Symbol('Lambda')) == r'\Lambda'
assert latex(Symbol('Mu')) == r'M'
assert latex(Symbol('Nu')) == r'N'
assert latex(Symbol('Xi')) == r'\Xi'
assert latex(Symbol('Omicron')) == r'O'
assert latex(Symbol('Pi')) == r'\Pi'
assert latex(Symbol('Rho')) == r'P'
assert latex(Symbol('Sigma')) == r'\Sigma'
assert latex(Symbol('Tau')) == r'T'
assert latex(Symbol('Upsilon')) == r'\Upsilon'
assert latex(Symbol('Phi')) == r'\Phi'
assert latex(Symbol('Chi')) == r'X'
assert latex(Symbol('Psi')) == r'\Psi'
assert latex(Symbol('Omega')) == r'\Omega'
assert latex(Symbol('varepsilon')) == r'\varepsilon'
assert latex(Symbol('varkappa')) == r'\varkappa'
assert latex(Symbol('varphi')) == r'\varphi'
assert latex(Symbol('varpi')) == r'\varpi'
assert latex(Symbol('varrho')) == r'\varrho'
assert latex(Symbol('varsigma')) == r'\varsigma'
assert latex(Symbol('vartheta')) == r'\vartheta'
def test_fancyset_symbols():
assert latex(S.Rationals) == '\\mathbb{Q}'
assert latex(S.Naturals) == '\\mathbb{N}'
assert latex(S.Naturals0) == '\\mathbb{N}_0'
assert latex(S.Integers) == '\\mathbb{Z}'
assert latex(S.Reals) == '\\mathbb{R}'
assert latex(S.Complexes) == '\\mathbb{C}'
@XFAIL
def test_builtin_without_args_mismatched_names():
assert latex(CosineTransform) == r'\mathcal{COS}'
def test_builtin_no_args():
assert latex(Chi) == r'\operatorname{Chi}'
assert latex(beta) == r'\operatorname{B}'
assert latex(gamma) == r'\Gamma'
assert latex(KroneckerDelta) == r'\delta'
assert latex(DiracDelta) == r'\delta'
assert latex(lowergamma) == r'\gamma'
def test_issue_6853():
p = Function('Pi')
assert latex(p(x)) == r"\Pi{\left(x \right)}"
def test_Mul():
e = Mul(-2, x + 1, evaluate=False)
assert latex(e) == r'- 2 \left(x + 1\right)'
e = Mul(2, x + 1, evaluate=False)
assert latex(e) == r'2 \left(x + 1\right)'
e = Mul(S.Half, x + 1, evaluate=False)
assert latex(e) == r'\frac{x + 1}{2}'
e = Mul(y, x + 1, evaluate=False)
assert latex(e) == r'y \left(x + 1\right)'
e = Mul(-y, x + 1, evaluate=False)
assert latex(e) == r'- y \left(x + 1\right)'
e = Mul(-2, x + 1)
assert latex(e) == r'- 2 x - 2'
e = Mul(2, x + 1)
assert latex(e) == r'2 x + 2'
def test_Pow():
e = Pow(2, 2, evaluate=False)
assert latex(e) == r'2^{2}'
assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}'
x2 = Symbol(r'x^2')
assert latex(x2**2) == r'\left(x^{2}\right)^{2}'
def test_issue_7180():
assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y"
assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y"
def test_issue_8409():
assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}"
def test_issue_8470():
from sympy.parsing.sympy_parser import parse_expr
e = parse_expr("-B*A", evaluate=False)
assert latex(e) == r"A \left(- B\right)"
def test_issue_15439():
x = MatrixSymbol('x', 2, 2)
y = MatrixSymbol('y', 2, 2)
assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)"
assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)"
assert latex((x * y).subs(x, -x)) == r"- x y"
def test_issue_2934():
assert latex(Symbol(r'\frac{a_1}{b_1}')) == '\\frac{a_1}{b_1}'
def test_issue_10489():
latexSymbolWithBrace = 'C_{x_{0}}'
s = Symbol(latexSymbolWithBrace)
assert latex(s) == latexSymbolWithBrace
assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}'
def test_issue_12886():
m__1, l__1 = symbols('m__1, l__1')
assert latex(m__1**2 + l__1**2) == \
r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}'
def test_issue_13559():
from sympy.parsing.sympy_parser import parse_expr
expr = parse_expr('5/1', evaluate=False)
assert latex(expr) == r"\frac{5}{1}"
def test_issue_13651():
expr = c + Mul(-1, a + b, evaluate=False)
assert latex(expr) == r"c - \left(a + b\right)"
def test_latex_UnevaluatedExpr():
x = symbols("x")
he = UnevaluatedExpr(1/x)
assert latex(he) == latex(1/x) == r"\frac{1}{x}"
assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}"
assert latex(he + 1) == r"1 + \frac{1}{x}"
assert latex(x*he) == r"x \frac{1}{x}"
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert latex(A[0, 0]) == r"A_{0, 0}"
assert latex(3 * A[0, 0]) == r"3 A_{0, 0}"
F = C[0, 0].subs(C, A - B)
assert latex(F) == r"\left(A - B\right)_{0, 0}"
i, j, k = symbols("i j k")
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
assert latex((M*N)[i, j]) == \
r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}'
def test_MatrixSymbol_printing():
# test cases for issue #14237
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert latex(-A) == r"- A"
assert latex(A - A*B - B) == r"A - A B - B"
assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B"
def test_KroneckerProduct_printing():
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 2, 2)
assert latex(KroneckerProduct(A, B)) == r'A \otimes B'
def test_Series_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert latex(Series(tf1, tf2)) == \
'\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right)'
assert latex(Series(tf1, tf2, tf3)) == \
'\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right) \\left(\\frac{t x^{2} - t^{w} x + w}{t - y}\\right)'
assert latex(Series(-tf2, tf1)) == \
'\\left(\\frac{- x + y}{x + y}\\right) \\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right)'
def test_TransferFunction_printing():
tf1 = TransferFunction(x - 1, x + 1, x)
assert latex(tf1) == r"\frac{x - 1}{x + 1}"
tf2 = TransferFunction(x + 1, 2 - y, x)
assert latex(tf2) == r"\frac{x + 1}{2 - y}"
tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}"
def test_Parallel_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
assert latex(Parallel(tf1, tf2)) == \
'\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right)'
assert latex(Parallel(-tf2, tf1)) == \
'\\left(\\frac{- x + y}{x + y}\\right) \\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right)'
def test_Feedback_printing():
tf1 = TransferFunction(p, p + x, p)
tf2 = TransferFunction(-s + p, p + s, p)
assert latex(Feedback(tf1, tf2)) == \
'\\frac{\\frac{p}{p + x}}{\\left(1 \\cdot 1^{-1}\\right) \\left(\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)\\right)}'
assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \
'\\frac{\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)}{\\left(1 \\cdot 1^{-1}\\right) \\left(\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)\\right)}'
def test_Quaternion_latex_printing():
q = Quaternion(x, y, z, t)
assert latex(q) == "x + y i + z j + t k"
q = Quaternion(x, y, z, x*t)
assert latex(q) == "x + y i + z j + t x k"
q = Quaternion(x, y, z, x + t)
assert latex(q) == r"x + y i + z j + \left(t + x\right) k"
def test_TensorProduct_printing():
from sympy.tensor.functions import TensorProduct
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
assert latex(TensorProduct(A, B)) == r"A \otimes B"
def test_WedgeProduct_printing():
from sympy.diffgeom.rn import R2
from sympy.diffgeom import WedgeProduct
wp = WedgeProduct(R2.dx, R2.dy)
assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y"
def test_issue_9216():
expr_1 = Pow(1, -1, evaluate=False)
assert latex(expr_1) == r"1^{-1}"
expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False)
assert latex(expr_2) == r"1^{1^{-1}}"
expr_3 = Pow(3, -2, evaluate=False)
assert latex(expr_3) == r"\frac{1}{9}"
expr_4 = Pow(1, -2, evaluate=False)
assert latex(expr_4) == r"1^{-2}"
def test_latex_printer_tensor():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads
L = TensorIndexType("L")
i, j, k, l = tensor_indices("i j k l", L)
i0 = tensor_indices("i_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L, L, L, L])
assert latex(i) == "{}^{i}"
assert latex(-i) == "{}_{i}"
expr = A(i)
assert latex(expr) == "A{}^{i}"
expr = A(i0)
assert latex(expr) == "A{}^{i_{0}}"
expr = A(-i)
assert latex(expr) == "A{}_{i}"
expr = -3*A(i)
assert latex(expr) == r"-3A{}^{i}"
expr = K(i, j, -k, -i0)
assert latex(expr) == "K{}^{ij}{}_{ki_{0}}"
expr = K(i, -j, -k, i0)
assert latex(expr) == "K{}^{i}{}_{jk}{}^{i_{0}}"
expr = K(i, -j, k, -i0)
assert latex(expr) == "K{}^{i}{}_{j}{}^{k}{}_{i_{0}}"
expr = H(i, -j)
assert latex(expr) == "H{}^{i}{}_{j}"
expr = H(i, j)
assert latex(expr) == "H{}^{ij}"
expr = H(-i, -j)
assert latex(expr) == "H{}_{ij}"
expr = (1+x)*A(i)
assert latex(expr) == r"\left(x + 1\right)A{}^{i}"
expr = H(i, -i)
assert latex(expr) == "H{}^{L_{0}}{}_{L_{0}}"
expr = H(i, -j)*A(j)*B(k)
assert latex(expr) == "H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}"
expr = A(i) + 3*B(i)
assert latex(expr) == "3B{}^{i} + A{}^{i}"
# Test ``TensorElement``:
from sympy.tensor.tensor import TensorElement
expr = TensorElement(K(i, j, k, l), {i: 3, k: 2})
assert latex(expr) == 'K{}^{i=3,j,k=2,l}'
expr = TensorElement(K(i, j, k, l), {i: 3})
assert latex(expr) == 'K{}^{i=3,jkl}'
expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2})
assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2,l}'
expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2})
assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2})
assert latex(expr) == 'K{}^{i=3,j}{}_{k=2,l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3})
assert latex(expr) == 'K{}^{i=3,j}{}_{kl}'
expr = PartialDerivative(A(i), A(i))
assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}"
expr = PartialDerivative(A(-i), A(-j))
assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}"
expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}"
expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}"
expr = PartialDerivative(3*A(-i), A(-j), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}"
def test_multiline_latex():
a, b, c, d, e, f = symbols('a b c d e f')
expr = -a + 2*b -3*c +4*d -5*e
expected = r"\begin{eqnarray}" + "\n"\
r"f & = &- a \nonumber\\" + "\n"\
r"& & + 2 b \nonumber\\" + "\n"\
r"& & - 3 c \nonumber\\" + "\n"\
r"& & + 4 d \nonumber\\" + "\n"\
r"& & - 5 e " + "\n"\
r"\end{eqnarray}"
assert multiline_latex(f, expr, environment="eqnarray") == expected
expected2 = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b \nonumber\\' + '\n'\
r'& & - 3 c + 4 d \nonumber\\' + '\n'\
r'& & - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2
expected3 = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\
r'& & + 4 d - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3
expected3dots = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\
r'& & + 4 d - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots
expected3align = r'\begin{align*}' + '\n'\
r'f = &- a + 2 b - 3 c \\'+ '\n'\
r'& + 4 d - 5 e ' + '\n'\
r'\end{align*}'
assert multiline_latex(f, expr, 3) == expected3align
assert multiline_latex(f, expr, 3, environment='align*') == expected3align
expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\
r'f & = &- a + 2 b \nonumber\\' + '\n'\
r'& & - 3 c + 4 d \nonumber\\' + '\n'\
r'& & - 5 e ' + '\n'\
r'\end{IEEEeqnarray}'
assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee
raises(ValueError, lambda: multiline_latex(f, expr, environment="foo"))
def test_issue_15353():
from sympy import ConditionSet, Tuple, S, sin, cos
a, x = symbols('a x')
# Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a])
sol = ConditionSet(
Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2)
assert latex(sol) == \
r'\left\{\left( x, \ a\right) \mid \left( x, \ a\right) \in ' \
r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \
r'\cos{\left(a x \right)} = 0 \right\}'
def test_trace():
# Issue 15303
from sympy import trace
A = MatrixSymbol("A", 2, 2)
assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)"
assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)"
def test_print_basic():
# Issue 15303
from sympy import Basic, Expr
# dummy class for testing printing where the function is not
# implemented in latex.py
class UnimplementedExpr(Expr):
def __new__(cls, e):
return Basic.__new__(cls, e)
# dummy function for testing
def unimplemented_expr(expr):
return UnimplementedExpr(expr).doit()
# override class name to use superscript / subscript
def unimplemented_expr_sup_sub(expr):
result = UnimplementedExpr(expr)
result.__class__.__name__ = 'UnimplementedExpr_x^1'
return result
assert latex(unimplemented_expr(x)) == r'UnimplementedExpr\left(x\right)'
assert latex(unimplemented_expr(x**2)) == \
r'UnimplementedExpr\left(x^{2}\right)'
assert latex(unimplemented_expr_sup_sub(x)) == \
r'UnimplementedExpr^{1}_{x}\left(x\right)'
def test_MatrixSymbol_bold():
# Issue #15871
from sympy import trace
A = MatrixSymbol("A", 2, 2)
assert latex(trace(A), mat_symbol_style='bold') == \
r"\operatorname{tr}\left(\mathbf{A} \right)"
assert latex(trace(A), mat_symbol_style='plain') == \
r"\operatorname{tr}\left(A \right)"
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}"
assert latex(A - A*B - B, mat_symbol_style='bold') == \
r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}"
assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \
r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}"
A_k = MatrixSymbol("A_k", 3, 3)
assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}"
A = MatrixSymbol(r"\nabla_k", 3, 3)
assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}"
def test_AppliedPermutation():
p = Permutation(0, 1, 2)
x = Symbol('x')
assert latex(AppliedPermutation(p, x)) == \
r'\sigma_{\left( 0\; 1\; 2\right)}(x)'
def test_PermutationMatrix():
p = Permutation(0, 1, 2)
assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}'
p = Permutation(0, 3)(1, 2)
assert latex(PermutationMatrix(p)) == \
r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}'
def test_imaginary_unit():
assert latex(1 + I) == '1 + i'
assert latex(1 + I, imaginary_unit='i') == '1 + i'
assert latex(1 + I, imaginary_unit='j') == '1 + j'
assert latex(1 + I, imaginary_unit='foo') == '1 + foo'
assert latex(I, imaginary_unit="ti") == '\\text{i}'
assert latex(I, imaginary_unit="tj") == '\\text{j}'
def test_text_re_im():
assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}'
assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}'
assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}'
assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}'
def test_latex_diffgeom():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
from sympy.diffgeom.rn import R2
x,y = symbols('x y', real=True)
m = Manifold('M', 2)
assert latex(m) == r'\text{M}'
p = Patch('P', m)
assert latex(p) == r'\text{P}_{\text{M}}'
rect = CoordSystem('rect', p, [x, y])
assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}'
b = BaseScalarField(rect, 0)
assert latex(b) == r'\mathbf{x}'
g = Function('g')
s_field = g(R2.x, R2.y)
assert latex(Differential(s_field)) == \
r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)'
def test_unit_printing():
assert latex(5*meter) == r'5 \text{m}'
assert latex(3*gibibyte) == r'3 \text{gibibyte}'
assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}'
def test_issue_17092():
x_star = Symbol('x^*')
assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}'
def test_latex_decimal_separator():
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
# comma decimal_separator
assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]')
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}')
assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)')
assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)')
# period decimal_separator
assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' )
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}')
assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)')
assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)')
# default decimal_separator
assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]')
assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}')
assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)')
assert(latex((1,)) == r'\left( 1,\right)')
assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') ==r'18{,}02')
assert(latex(3.4*5.3, decimal_separator = 'comma')==r'18{,}02')
x = symbols('x')
y = symbols('y')
z = symbols('z')
assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma')== r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5')
assert(latex(0.987, decimal_separator='comma') == r'0{,}987')
assert(latex(S(0.987), decimal_separator='comma')== r'0{,}987')
assert(latex(.3, decimal_separator='comma')== r'0{,}3')
assert(latex(S(.3), decimal_separator='comma')== r'0{,}3')
assert(latex(5.8*10**(-7), decimal_separator='comma') ==r'5{,}8 \cdot 10^{-7}')
assert(latex(S(5.7)*10**(-7), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}')
assert(latex(S(5.7*10**(-7)), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}')
x = symbols('x')
assert(latex(1.2*x+3.4, decimal_separator='comma')==r'1{,}2 x + 3{,}4')
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period')==r'\left\{1, 2.3, 4.5\right\}')
# Error Handling tests
raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list'))
raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set'))
raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple'))
def test_Str():
from sympy.core.symbol import Str
assert str(Str('x')) == 'x'
def test_latex_escape():
assert latex_escape(r"~^\&%$#_{}") == "".join([
r'\textasciitilde',
r'\textasciicircum',
r'\textbackslash',
r'\&',
r'\%',
r'\$',
r'\#',
r'\_',
r'\{',
r'\}',
])
def test_emptyPrinter():
class MyObject:
def __repr__(self):
return "<MyObject with {...}>"
# unknown objects are monospaced
assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}"
# even if they are nested within other objects
assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)"
def test_global_settings():
import inspect
# settings should be visible in the signature of `latex`
assert inspect.signature(latex).parameters['imaginary_unit'].default == 'i'
assert latex(I) == 'i'
try:
# but changing the defaults...
LatexPrinter.set_global_settings(imaginary_unit='j')
# ... should change the signature
assert inspect.signature(latex).parameters['imaginary_unit'].default == 'j'
assert latex(I) == 'j'
finally:
# there's no public API to undo this, but we need to make sure we do
# so as not to impact other tests
del LatexPrinter._global_settings['imaginary_unit']
# check we really did undo it
assert inspect.signature(latex).parameters['imaginary_unit'].default == 'i'
assert latex(I) == 'i'
def test_pickleable():
# this tests that the _PrintFunction instance is pickleable
import pickle
assert pickle.loads(pickle.dumps(latex)) is latex
|
cdb156dee5d367ea78303361f33bcddda38188c67d991181954b93230c248d14 | # -*- coding: utf-8 -*-
from sympy import (
Add, And, Basic, Derivative, Dict, Eq, Equivalent, FF,
FiniteSet, Function, Ge, Gt, I, Implies, Integral, SingularityFunction,
Lambda, Le, Limit, Lt, Matrix, Mul, Nand, Ne, Nor, Not, O, Or,
Pow, Product, QQ, RR, Rational, Ray, rootof, RootSum, S,
Segment, Subs, Sum, Symbol, Tuple, Trace, Xor, ZZ, conjugate,
groebner, oo, pi, symbols, ilex, grlex, Range, Contains,
SeqPer, SeqFormula, SeqAdd, SeqMul, fourier_series, fps, ITE,
Complement, Interval, Intersection, Union, EulerGamma, GoldenRatio,
LambertW, airyai, airybi, airyaiprime, airybiprime, fresnelc, fresnels,
Heaviside, dirichlet_eta, diag, MatrixSlice)
from sympy.codegen.ast import (Assignment, AddAugmentedAssignment,
SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment)
from sympy.core.expr import UnevaluatedExpr
from sympy.core.trace import Tr
from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta,
Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos,
euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log,
meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi,
elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell,
bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus,
mathieusprime, mathieucprime)
from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct
from sympy.matrices.expressions import hadamard_power
from sympy.physics import mechanics
from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback
from sympy.physics.units import joule, degree
from sympy.printing.pretty import pprint, pretty as xpretty
from sympy.printing.pretty.pretty_symbology import center_accent, is_combining
from sympy import ConditionSet
from sympy.sets import ImageSet, ProductSet
from sympy.sets.setexpr import SetExpr
from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct)
from sympy.tensor.functions import TensorProduct
from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead,
TensorElement, tensor_heads)
from sympy.testing.pytest import raises
from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian
import sympy as sym
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
a, b, c, d, x, y, z, k, n, s, p = symbols('a,b,c,d,x,y,z,k,n,s,p')
f = Function("f")
th = Symbol('theta')
ph = Symbol('phi')
"""
Expressions whose pretty-printing is tested here:
(A '#' to the right of an expression indicates that its various acceptable
orderings are accounted for by the tests.)
BASIC EXPRESSIONS:
oo
(x**2)
1/x
y*x**-2
x**Rational(-5,2)
(-2)**x
Pow(3, 1, evaluate=False)
(x**2 + x + 1) #
1-x #
1-2*x #
x/y
-x/y
(x+2)/y #
(1+x)*y #3
-5*x/(x+10) # correct placement of negative sign
1 - Rational(3,2)*(x+1)
-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524
ORDERING:
x**2 + x + 1
1 - x
1 - 2*x
2*x**4 + y**2 - x**2 + y**3
RELATIONAL:
Eq(x, y)
Lt(x, y)
Gt(x, y)
Le(x, y)
Ge(x, y)
Ne(x/(y+1), y**2) #
RATIONAL NUMBERS:
y*x**-2
y**Rational(3,2) * x**Rational(-5,2)
sin(x)**3/tan(x)**2
FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING):
(2*x + exp(x)) #
Abs(x)
Abs(x/(x**2+1)) #
Abs(1 / (y - Abs(x)))
factorial(n)
factorial(2*n)
subfactorial(n)
subfactorial(2*n)
factorial(factorial(factorial(n)))
factorial(n+1) #
conjugate(x)
conjugate(f(x+1)) #
f(x)
f(x, y)
f(x/(y+1), y) #
f(x**x**x**x**x**x)
sin(x)**2
conjugate(a+b*I)
conjugate(exp(a+b*I))
conjugate( f(1 + conjugate(f(x))) ) #
f(x/(y+1), y) # denom of first arg
floor(1 / (y - floor(x)))
ceiling(1 / (y - ceiling(x)))
SQRT:
sqrt(2)
2**Rational(1,3)
2**Rational(1,1000)
sqrt(x**2 + 1)
(1 + sqrt(5))**Rational(1,3)
2**(1/x)
sqrt(2+pi)
(2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2)
DERIVATIVES:
Derivative(log(x), x, evaluate=False)
Derivative(log(x), x, evaluate=False) + x #
Derivative(log(x) + x**2, x, y, evaluate=False)
Derivative(2*x*y, y, x, evaluate=False) + x**2 #
beta(alpha).diff(alpha)
INTEGRALS:
Integral(log(x), x)
Integral(x**2, x)
Integral((sin(x))**2 / (tan(x))**2)
Integral(x**(2**x), x)
Integral(x**2, (x,1,2))
Integral(x**2, (x,Rational(1,2),10))
Integral(x**2*y**2, x,y)
Integral(x**2, (x, None, 1))
Integral(x**2, (x, 1, None))
Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi))
MATRICES:
Matrix([[x**2+1, 1], [y, x+y]]) #
Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
PIECEWISE:
Piecewise((x,x<1),(x**2,True))
ITE:
ITE(x, y, z)
SEQUENCES (TUPLES, LISTS, DICTIONARIES):
()
[]
{}
(1/x,)
[x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
{x: sin(x)}
{1/x: 1/y, x: sin(x)**2} #
[x**2]
(x**2,)
{x**2: 1}
LIMITS:
Limit(x, x, oo)
Limit(x**2, x, 0)
Limit(1/x, x, 0)
Limit(sin(x)/x, x, 0)
UNITS:
joule => kg*m**2/s
SUBS:
Subs(f(x), x, ph**2)
Subs(f(x).diff(x), x, 0)
Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
ORDER:
O(1)
O(1/x)
O(x**2 + y**2)
"""
def pretty(expr, order=None):
"""ASCII pretty-printing"""
return xpretty(expr, order=order, use_unicode=False, wrap_line=False)
def upretty(expr, order=None):
"""Unicode pretty-printing"""
return xpretty(expr, order=order, use_unicode=True, wrap_line=False)
def test_pretty_ascii_str():
assert pretty( 'xxx' ) == 'xxx'
assert pretty( "xxx" ) == 'xxx'
assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx'
assert pretty( 'xxx"xxx' ) == 'xxx\"xxx'
assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx'
assert pretty( "xxx'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\"xxx" ) == 'xxx\"xxx'
assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx'
assert pretty( "xxx\nxxx" ) == 'xxx\nxxx'
def test_pretty_unicode_str():
assert pretty( 'xxx' ) == 'xxx'
assert pretty( 'xxx' ) == 'xxx'
assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx'
assert pretty( 'xxx"xxx' ) == 'xxx\"xxx'
assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx'
assert pretty( "xxx'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\"xxx" ) == 'xxx\"xxx'
assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx'
assert pretty( "xxx\nxxx" ) == 'xxx\nxxx'
def test_upretty_greek():
assert upretty( oo ) == '∞'
assert upretty( Symbol('alpha^+_1') ) == 'α⁺₁'
assert upretty( Symbol('beta') ) == 'β'
assert upretty(Symbol('lambda')) == 'λ'
def test_upretty_multiindex():
assert upretty( Symbol('beta12') ) == 'β₁₂'
assert upretty( Symbol('Y00') ) == 'Y₀₀'
assert upretty( Symbol('Y_00') ) == 'Y₀₀'
assert upretty( Symbol('F^+-') ) == 'F⁺⁻'
def test_upretty_sub_super():
assert upretty( Symbol('beta_1_2') ) == 'β₁ ₂'
assert upretty( Symbol('beta^1^2') ) == 'β¹ ²'
assert upretty( Symbol('beta_1^2') ) == 'β²₁'
assert upretty( Symbol('beta_10_20') ) == 'β₁₀ ₂₀'
assert upretty( Symbol('beta_ax_gamma^i') ) == 'βⁱₐₓ ᵧ'
assert upretty( Symbol("F^1^2_3_4") ) == 'F¹ ²₃ ₄'
assert upretty( Symbol("F_1_2^3^4") ) == 'F³ ⁴₁ ₂'
assert upretty( Symbol("F_1_2_3_4") ) == 'F₁ ₂ ₃ ₄'
assert upretty( Symbol("F^1^2^3^4") ) == 'F¹ ² ³ ⁴'
def test_upretty_subs_missing_in_24():
assert upretty( Symbol('F_beta') ) == 'Fᵦ'
assert upretty( Symbol('F_gamma') ) == 'Fᵧ'
assert upretty( Symbol('F_rho') ) == 'Fᵨ'
assert upretty( Symbol('F_phi') ) == 'Fᵩ'
assert upretty( Symbol('F_chi') ) == 'Fᵪ'
assert upretty( Symbol('F_a') ) == 'Fₐ'
assert upretty( Symbol('F_e') ) == 'Fₑ'
assert upretty( Symbol('F_i') ) == 'Fᵢ'
assert upretty( Symbol('F_o') ) == 'Fₒ'
assert upretty( Symbol('F_u') ) == 'Fᵤ'
assert upretty( Symbol('F_r') ) == 'Fᵣ'
assert upretty( Symbol('F_v') ) == 'Fᵥ'
assert upretty( Symbol('F_x') ) == 'Fₓ'
def test_missing_in_2X_issue_9047():
assert upretty( Symbol('F_h') ) == 'Fₕ'
assert upretty( Symbol('F_k') ) == 'Fₖ'
assert upretty( Symbol('F_l') ) == 'Fₗ'
assert upretty( Symbol('F_m') ) == 'Fₘ'
assert upretty( Symbol('F_n') ) == 'Fₙ'
assert upretty( Symbol('F_p') ) == 'Fₚ'
assert upretty( Symbol('F_s') ) == 'Fₛ'
assert upretty( Symbol('F_t') ) == 'Fₜ'
def test_upretty_modifiers():
# Accents
assert upretty( Symbol('Fmathring') ) == 'F̊'
assert upretty( Symbol('Fddddot') ) == 'F⃜'
assert upretty( Symbol('Fdddot') ) == 'F⃛'
assert upretty( Symbol('Fddot') ) == 'F̈'
assert upretty( Symbol('Fdot') ) == 'Ḟ'
assert upretty( Symbol('Fcheck') ) == 'F̌'
assert upretty( Symbol('Fbreve') ) == 'F̆'
assert upretty( Symbol('Facute') ) == 'F́'
assert upretty( Symbol('Fgrave') ) == 'F̀'
assert upretty( Symbol('Ftilde') ) == 'F̃'
assert upretty( Symbol('Fhat') ) == 'F̂'
assert upretty( Symbol('Fbar') ) == 'F̅'
assert upretty( Symbol('Fvec') ) == 'F⃗'
assert upretty( Symbol('Fprime') ) == 'F′'
assert upretty( Symbol('Fprm') ) == 'F′'
# No faces are actually implemented, but test to make sure the modifiers are stripped
assert upretty( Symbol('Fbold') ) == 'Fbold'
assert upretty( Symbol('Fbm') ) == 'Fbm'
assert upretty( Symbol('Fcal') ) == 'Fcal'
assert upretty( Symbol('Fscr') ) == 'Fscr'
assert upretty( Symbol('Ffrak') ) == 'Ffrak'
# Brackets
assert upretty( Symbol('Fnorm') ) == '‖F‖'
assert upretty( Symbol('Favg') ) == '⟨F⟩'
assert upretty( Symbol('Fabs') ) == '|F|'
assert upretty( Symbol('Fmag') ) == '|F|'
# Combinations
assert upretty( Symbol('xvecdot') ) == 'x⃗̇'
assert upretty( Symbol('xDotVec') ) == 'ẋ⃗'
assert upretty( Symbol('xHATNorm') ) == '‖x̂‖'
assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == 'x̊_y̌′__|z̆|'
assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == 'α̇̂_n⃗̇__t̃′'
assert upretty( Symbol('x_dot') ) == 'x_dot'
assert upretty( Symbol('x__dot') ) == 'x__dot'
def test_pretty_Cycle():
from sympy.combinatorics.permutations import Cycle
assert pretty(Cycle(1, 2)) == '(1 2)'
assert pretty(Cycle(2)) == '(2)'
assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)'
assert pretty(Cycle()) == '()'
def test_pretty_Permutation():
from sympy.combinatorics.permutations import Permutation
p1 = Permutation(1, 2)(3, 4)
assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)"
assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)"
assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \
'⎛0 1 2 3 4⎞\n'\
'⎝0 2 1 4 3⎠'
assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \
"/0 1 2 3 4\\\n"\
"\\0 2 1 4 3/"
def test_pretty_basic():
assert pretty( -Rational(1)/2 ) == '-1/2'
assert pretty( -Rational(13)/22 ) == \
"""\
-13 \n\
----\n\
22 \
"""
expr = oo
ascii_str = \
"""\
oo\
"""
ucode_str = \
"""\
∞\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2)
ascii_str = \
"""\
2\n\
x \
"""
ucode_str = \
"""\
2\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 1/x
ascii_str = \
"""\
1\n\
-\n\
x\
"""
ucode_str = \
"""\
1\n\
─\n\
x\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# not the same as 1/x
expr = x**-1.0
ascii_str = \
"""\
-1.0\n\
x \
"""
ucode_str = \
"""\
-1.0\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# see issue #2860
expr = Pow(S(2), -1.0, evaluate=False)
ascii_str = \
"""\
-1.0\n\
2 \
"""
ucode_str = \
"""\
-1.0\n\
2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y*x**-2
ascii_str = \
"""\
y \n\
--\n\
2\n\
x \
"""
ucode_str = \
"""\
y \n\
──\n\
2\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
#see issue #14033
expr = x**Rational(1, 3)
ascii_str = \
"""\
1/3\n\
x \
"""
ucode_str = \
"""\
1/3\n\
x \
"""
assert xpretty(expr, use_unicode=False, wrap_line=False,\
root_notation = False) == ascii_str
assert xpretty(expr, use_unicode=True, wrap_line=False,\
root_notation = False) == ucode_str
expr = x**Rational(-5, 2)
ascii_str = \
"""\
1 \n\
----\n\
5/2\n\
x \
"""
ucode_str = \
"""\
1 \n\
────\n\
5/2\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (-2)**x
ascii_str = \
"""\
x\n\
(-2) \
"""
ucode_str = \
"""\
x\n\
(-2) \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# See issue 4923
expr = Pow(3, 1, evaluate=False)
ascii_str = \
"""\
1\n\
3 \
"""
ucode_str = \
"""\
1\n\
3 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2 + x + 1)
ascii_str_1 = \
"""\
2\n\
1 + x + x \
"""
ascii_str_2 = \
"""\
2 \n\
x + x + 1\
"""
ascii_str_3 = \
"""\
2 \n\
x + 1 + x\
"""
ucode_str_1 = \
"""\
2\n\
1 + x + x \
"""
ucode_str_2 = \
"""\
2 \n\
x + x + 1\
"""
ucode_str_3 = \
"""\
2 \n\
x + 1 + x\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
expr = 1 - x
ascii_str_1 = \
"""\
1 - x\
"""
ascii_str_2 = \
"""\
-x + 1\
"""
ucode_str_1 = \
"""\
1 - x\
"""
ucode_str_2 = \
"""\
-x + 1\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = 1 - 2*x
ascii_str_1 = \
"""\
1 - 2*x\
"""
ascii_str_2 = \
"""\
-2*x + 1\
"""
ucode_str_1 = \
"""\
1 - 2⋅x\
"""
ucode_str_2 = \
"""\
-2⋅x + 1\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = x/y
ascii_str = \
"""\
x\n\
-\n\
y\
"""
ucode_str = \
"""\
x\n\
─\n\
y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x/y
ascii_str = \
"""\
-x \n\
---\n\
y \
"""
ucode_str = \
"""\
-x \n\
───\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x + 2)/y
ascii_str_1 = \
"""\
2 + x\n\
-----\n\
y \
"""
ascii_str_2 = \
"""\
x + 2\n\
-----\n\
y \
"""
ucode_str_1 = \
"""\
2 + x\n\
─────\n\
y \
"""
ucode_str_2 = \
"""\
x + 2\n\
─────\n\
y \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = (1 + x)*y
ascii_str_1 = \
"""\
y*(1 + x)\
"""
ascii_str_2 = \
"""\
(1 + x)*y\
"""
ascii_str_3 = \
"""\
y*(x + 1)\
"""
ucode_str_1 = \
"""\
y⋅(1 + x)\
"""
ucode_str_2 = \
"""\
(1 + x)⋅y\
"""
ucode_str_3 = \
"""\
y⋅(x + 1)\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
# Test for correct placement of the negative sign
expr = -5*x/(x + 10)
ascii_str_1 = \
"""\
-5*x \n\
------\n\
10 + x\
"""
ascii_str_2 = \
"""\
-5*x \n\
------\n\
x + 10\
"""
ucode_str_1 = \
"""\
-5⋅x \n\
──────\n\
10 + x\
"""
ucode_str_2 = \
"""\
-5⋅x \n\
──────\n\
x + 10\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = -S.Half - 3*x
ascii_str = \
"""\
-3*x - 1/2\
"""
ucode_str = \
"""\
-3⋅x - 1/2\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = S.Half - 3*x
ascii_str = \
"""\
1/2 - 3*x\
"""
ucode_str = \
"""\
1/2 - 3⋅x\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -S.Half - 3*x/2
ascii_str = \
"""\
3*x 1\n\
- --- - -\n\
2 2\
"""
ucode_str = \
"""\
3⋅x 1\n\
- ─── - ─\n\
2 2\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = S.Half - 3*x/2
ascii_str = \
"""\
1 3*x\n\
- - ---\n\
2 2 \
"""
ucode_str = \
"""\
1 3⋅x\n\
─ - ───\n\
2 2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_negative_fractions():
expr = -x/y
ascii_str =\
"""\
-x \n\
---\n\
y \
"""
ucode_str =\
"""\
-x \n\
───\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x*z/y
ascii_str =\
"""\
-x*z \n\
-----\n\
y \
"""
ucode_str =\
"""\
-x⋅z \n\
─────\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x**2/y
ascii_str =\
"""\
2\n\
x \n\
--\n\
y \
"""
ucode_str =\
"""\
2\n\
x \n\
──\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x**2/y
ascii_str =\
"""\
2 \n\
-x \n\
----\n\
y \
"""
ucode_str =\
"""\
2 \n\
-x \n\
────\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x/(y*z)
ascii_str =\
"""\
-x \n\
---\n\
y*z\
"""
ucode_str =\
"""\
-x \n\
───\n\
y⋅z\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -a/y**2
ascii_str =\
"""\
-a \n\
---\n\
2\n\
y \
"""
ucode_str =\
"""\
-a \n\
───\n\
2\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y**(-a/b)
ascii_str =\
"""\
-a \n\
---\n\
b \n\
y \
"""
ucode_str =\
"""\
-a \n\
───\n\
b \n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -1/y**2
ascii_str =\
"""\
-1 \n\
---\n\
2\n\
y \
"""
ucode_str =\
"""\
-1 \n\
───\n\
2\n\
y \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -10/b**2
ascii_str =\
"""\
-10 \n\
----\n\
2 \n\
b \
"""
ucode_str =\
"""\
-10 \n\
────\n\
2 \n\
b \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Rational(-200, 37)
ascii_str =\
"""\
-200 \n\
-----\n\
37 \
"""
ucode_str =\
"""\
-200 \n\
─────\n\
37 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Mul(0, 1, evaluate=False)
assert pretty(expr) == "0*1"
assert upretty(expr) == "0⋅1"
expr = Mul(1, 0, evaluate=False)
assert pretty(expr) == "1*0"
assert upretty(expr) == "1⋅0"
expr = Mul(1, 1, evaluate=False)
assert pretty(expr) == "1*1"
assert upretty(expr) == "1⋅1"
expr = Mul(1, 1, 1, evaluate=False)
assert pretty(expr) == "1*1*1"
assert upretty(expr) == "1⋅1⋅1"
expr = Mul(1, 2, evaluate=False)
assert pretty(expr) == "1*2"
assert upretty(expr) == "1⋅2"
expr = Add(0, 1, evaluate=False)
assert pretty(expr) == "0 + 1"
assert upretty(expr) == "0 + 1"
expr = Mul(1, 1, 2, evaluate=False)
assert pretty(expr) == "1*1*2"
assert upretty(expr) == "1⋅1⋅2"
expr = Add(0, 0, 1, evaluate=False)
assert pretty(expr) == "0 + 0 + 1"
assert upretty(expr) == "0 + 0 + 1"
expr = Mul(1, -1, evaluate=False)
assert pretty(expr) == "1*(-1)"
assert upretty(expr) == "1⋅(-1)"
expr = Mul(1.0, x, evaluate=False)
assert pretty(expr) == "1.0*x"
assert upretty(expr) == "1.0⋅x"
expr = Mul(1, 1, 2, 3, x, evaluate=False)
assert pretty(expr) == "1*1*2*3*x"
assert upretty(expr) == "1⋅1⋅2⋅3⋅x"
expr = Mul(-1, 1, evaluate=False)
assert pretty(expr) == "-1*1"
assert upretty(expr) == "-1⋅1"
expr = Mul(4, 3, 2, 1, 0, y, x, evaluate=False)
assert pretty(expr) == "4*3*2*1*0*y*x"
assert upretty(expr) == "4⋅3⋅2⋅1⋅0⋅y⋅x"
expr = Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)
assert pretty(expr) == "4*3*2*(z + 1)*0*y*x"
assert upretty(expr) == "4⋅3⋅2⋅(z + 1)⋅0⋅y⋅x"
expr = Mul(Rational(2, 3), Rational(5, 7), evaluate=False)
assert pretty(expr) == "2/3*5/7"
assert upretty(expr) == "2/3⋅5/7"
def test_issue_5524():
assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
"""\
2 / ___ \\\n\
- (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\
"""
assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
"""\
2 \n\
- (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\
"""
def test_pretty_ordering():
assert pretty(x**2 + x + 1, order='lex') == \
"""\
2 \n\
x + x + 1\
"""
assert pretty(x**2 + x + 1, order='rev-lex') == \
"""\
2\n\
1 + x + x \
"""
assert pretty(1 - x, order='lex') == '-x + 1'
assert pretty(1 - x, order='rev-lex') == '1 - x'
assert pretty(1 - 2*x, order='lex') == '-2*x + 1'
assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x'
f = 2*x**4 + y**2 - x**2 + y**3
assert pretty(f, order=None) == \
"""\
4 2 3 2\n\
2*x - x + y + y \
"""
assert pretty(f, order='lex') == \
"""\
4 2 3 2\n\
2*x - x + y + y \
"""
assert pretty(f, order='rev-lex') == \
"""\
2 3 2 4\n\
y + y - x + 2*x \
"""
expr = x - x**3/6 + x**5/120 + O(x**6)
ascii_str = \
"""\
3 5 \n\
x x / 6\\\n\
x - -- + --- + O\\x /\n\
6 120 \
"""
ucode_str = \
"""\
3 5 \n\
x x ⎛ 6⎞\n\
x - ── + ─── + O⎝x ⎠\n\
6 120 \
"""
assert pretty(expr, order=None) == ascii_str
assert upretty(expr, order=None) == ucode_str
assert pretty(expr, order='lex') == ascii_str
assert upretty(expr, order='lex') == ucode_str
assert pretty(expr, order='rev-lex') == ascii_str
assert upretty(expr, order='rev-lex') == ucode_str
def test_EulerGamma():
assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma"
assert upretty(EulerGamma) == "γ"
def test_GoldenRatio():
assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio"
assert upretty(GoldenRatio) == "φ"
def test_pretty_relational():
expr = Eq(x, y)
ascii_str = \
"""\
x = y\
"""
ucode_str = \
"""\
x = y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lt(x, y)
ascii_str = \
"""\
x < y\
"""
ucode_str = \
"""\
x < y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Gt(x, y)
ascii_str = \
"""\
x > y\
"""
ucode_str = \
"""\
x > y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Le(x, y)
ascii_str = \
"""\
x <= y\
"""
ucode_str = \
"""\
x ≤ y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Ge(x, y)
ascii_str = \
"""\
x >= y\
"""
ucode_str = \
"""\
x ≥ y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Ne(x/(y + 1), y**2)
ascii_str_1 = \
"""\
x 2\n\
----- != y \n\
1 + y \
"""
ascii_str_2 = \
"""\
x 2\n\
----- != y \n\
y + 1 \
"""
ucode_str_1 = \
"""\
x 2\n\
───── ≠ y \n\
1 + y \
"""
ucode_str_2 = \
"""\
x 2\n\
───── ≠ y \n\
y + 1 \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
def test_Assignment():
expr = Assignment(x, y)
ascii_str = \
"""\
x := y\
"""
ucode_str = \
"""\
x := y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_AugmentedAssignment():
expr = AddAugmentedAssignment(x, y)
ascii_str = \
"""\
x += y\
"""
ucode_str = \
"""\
x += y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = SubAugmentedAssignment(x, y)
ascii_str = \
"""\
x -= y\
"""
ucode_str = \
"""\
x -= y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = MulAugmentedAssignment(x, y)
ascii_str = \
"""\
x *= y\
"""
ucode_str = \
"""\
x *= y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = DivAugmentedAssignment(x, y)
ascii_str = \
"""\
x /= y\
"""
ucode_str = \
"""\
x /= y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = ModAugmentedAssignment(x, y)
ascii_str = \
"""\
x %= y\
"""
ucode_str = \
"""\
x %= y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_rational():
expr = y*x**-2
ascii_str = \
"""\
y \n\
--\n\
2\n\
x \
"""
ucode_str = \
"""\
y \n\
──\n\
2\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y**Rational(3, 2) * x**Rational(-5, 2)
ascii_str = \
"""\
3/2\n\
y \n\
----\n\
5/2\n\
x \
"""
ucode_str = \
"""\
3/2\n\
y \n\
────\n\
5/2\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sin(x)**3/tan(x)**2
ascii_str = \
"""\
3 \n\
sin (x)\n\
-------\n\
2 \n\
tan (x)\
"""
ucode_str = \
"""\
3 \n\
sin (x)\n\
───────\n\
2 \n\
tan (x)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_functions():
"""Tests for Abs, conjugate, exp, function braces, and factorial."""
expr = (2*x + exp(x))
ascii_str_1 = \
"""\
x\n\
2*x + e \
"""
ascii_str_2 = \
"""\
x \n\
e + 2*x\
"""
ucode_str_1 = \
"""\
x\n\
2⋅x + ℯ \
"""
ucode_str_2 = \
"""\
x \n\
ℯ + 2⋅x\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Abs(x)
ascii_str = \
"""\
|x|\
"""
ucode_str = \
"""\
│x│\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Abs(x/(x**2 + 1))
ascii_str_1 = \
"""\
| x |\n\
|------|\n\
| 2|\n\
|1 + x |\
"""
ascii_str_2 = \
"""\
| x |\n\
|------|\n\
| 2 |\n\
|x + 1|\
"""
ucode_str_1 = \
"""\
│ x │\n\
│──────│\n\
│ 2│\n\
│1 + x │\
"""
ucode_str_2 = \
"""\
│ x │\n\
│──────│\n\
│ 2 │\n\
│x + 1│\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Abs(1 / (y - Abs(x)))
ascii_str = \
"""\
1 \n\
---------\n\
|y - |x||\
"""
ucode_str = \
"""\
1 \n\
─────────\n\
│y - │x││\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
n = Symbol('n', integer=True)
expr = factorial(n)
ascii_str = \
"""\
n!\
"""
ucode_str = \
"""\
n!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(2*n)
ascii_str = \
"""\
(2*n)!\
"""
ucode_str = \
"""\
(2⋅n)!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(factorial(factorial(n)))
ascii_str = \
"""\
((n!)!)!\
"""
ucode_str = \
"""\
((n!)!)!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(n + 1)
ascii_str_1 = \
"""\
(1 + n)!\
"""
ascii_str_2 = \
"""\
(n + 1)!\
"""
ucode_str_1 = \
"""\
(1 + n)!\
"""
ucode_str_2 = \
"""\
(n + 1)!\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = subfactorial(n)
ascii_str = \
"""\
!n\
"""
ucode_str = \
"""\
!n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = subfactorial(2*n)
ascii_str = \
"""\
!(2*n)\
"""
ucode_str = \
"""\
!(2⋅n)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
n = Symbol('n', integer=True)
expr = factorial2(n)
ascii_str = \
"""\
n!!\
"""
ucode_str = \
"""\
n!!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(2*n)
ascii_str = \
"""\
(2*n)!!\
"""
ucode_str = \
"""\
(2⋅n)!!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(factorial2(factorial2(n)))
ascii_str = \
"""\
((n!!)!!)!!\
"""
ucode_str = \
"""\
((n!!)!!)!!\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(n + 1)
ascii_str_1 = \
"""\
(1 + n)!!\
"""
ascii_str_2 = \
"""\
(n + 1)!!\
"""
ucode_str_1 = \
"""\
(1 + n)!!\
"""
ucode_str_2 = \
"""\
(n + 1)!!\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = 2*binomial(n, k)
ascii_str = \
"""\
/n\\\n\
2*| |\n\
\\k/\
"""
ucode_str = \
"""\
⎛n⎞\n\
2⋅⎜ ⎟\n\
⎝k⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*binomial(2*n, k)
ascii_str = \
"""\
/2*n\\\n\
2*| |\n\
\\ k /\
"""
ucode_str = \
"""\
⎛2⋅n⎞\n\
2⋅⎜ ⎟\n\
⎝ k ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*binomial(n**2, k)
ascii_str = \
"""\
/ 2\\\n\
|n |\n\
2*| |\n\
\\k /\
"""
ucode_str = \
"""\
⎛ 2⎞\n\
⎜n ⎟\n\
2⋅⎜ ⎟\n\
⎝k ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = catalan(n)
ascii_str = \
"""\
C \n\
n\
"""
ucode_str = \
"""\
C \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = catalan(n)
ascii_str = \
"""\
C \n\
n\
"""
ucode_str = \
"""\
C \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bell(n)
ascii_str = \
"""\
B \n\
n\
"""
ucode_str = \
"""\
B \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bernoulli(n)
ascii_str = \
"""\
B \n\
n\
"""
ucode_str = \
"""\
B \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bernoulli(n, x)
ascii_str = \
"""\
B (x)\n\
n \
"""
ucode_str = \
"""\
B (x)\n\
n \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = fibonacci(n)
ascii_str = \
"""\
F \n\
n\
"""
ucode_str = \
"""\
F \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = lucas(n)
ascii_str = \
"""\
L \n\
n\
"""
ucode_str = \
"""\
L \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = tribonacci(n)
ascii_str = \
"""\
T \n\
n\
"""
ucode_str = \
"""\
T \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = stieltjes(n)
ascii_str = \
"""\
stieltjes \n\
n\
"""
ucode_str = \
"""\
γ \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = stieltjes(n, x)
ascii_str = \
"""\
stieltjes (x)\n\
n \
"""
ucode_str = \
"""\
γ (x)\n\
n \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieuc(x, y, z)
ascii_str = 'C(x, y, z)'
ucode_str = 'C(x, y, z)'
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieus(x, y, z)
ascii_str = 'S(x, y, z)'
ucode_str = 'S(x, y, z)'
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieucprime(x, y, z)
ascii_str = "C'(x, y, z)"
ucode_str = "C'(x, y, z)"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieusprime(x, y, z)
ascii_str = "S'(x, y, z)"
ucode_str = "S'(x, y, z)"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(x)
ascii_str = \
"""\
_\n\
x\
"""
ucode_str = \
"""\
_\n\
x\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
f = Function('f')
expr = conjugate(f(x + 1))
ascii_str_1 = \
"""\
________\n\
f(1 + x)\
"""
ascii_str_2 = \
"""\
________\n\
f(x + 1)\
"""
ucode_str_1 = \
"""\
________\n\
f(1 + x)\
"""
ucode_str_2 = \
"""\
________\n\
f(x + 1)\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x)
ascii_str = \
"""\
f(x)\
"""
ucode_str = \
"""\
f(x)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = f(x, y)
ascii_str = \
"""\
f(x, y)\
"""
ucode_str = \
"""\
f(x, y)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = f(x/(y + 1), y)
ascii_str_1 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\1 + y /\
"""
ascii_str_2 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\y + 1 /\
"""
ucode_str_1 = \
"""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝1 + y ⎠\
"""
ucode_str_2 = \
"""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝y + 1 ⎠\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x**x**x**x**x**x)
ascii_str = \
"""\
/ / / / / x\\\\\\\\\\
| | | | \\x /||||
| | | \\x /|||
| | \\x /||
| \\x /|
f\\x /\
"""
ucode_str = \
"""\
⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞
⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟
⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟
⎜ ⎜ ⎝x ⎠⎟⎟
⎜ ⎝x ⎠⎟
f⎝x ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sin(x)**2
ascii_str = \
"""\
2 \n\
sin (x)\
"""
ucode_str = \
"""\
2 \n\
sin (x)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(a + b*I)
ascii_str = \
"""\
_ _\n\
a - I*b\
"""
ucode_str = \
"""\
_ _\n\
a - ⅈ⋅b\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(exp(a + b*I))
ascii_str = \
"""\
_ _\n\
a - I*b\n\
e \
"""
ucode_str = \
"""\
_ _\n\
a - ⅈ⋅b\n\
ℯ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate( f(1 + conjugate(f(x))) )
ascii_str_1 = \
"""\
___________\n\
/ ____\\\n\
f\\1 + f(x)/\
"""
ascii_str_2 = \
"""\
___________\n\
/____ \\\n\
f\\f(x) + 1/\
"""
ucode_str_1 = \
"""\
___________\n\
⎛ ____⎞\n\
f⎝1 + f(x)⎠\
"""
ucode_str_2 = \
"""\
___________\n\
⎛____ ⎞\n\
f⎝f(x) + 1⎠\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x/(y + 1), y)
ascii_str_1 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\1 + y /\
"""
ascii_str_2 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\y + 1 /\
"""
ucode_str_1 = \
"""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝1 + y ⎠\
"""
ucode_str_2 = \
"""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝y + 1 ⎠\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = floor(1 / (y - floor(x)))
ascii_str = \
"""\
/ 1 \\\n\
floor|------------|\n\
\\y - floor(x)/\
"""
ucode_str = \
"""\
⎢ 1 ⎥\n\
⎢───────⎥\n\
⎣y - ⌊x⌋⎦\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = ceiling(1 / (y - ceiling(x)))
ascii_str = \
"""\
/ 1 \\\n\
ceiling|--------------|\n\
\\y - ceiling(x)/\
"""
ucode_str = \
"""\
⎡ 1 ⎤\n\
⎢───────⎥\n\
⎢y - ⌈x⌉⎥\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n)
ascii_str = \
"""\
E \n\
n\
"""
ucode_str = \
"""\
E \n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(1/(1 + 1/(1 + 1/n)))
ascii_str = \
"""\
E \n\
1 \n\
---------\n\
1 \n\
1 + -----\n\
1\n\
1 + -\n\
n\
"""
ucode_str = \
"""\
E \n\
1 \n\
─────────\n\
1 \n\
1 + ─────\n\
1\n\
1 + ─\n\
n\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n, x)
ascii_str = \
"""\
E (x)\n\
n \
"""
ucode_str = \
"""\
E (x)\n\
n \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n, x/2)
ascii_str = \
"""\
/x\\\n\
E |-|\n\
n\\2/\
"""
ucode_str = \
"""\
⎛x⎞\n\
E ⎜─⎟\n\
n⎝2⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_sqrt():
expr = sqrt(2)
ascii_str = \
"""\
___\n\
\\/ 2 \
"""
ucode_str = \
"√2"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**Rational(1, 3)
ascii_str = \
"""\
3 ___\n\
\\/ 2 \
"""
ucode_str = \
"""\
3 ___\n\
╲╱ 2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**Rational(1, 1000)
ascii_str = \
"""\
1000___\n\
\\/ 2 \
"""
ucode_str = \
"""\
1000___\n\
╲╱ 2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sqrt(x**2 + 1)
ascii_str = \
"""\
________\n\
/ 2 \n\
\\/ x + 1 \
"""
ucode_str = \
"""\
________\n\
╱ 2 \n\
╲╱ x + 1 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (1 + sqrt(5))**Rational(1, 3)
ascii_str = \
"""\
___________\n\
3 / ___ \n\
\\/ 1 + \\/ 5 \
"""
ucode_str = \
"""\
3 ________\n\
╲╱ 1 + √5 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**(1/x)
ascii_str = \
"""\
x ___\n\
\\/ 2 \
"""
ucode_str = \
"""\
x ___\n\
╲╱ 2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sqrt(2 + pi)
ascii_str = \
"""\
________\n\
\\/ 2 + pi \
"""
ucode_str = \
"""\
_______\n\
╲╱ 2 + π \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (2 + (
1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2)
ascii_str = \
"""\
____________ \n\
/ 2 1000___ \n\
/ x + 1 \\/ x + 1\n\
4 / 2 + ------ + -----------\n\
\\/ x + 2 ________\n\
/ 2 \n\
\\/ x + 3 \
"""
ucode_str = \
"""\
____________ \n\
╱ 2 1000___ \n\
╱ x + 1 ╲╱ x + 1\n\
4 ╱ 2 + ────── + ───────────\n\
╲╱ x + 2 ________\n\
╱ 2 \n\
╲╱ x + 3 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_sqrt_char_knob():
# See PR #9234.
expr = sqrt(2)
ucode_str1 = \
"""\
___\n\
╲╱ 2 \
"""
ucode_str2 = \
"√2"
assert xpretty(expr, use_unicode=True,
use_unicode_sqrt_char=False) == ucode_str1
assert xpretty(expr, use_unicode=True,
use_unicode_sqrt_char=True) == ucode_str2
def test_pretty_sqrt_longsymbol_no_sqrt_char():
# Do not use unicode sqrt char for long symbols (see PR #9234).
expr = sqrt(Symbol('C1'))
ucode_str = \
"""\
____\n\
╲╱ C₁ \
"""
assert upretty(expr) == ucode_str
def test_pretty_KroneckerDelta():
x, y = symbols("x, y")
expr = KroneckerDelta(x, y)
ascii_str = \
"""\
d \n\
x,y\
"""
ucode_str = \
"""\
δ \n\
x,y\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_product():
n, m, k, l = symbols('n m k l')
f = symbols('f', cls=Function)
expr = Product(f((n/3)**2), (n, k**2, l))
unicode_str = \
"""\
l \n\
─┬──────┬─ \n\
│ │ ⎛ 2⎞\n\
│ │ ⎜n ⎟\n\
│ │ f⎜──⎟\n\
│ │ ⎝9 ⎠\n\
│ │ \n\
2 \n\
n = k """
ascii_str = \
"""\
l \n\
__________ \n\
| | / 2\\\n\
| | |n |\n\
| | f|--|\n\
| | \\9 /\n\
| | \n\
2 \n\
n = k """
expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m))
unicode_str = \
"""\
m l \n\
─┬──────┬─ ─┬──────┬─ \n\
│ │ │ │ ⎛ 2⎞\n\
│ │ │ │ ⎜n ⎟\n\
│ │ │ │ f⎜──⎟\n\
│ │ │ │ ⎝9 ⎠\n\
│ │ │ │ \n\
l = 1 2 \n\
n = k """
ascii_str = \
"""\
m l \n\
__________ __________ \n\
| | | | / 2\\\n\
| | | | |n |\n\
| | | | f|--|\n\
| | | | \\9 /\n\
| | | | \n\
l = 1 2 \n\
n = k """
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
def test_pretty_Lambda():
# S.IdentityFunction is a special case
expr = Lambda(y, y)
assert pretty(expr) == "x -> x"
assert upretty(expr) == "x ↦ x"
expr = Lambda(x, x+1)
assert pretty(expr) == "x -> x + 1"
assert upretty(expr) == "x ↦ x + 1"
expr = Lambda(x, x**2)
ascii_str = \
"""\
2\n\
x -> x \
"""
ucode_str = \
"""\
2\n\
x ↦ x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda(x, x**2)**2
ascii_str = \
"""\
2
/ 2\\ \n\
\\x -> x / \
"""
ucode_str = \
"""\
2
⎛ 2⎞ \n\
⎝x ↦ x ⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda((x, y), x)
ascii_str = "(x, y) -> x"
ucode_str = "(x, y) ↦ x"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda((x, y), x**2)
ascii_str = \
"""\
2\n\
(x, y) -> x \
"""
ucode_str = \
"""\
2\n\
(x, y) ↦ x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda(((x, y),), x**2)
ascii_str = \
"""\
2\n\
((x, y),) -> x \
"""
ucode_str = \
"""\
2\n\
((x, y),) ↦ x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_TransferFunction():
tf1 = TransferFunction(s - 1, s + 1, s)
assert upretty(tf1) == "s - 1\n─────\ns + 1"
tf2 = TransferFunction(2*s + 1, 3 - p, s)
assert upretty(tf2) == "2⋅s + 1\n───────\n 3 - p "
tf3 = TransferFunction(p, p + 1, p)
assert upretty(tf3) == " p \n─────\np + 1"
def test_pretty_Series():
tf1 = TransferFunction(x + y, x - 2*y, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(x**2 + y, y - x, y)
expected1 = \
"""\
⎛ 2 ⎞\n\
⎛ x + y ⎞ ⎜x + y⎟\n\
⎜───────⎟⋅⎜──────⎟\n\
⎝x - 2⋅y⎠ ⎝-x + y⎠\
"""
expected2 = \
"""\
⎛-x + y⎞ ⎛ -x - y⎞\n\
⎜──────⎟⋅⎜───────⎟\n\
⎝x + y ⎠ ⎝x - 2⋅y⎠\
"""
expected3 = \
"""\
⎛ 2 ⎞ \n\
⎜x + y⎟ ⎛ x + y ⎞ ⎛ -x - y x - y⎞\n\
⎜──────⎟⋅⎜───────⎟⋅⎜─────── + ─────⎟\n\
⎝-x + y⎠ ⎝x - 2⋅y⎠ ⎝x - 2⋅y x + y⎠\
"""
expected4 = \
"""\
⎛ 2 ⎞\n\
⎛ x + y x - y⎞ ⎜x - y x + y⎟\n\
⎜─────── + ─────⎟⋅⎜───── + ──────⎟\n\
⎝x - 2⋅y x + y⎠ ⎝x + y -x + y⎠\
"""
assert upretty(Series(tf1, tf3)) == expected1
assert upretty(Series(-tf2, -tf1)) == expected2
assert upretty(Series(tf3, tf1, Parallel(-tf1, tf2))) == expected3
assert upretty(Series(Parallel(tf1, tf2), Parallel(tf2, tf3))) == expected4
def test_pretty_Parallel():
tf1 = TransferFunction(x + y, x - 2*y, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(x**2 + y, y - x, y)
expected1 = \
"""\
x + y x - y\n\
─────── + ─────\n\
x - 2⋅y x + y\
"""
expected2 = \
"""\
-x + y -x - y\n\
────── + ───────\n\
x + y x - 2⋅y\
"""
expected3 = \
"""\
2 \n\
x + y x + y ⎛ -x - y⎞ ⎛x - y⎞\n\
────── + ─────── + ⎜───────⎟⋅⎜─────⎟\n\
-x + y x - 2⋅y ⎝x - 2⋅y⎠ ⎝x + y⎠\
"""
expected4 = \
"""\
⎛ 2 ⎞\n\
⎛ x + y ⎞ ⎛x - y⎞ ⎛x - y⎞ ⎜x + y⎟\n\
⎜───────⎟⋅⎜─────⎟ + ⎜─────⎟⋅⎜──────⎟\n\
⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x + y⎠ ⎝-x + y⎠\
"""
assert upretty(Parallel(tf1, tf2)) == expected1
assert upretty(Parallel(-tf2, -tf1)) == expected2
assert upretty(Parallel(tf3, tf1, Series(-tf1, tf2))) == expected3
assert upretty(Parallel(Series(tf1, tf2), Series(tf2, tf3))) == expected4
def test_pretty_Feedback():
tf = TransferFunction(1, 1, y)
tf1 = TransferFunction(x + y, x - 2*y, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y)
tf4 = TransferFunction(x - 2*y**3, x + y, x)
tf5 = TransferFunction(1 - x, x - y, y)
tf6 = TransferFunction(2, 2, x)
expected1 = \
"""\
⎛1⎞ \n\
⎜─⎟ \n\
⎝1⎠ \n\
───────────\n\
1 x + y \n\
─ + ───────\n\
1 x - 2⋅y\
"""
expected2 = \
"""\
⎛1⎞ \n\
⎜─⎟ \n\
⎝1⎠ \n\
────────────────────────────────────\n\
⎛ 2 ⎞\n\
1 ⎛x - y⎞ ⎛ x + y ⎞ ⎜y - 2⋅y + 1⎟\n\
─ + ⎜─────⎟⋅⎜───────⎟⋅⎜────────────⎟\n\
1 ⎝x + y⎠ ⎝x - 2⋅y⎠ ⎝ y + 5 ⎠\
"""
expected3 = \
"""\
⎛ x + y ⎞ \n\
⎜───────⎟ \n\
⎝x - 2⋅y⎠ \n\
────────────────────────────────────────────\n\
⎛ 2 ⎞ \n\
1 ⎛ x + y ⎞ ⎛x - y⎞ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞\n\
─ + ⎜───────⎟⋅⎜─────⎟⋅⎜────────────⎟⋅⎜─────⎟\n\
1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝ y + 5 ⎠ ⎝x - y⎠\
"""
expected4 = \
"""\
⎛ x + y ⎞ ⎛x - y⎞ \n\
⎜───────⎟⋅⎜─────⎟ \n\
⎝x - 2⋅y⎠ ⎝x + y⎠ \n\
─────────────────────\n\
1 ⎛ x + y ⎞ ⎛x - y⎞\n\
─ + ⎜───────⎟⋅⎜─────⎟\n\
1 ⎝x - 2⋅y⎠ ⎝x + y⎠\
"""
expected5 = \
"""\
⎛ x + y ⎞ ⎛x - y⎞ \n\
⎜───────⎟⋅⎜─────⎟ \n\
⎝x - 2⋅y⎠ ⎝x + y⎠ \n\
─────────────────────────────\n\
1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\
─ + ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\
1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\
"""
expected6 = \
"""\
⎛ 2 ⎞ \n\
⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ \n\
⎜────────────⎟⋅⎜─────⎟ \n\
⎝ y + 5 ⎠ ⎝x - y⎠ \n\
────────────────────────────────────────────\n\
⎛ 2 ⎞ \n\
1 ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ ⎛x - y⎞ ⎛ x + y ⎞\n\
─ + ⎜────────────⎟⋅⎜─────⎟⋅⎜─────⎟⋅⎜───────⎟\n\
1 ⎝ y + 5 ⎠ ⎝x - y⎠ ⎝x + y⎠ ⎝x - 2⋅y⎠\
"""
expected7 = \
"""\
⎛ 3⎞ \n\
⎜x - 2⋅y ⎟ \n\
⎜────────⎟ \n\
⎝ x + y ⎠ \n\
──────────────────\n\
⎛ 3⎞ \n\
1 ⎜x - 2⋅y ⎟ ⎛2⎞\n\
─ + ⎜────────⎟⋅⎜─⎟\n\
1 ⎝ x + y ⎠ ⎝2⎠\
"""
expected8 = \
"""\
⎛1 - x⎞ \n\
⎜─────⎟ \n\
⎝x - y⎠ \n\
─────────\n\
1 1 - x\n\
─ + ─────\n\
1 x - y\
"""
assert upretty(Feedback(tf, tf1)) == expected1
assert upretty(Feedback(tf, tf2*tf1*tf3)) == expected2
assert upretty(Feedback(tf1, tf2*tf3*tf5)) == expected3
assert upretty(Feedback(tf1*tf2, tf)) == expected4
assert upretty(Feedback(tf1*tf2, tf5)) == expected5
assert upretty(Feedback(tf3*tf5, tf2*tf1)) == expected6
assert upretty(Feedback(tf4, tf6)) == expected7
assert upretty(Feedback(tf5, tf)) == expected8
def test_pretty_order():
expr = O(1)
ascii_str = \
"""\
O(1)\
"""
ucode_str = \
"""\
O(1)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1/x)
ascii_str = \
"""\
/1\\\n\
O|-|\n\
\\x/\
"""
ucode_str = \
"""\
⎛1⎞\n\
O⎜─⎟\n\
⎝x⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(x**2 + y**2)
ascii_str = \
"""\
/ 2 2 \\\n\
O\\x + y ; (x, y) -> (0, 0)/\
"""
ucode_str = \
"""\
⎛ 2 2 ⎞\n\
O⎝x + y ; (x, y) → (0, 0)⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1, (x, oo))
ascii_str = \
"""\
O(1; x -> oo)\
"""
ucode_str = \
"""\
O(1; x → ∞)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1/x, (x, oo))
ascii_str = \
"""\
/1 \\\n\
O|-; x -> oo|\n\
\\x /\
"""
ucode_str = \
"""\
⎛1 ⎞\n\
O⎜─; x → ∞⎟\n\
⎝x ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(x**2 + y**2, (x, oo), (y, oo))
ascii_str = \
"""\
/ 2 2 \\\n\
O\\x + y ; (x, y) -> (oo, oo)/\
"""
ucode_str = \
"""\
⎛ 2 2 ⎞\n\
O⎝x + y ; (x, y) → (∞, ∞)⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_derivatives():
# Simple
expr = Derivative(log(x), x, evaluate=False)
ascii_str = \
"""\
d \n\
--(log(x))\n\
dx \
"""
ucode_str = \
"""\
d \n\
──(log(x))\n\
dx \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(log(x), x, evaluate=False) + x
ascii_str_1 = \
"""\
d \n\
x + --(log(x))\n\
dx \
"""
ascii_str_2 = \
"""\
d \n\
--(log(x)) + x\n\
dx \
"""
ucode_str_1 = \
"""\
d \n\
x + ──(log(x))\n\
dx \
"""
ucode_str_2 = \
"""\
d \n\
──(log(x)) + x\n\
dx \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
# basic partial derivatives
expr = Derivative(log(x + y) + x, x)
ascii_str_1 = \
"""\
d \n\
--(log(x + y) + x)\n\
dx \
"""
ascii_str_2 = \
"""\
d \n\
--(x + log(x + y))\n\
dx \
"""
ucode_str_1 = \
"""\
∂ \n\
──(log(x + y) + x)\n\
∂x \
"""
ucode_str_2 = \
"""\
∂ \n\
──(x + log(x + y))\n\
∂x \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr)
# Multiple symbols
expr = Derivative(log(x) + x**2, x, y)
ascii_str_1 = \
"""\
2 \n\
d / 2\\\n\
-----\\log(x) + x /\n\
dy dx \
"""
ascii_str_2 = \
"""\
2 \n\
d / 2 \\\n\
-----\\x + log(x)/\n\
dy dx \
"""
ucode_str_1 = \
"""\
2 \n\
d ⎛ 2⎞\n\
─────⎝log(x) + x ⎠\n\
dy dx \
"""
ucode_str_2 = \
"""\
2 \n\
d ⎛ 2 ⎞\n\
─────⎝x + log(x)⎠\n\
dy dx \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Derivative(2*x*y, y, x) + x**2
ascii_str_1 = \
"""\
2 \n\
d 2\n\
-----(2*x*y) + x \n\
dx dy \
"""
ascii_str_2 = \
"""\
2 \n\
2 d \n\
x + -----(2*x*y)\n\
dx dy \
"""
ucode_str_1 = \
"""\
2 \n\
∂ 2\n\
─────(2⋅x⋅y) + x \n\
∂x ∂y \
"""
ucode_str_2 = \
"""\
2 \n\
2 ∂ \n\
x + ─────(2⋅x⋅y)\n\
∂x ∂y \
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Derivative(2*x*y, x, x)
ascii_str = \
"""\
2 \n\
d \n\
---(2*x*y)\n\
2 \n\
dx \
"""
ucode_str = \
"""\
2 \n\
∂ \n\
───(2⋅x⋅y)\n\
2 \n\
∂x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(2*x*y, x, 17)
ascii_str = \
"""\
17 \n\
d \n\
----(2*x*y)\n\
17 \n\
dx \
"""
ucode_str = \
"""\
17 \n\
∂ \n\
────(2⋅x⋅y)\n\
17 \n\
∂x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(2*x*y, x, x, y)
ascii_str = \
"""\
3 \n\
d \n\
------(2*x*y)\n\
2 \n\
dy dx \
"""
ucode_str = \
"""\
3 \n\
∂ \n\
──────(2⋅x⋅y)\n\
2 \n\
∂y ∂x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# Greek letters
alpha = Symbol('alpha')
beta = Function('beta')
expr = beta(alpha).diff(alpha)
ascii_str = \
"""\
d \n\
------(beta(alpha))\n\
dalpha \
"""
ucode_str = \
"""\
d \n\
──(β(α))\n\
dα \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(f(x), (x, n))
ascii_str = \
"""\
n \n\
d \n\
---(f(x))\n\
n \n\
dx \
"""
ucode_str = \
"""\
n \n\
d \n\
───(f(x))\n\
n \n\
dx \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_integrals():
expr = Integral(log(x), x)
ascii_str = \
"""\
/ \n\
| \n\
| log(x) dx\n\
| \n\
/ \
"""
ucode_str = \
"""\
⌠ \n\
⎮ log(x) dx\n\
⌡ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, x)
ascii_str = \
"""\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \
"""
ucode_str = \
"""\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral((sin(x))**2 / (tan(x))**2)
ascii_str = \
"""\
/ \n\
| \n\
| 2 \n\
| sin (x) \n\
| ------- dx\n\
| 2 \n\
| tan (x) \n\
| \n\
/ \
"""
ucode_str = \
"""\
⌠ \n\
⎮ 2 \n\
⎮ sin (x) \n\
⎮ ─────── dx\n\
⎮ 2 \n\
⎮ tan (x) \n\
⌡ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**(2**x), x)
ascii_str = \
"""\
/ \n\
| \n\
| / x\\ \n\
| \\2 / \n\
| x dx\n\
| \n\
/ \
"""
ucode_str = \
"""\
⌠ \n\
⎮ ⎛ x⎞ \n\
⎮ ⎝2 ⎠ \n\
⎮ x dx\n\
⌡ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, (x, 1, 2))
ascii_str = \
"""\
2 \n\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \n\
1 \
"""
ucode_str = \
"""\
2 \n\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \n\
1 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, (x, Rational(1, 2), 10))
ascii_str = \
"""\
10 \n\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \n\
1/2 \
"""
ucode_str = \
"""\
10 \n\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \n\
1/2 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2*y**2, x, y)
ascii_str = \
"""\
/ / \n\
| | \n\
| | 2 2 \n\
| | x *y dx dy\n\
| | \n\
/ / \
"""
ucode_str = \
"""\
⌠ ⌠ \n\
⎮ ⎮ 2 2 \n\
⎮ ⎮ x ⋅y dx dy\n\
⌡ ⌡ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi))
ascii_str = \
"""\
2*pi pi \n\
/ / \n\
| | \n\
| | sin(theta) \n\
| | ---------- d(theta) d(phi)\n\
| | cos(phi) \n\
| | \n\
/ / \n\
0 0 \
"""
ucode_str = \
"""\
2⋅π π \n\
⌠ ⌠ \n\
⎮ ⎮ sin(θ) \n\
⎮ ⎮ ────── dθ dφ\n\
⎮ ⎮ cos(φ) \n\
⌡ ⌡ \n\
0 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_matrix():
# Empty Matrix
expr = Matrix()
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix(2, 0, lambda i, j: 0)
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix(0, 2, lambda i, j: 0)
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix([[x**2 + 1, 1], [y, x + y]])
ascii_str_1 = \
"""\
[ 2 ]
[1 + x 1 ]
[ ]
[ y x + y]\
"""
ascii_str_2 = \
"""\
[ 2 ]
[x + 1 1 ]
[ ]
[ y x + y]\
"""
ucode_str_1 = \
"""\
⎡ 2 ⎤
⎢1 + x 1 ⎥
⎢ ⎥
⎣ y x + y⎦\
"""
ucode_str_2 = \
"""\
⎡ 2 ⎤
⎢x + 1 1 ⎥
⎢ ⎥
⎣ y x + y⎦\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
ascii_str = \
"""\
[x ]
[- y theta]
[y ]
[ ]
[ I*k*phi ]
[0 e 1 ]\
"""
ucode_str = \
"""\
⎡x ⎤
⎢─ y θ⎥
⎢y ⎥
⎢ ⎥
⎢ ⅈ⋅k⋅φ ⎥
⎣0 ℯ 1⎦\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
unicode_str = \
"""\
⎡v̇_msc_00 0 0 ⎤
⎢ ⎥
⎢ 0 v̇_msc_01 0 ⎥
⎢ ⎥
⎣ 0 0 v̇_msc_02⎦\
"""
expr = diag(*MatrixSymbol('vdot_msc',1,3))
assert upretty(expr) == unicode_str
def test_pretty_ndim_arrays():
x, y, z, w = symbols("x y z w")
for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray):
# Basic: scalar array
M = ArrayType(x)
assert pretty(M) == "x"
assert upretty(M) == "x"
M = ArrayType([[1/x, y], [z, w]])
M1 = ArrayType([1/x, y, z])
M2 = tensorproduct(M1, M)
M3 = tensorproduct(M, M)
ascii_str = \
"""\
[1 ]\n\
[- y]\n\
[x ]\n\
[ ]\n\
[z w]\
"""
ucode_str = \
"""\
⎡1 ⎤\n\
⎢─ y⎥\n\
⎢x ⎥\n\
⎢ ⎥\n\
⎣z w⎦\
"""
assert pretty(M) == ascii_str
assert upretty(M) == ucode_str
ascii_str = \
"""\
[1 ]\n\
[- y z]\n\
[x ]\
"""
ucode_str = \
"""\
⎡1 ⎤\n\
⎢─ y z⎥\n\
⎣x ⎦\
"""
assert pretty(M1) == ascii_str
assert upretty(M1) == ucode_str
ascii_str = \
"""\
[[1 y] ]\n\
[[-- -] [z ]]\n\
[[ 2 x] [ y 2 ] [- y*z]]\n\
[[x ] [ - y ] [x ]]\n\
[[ ] [ x ] [ ]]\n\
[[z w] [ ] [ 2 ]]\n\
[[- -] [y*z w*y] [z w*z]]\n\
[[x x] ]\
"""
ucode_str = \
"""\
⎡⎡1 y⎤ ⎤\n\
⎢⎢── ─⎥ ⎡z ⎤⎥\n\
⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\
⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\
⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\
⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\
⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\
⎣⎣x x⎦ ⎦\
"""
assert pretty(M2) == ascii_str
assert upretty(M2) == ucode_str
ascii_str = \
"""\
[ [1 y] ]\n\
[ [-- -] ]\n\
[ [ 2 x] [ y 2 ]]\n\
[ [x ] [ - y ]]\n\
[ [ ] [ x ]]\n\
[ [z w] [ ]]\n\
[ [- -] [y*z w*y]]\n\
[ [x x] ]\n\
[ ]\n\
[[z ] [ w ]]\n\
[[- y*z] [ - w*y]]\n\
[[x ] [ x ]]\n\
[[ ] [ ]]\n\
[[ 2 ] [ 2 ]]\n\
[[z w*z] [w*z w ]]\
"""
ucode_str = \
"""\
⎡ ⎡1 y⎤ ⎤\n\
⎢ ⎢── ─⎥ ⎥\n\
⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\
⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\
⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\
⎢ ⎢z w⎥ ⎢ ⎥⎥\n\
⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\
⎢ ⎣x x⎦ ⎥\n\
⎢ ⎥\n\
⎢⎡z ⎤ ⎡ w ⎤⎥\n\
⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\
⎢⎢x ⎥ ⎢ x ⎥⎥\n\
⎢⎢ ⎥ ⎢ ⎥⎥\n\
⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\
⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\
"""
assert pretty(M3) == ascii_str
assert upretty(M3) == ucode_str
Mrow = ArrayType([[x, y, 1 / z]])
Mcolumn = ArrayType([[x], [y], [1 / z]])
Mcol2 = ArrayType([Mcolumn.tolist()])
ascii_str = \
"""\
[[ 1]]\n\
[[x y -]]\n\
[[ z]]\
"""
ucode_str = \
"""\
⎡⎡ 1⎤⎤\n\
⎢⎢x y ─⎥⎥\n\
⎣⎣ z⎦⎦\
"""
assert pretty(Mrow) == ascii_str
assert upretty(Mrow) == ucode_str
ascii_str = \
"""\
[x]\n\
[ ]\n\
[y]\n\
[ ]\n\
[1]\n\
[-]\n\
[z]\
"""
ucode_str = \
"""\
⎡x⎤\n\
⎢ ⎥\n\
⎢y⎥\n\
⎢ ⎥\n\
⎢1⎥\n\
⎢─⎥\n\
⎣z⎦\
"""
assert pretty(Mcolumn) == ascii_str
assert upretty(Mcolumn) == ucode_str
ascii_str = \
"""\
[[x]]\n\
[[ ]]\n\
[[y]]\n\
[[ ]]\n\
[[1]]\n\
[[-]]\n\
[[z]]\
"""
ucode_str = \
"""\
⎡⎡x⎤⎤\n\
⎢⎢ ⎥⎥\n\
⎢⎢y⎥⎥\n\
⎢⎢ ⎥⎥\n\
⎢⎢1⎥⎥\n\
⎢⎢─⎥⎥\n\
⎣⎣z⎦⎦\
"""
assert pretty(Mcol2) == ascii_str
assert upretty(Mcol2) == ucode_str
def test_tensor_TensorProduct():
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
assert upretty(TensorProduct(A, B)) == "A\u2297B"
assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A"
def test_diffgeom_print_WedgeProduct():
from sympy.diffgeom.rn import R2
from sympy.diffgeom import WedgeProduct
wp = WedgeProduct(R2.dx, R2.dy)
assert upretty(wp) == "ⅆ x∧ⅆ y"
def test_Adjoint():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert pretty(Adjoint(X)) == " +\nX "
assert pretty(Adjoint(X + Y)) == " +\n(X + Y) "
assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y "
assert pretty(Adjoint(X*Y)) == " +\n(X*Y) "
assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X "
assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / "
assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / "
assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / "
assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / "
assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / "
assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / "
assert upretty(Adjoint(X)) == " †\nX "
assert upretty(Adjoint(X + Y)) == " †\n(X + Y) "
assert upretty(Adjoint(X) + Adjoint(Y)) == " † †\nX + Y "
assert upretty(Adjoint(X*Y)) == " †\n(X⋅Y) "
assert upretty(Adjoint(Y)*Adjoint(X)) == " † †\nY ⋅X "
assert upretty(Adjoint(X**2)) == \
" †\n⎛ 2⎞ \n⎝X ⎠ "
assert upretty(Adjoint(X)**2) == \
" 2\n⎛ †⎞ \n⎝X ⎠ "
assert upretty(Adjoint(Inverse(X))) == \
" †\n⎛ -1⎞ \n⎝X ⎠ "
assert upretty(Inverse(Adjoint(X))) == \
" -1\n⎛ †⎞ \n⎝X ⎠ "
assert upretty(Adjoint(Transpose(X))) == \
" †\n⎛ T⎞ \n⎝X ⎠ "
assert upretty(Transpose(Adjoint(X))) == \
" T\n⎛ †⎞ \n⎝X ⎠ "
def test_pretty_Trace_issue_9044():
X = Matrix([[1, 2], [3, 4]])
Y = Matrix([[2, 4], [6, 8]])
ascii_str_1 = \
"""\
/[1 2]\\
tr|[ ]|
\\[3 4]/\
"""
ucode_str_1 = \
"""\
⎛⎡1 2⎤⎞
tr⎜⎢ ⎥⎟
⎝⎣3 4⎦⎠\
"""
ascii_str_2 = \
"""\
/[1 2]\\ /[2 4]\\
tr|[ ]| + tr|[ ]|
\\[3 4]/ \\[6 8]/\
"""
ucode_str_2 = \
"""\
⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞
tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟
⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\
"""
assert pretty(Trace(X)) == ascii_str_1
assert upretty(Trace(X)) == ucode_str_1
assert pretty(Trace(X) + Trace(Y)) == ascii_str_2
assert upretty(Trace(X) + Trace(Y)) == ucode_str_2
def test_MatrixSlice():
n = Symbol('n', integer=True)
x, y, z, w, t, = symbols('x y z w t')
X = MatrixSymbol('X', n, n)
Y = MatrixSymbol('Y', 10, 10)
Z = MatrixSymbol('Z', 10, 10)
expr = MatrixSlice(X, (None, None, None), (None, None, None))
assert pretty(expr) == upretty(expr) == 'X[:, :]'
expr = X[x:x + 1, y:y + 1]
assert pretty(expr) == upretty(expr) == 'X[x:x + 1, y:y + 1]'
expr = X[x:x + 1:2, y:y + 1:2]
assert pretty(expr) == upretty(expr) == 'X[x:x + 1:2, y:y + 1:2]'
expr = X[:x, y:]
assert pretty(expr) == upretty(expr) == 'X[:x, y:]'
expr = X[:x, y:]
assert pretty(expr) == upretty(expr) == 'X[:x, y:]'
expr = X[x:, :y]
assert pretty(expr) == upretty(expr) == 'X[x:, :y]'
expr = X[x:y, z:w]
assert pretty(expr) == upretty(expr) == 'X[x:y, z:w]'
expr = X[x:y:t, w:t:x]
assert pretty(expr) == upretty(expr) == 'X[x:y:t, w:t:x]'
expr = X[x::y, t::w]
assert pretty(expr) == upretty(expr) == 'X[x::y, t::w]'
expr = X[:x:y, :t:w]
assert pretty(expr) == upretty(expr) == 'X[:x:y, :t:w]'
expr = X[::x, ::y]
assert pretty(expr) == upretty(expr) == 'X[::x, ::y]'
expr = MatrixSlice(X, (0, None, None), (0, None, None))
assert pretty(expr) == upretty(expr) == 'X[:, :]'
expr = MatrixSlice(X, (None, n, None), (None, n, None))
assert pretty(expr) == upretty(expr) == 'X[:, :]'
expr = MatrixSlice(X, (0, n, None), (0, n, None))
assert pretty(expr) == upretty(expr) == 'X[:, :]'
expr = MatrixSlice(X, (0, n, 2), (0, n, 2))
assert pretty(expr) == upretty(expr) == 'X[::2, ::2]'
expr = X[1:2:3, 4:5:6]
assert pretty(expr) == upretty(expr) == 'X[1:2:3, 4:5:6]'
expr = X[1:3:5, 4:6:8]
assert pretty(expr) == upretty(expr) == 'X[1:3:5, 4:6:8]'
expr = X[1:10:2]
assert pretty(expr) == upretty(expr) == 'X[1:10:2, :]'
expr = Y[:5, 1:9:2]
assert pretty(expr) == upretty(expr) == 'Y[:5, 1:9:2]'
expr = Y[:5, 1:10:2]
assert pretty(expr) == upretty(expr) == 'Y[:5, 1::2]'
expr = Y[5, :5:2]
assert pretty(expr) == upretty(expr) == 'Y[5:6, :5:2]'
expr = X[0:1, 0:1]
assert pretty(expr) == upretty(expr) == 'X[:1, :1]'
expr = X[0:1:2, 0:1:2]
assert pretty(expr) == upretty(expr) == 'X[:1:2, :1:2]'
expr = (Y + Z)[2:, 2:]
assert pretty(expr) == upretty(expr) == '(Y + Z)[2:, 2:]'
def test_MatrixExpressions():
n = Symbol('n', integer=True)
X = MatrixSymbol('X', n, n)
assert pretty(X) == upretty(X) == "X"
# Apply function elementwise (`ElementwiseApplyFunc`):
expr = (X.T*X).applyfunc(sin)
ascii_str = """\
/ T \\\n\
(d -> sin(d)).\\X *X/\
"""
ucode_str = """\
⎛ T ⎞\n\
(d ↦ sin(d))˳⎝X ⋅X⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
lamda = Lambda(x, 1/x)
expr = (n*X).applyfunc(lamda)
ascii_str = """\
/ 1\\ \n\
|x -> -|.(n*X)\n\
\\ x/ \
"""
ucode_str = """\
⎛ 1⎞ \n\
⎜x ↦ ─⎟˳(n⋅X)\n\
⎝ x⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_dotproduct():
from sympy.matrices import Matrix, MatrixSymbol
from sympy.matrices.expressions.dotproduct import DotProduct
n = symbols("n", integer=True)
A = MatrixSymbol('A', n, 1)
B = MatrixSymbol('B', n, 1)
C = Matrix(1, 3, [1, 2, 3])
D = Matrix(1, 3, [1, 3, 4])
assert pretty(DotProduct(A, B)) == "A*B"
assert pretty(DotProduct(C, D)) == "[1 2 3]*[1 3 4]"
assert upretty(DotProduct(A, B)) == "A⋅B"
assert upretty(DotProduct(C, D)) == "[1 2 3]⋅[1 3 4]"
def test_pretty_piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
ascii_str = \
"""\
/x for x < 1\n\
| \n\
< 2 \n\
|x otherwise\n\
\\ \
"""
ucode_str = \
"""\
⎧x for x < 1\n\
⎪ \n\
⎨ 2 \n\
⎪x otherwise\n\
⎩ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -Piecewise((x, x < 1), (x**2, True))
ascii_str = \
"""\
//x for x < 1\\\n\
|| |\n\
-|< 2 |\n\
||x otherwise|\n\
\\\\ /\
"""
ucode_str = \
"""\
⎛⎧x for x < 1⎞\n\
⎜⎪ ⎟\n\
-⎜⎨ 2 ⎟\n\
⎜⎪x otherwise⎟\n\
⎝⎩ ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
(y**2, x > 2), (1, True)) + 1
ascii_str = \
"""\
//x \\ \n\
||- for x < 2| \n\
||y | \n\
//x for x > 0\\ || | \n\
x + |< | + |< 2 | + 1\n\
\\\\y otherwise/ ||y for x > 2| \n\
|| | \n\
||1 otherwise| \n\
\\\\ / \
"""
ucode_str = \
"""\
⎛⎧x ⎞ \n\
⎜⎪─ for x < 2⎟ \n\
⎜⎪y ⎟ \n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\
x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\
⎜⎪ ⎟ \n\
⎜⎪1 otherwise⎟ \n\
⎝⎩ ⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
(y**2, x > 2), (1, True)) + 1
ascii_str = \
"""\
//x \\ \n\
||- for x < 2| \n\
||y | \n\
//x for x > 0\\ || | \n\
x - |< | + |< 2 | + 1\n\
\\\\y otherwise/ ||y for x > 2| \n\
|| | \n\
||1 otherwise| \n\
\\\\ / \
"""
ucode_str = \
"""\
⎛⎧x ⎞ \n\
⎜⎪─ for x < 2⎟ \n\
⎜⎪y ⎟ \n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\
x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\
⎜⎪ ⎟ \n\
⎜⎪1 otherwise⎟ \n\
⎝⎩ ⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x*Piecewise((x, x > 0), (y, True))
ascii_str = \
"""\
//x for x > 0\\\n\
x*|< |\n\
\\\\y otherwise/\
"""
ucode_str = \
"""\
⎛⎧x for x > 0⎞\n\
x⋅⎜⎨ ⎟\n\
⎝⎩y otherwise⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x >
2), (1, True))
ascii_str = \
"""\
//x \\\n\
||- for x < 2|\n\
||y |\n\
//x for x > 0\\ || |\n\
|< |*|< 2 |\n\
\\\\y otherwise/ ||y for x > 2|\n\
|| |\n\
||1 otherwise|\n\
\\\\ /\
"""
ucode_str = \
"""\
⎛⎧x ⎞\n\
⎜⎪─ for x < 2⎟\n\
⎜⎪y ⎟\n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\
⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\
⎜⎪ ⎟\n\
⎜⎪1 otherwise⎟\n\
⎝⎩ ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x
> 2), (1, True))
ascii_str = \
"""\
//x \\\n\
||- for x < 2|\n\
||y |\n\
//x for x > 0\\ || |\n\
-|< |*|< 2 |\n\
\\\\y otherwise/ ||y for x > 2|\n\
|| |\n\
||1 otherwise|\n\
\\\\ /\
"""
ucode_str = \
"""\
⎛⎧x ⎞\n\
⎜⎪─ for x < 2⎟\n\
⎜⎪y ⎟\n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\
-⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\
⎜⎪ ⎟\n\
⎜⎪1 otherwise⎟\n\
⎝⎩ ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1),
()), ((), (1, 0)), 1/y), True))
ascii_str = \
"""\
/ 1 \n\
| 0 for --- < 1\n\
| |y| \n\
| \n\
< 1 for |y| < 1\n\
| \n\
| __0, 2 /2, 1 | 1\\ \n\
|y*/__ | | -| otherwise \n\
\\ \\_|2, 2 \\ 1, 0 | y/ \
"""
ucode_str = \
"""\
⎧ 1 \n\
⎪ 0 for ─── < 1\n\
⎪ │y│ \n\
⎪ \n\
⎨ 1 for │y│ < 1\n\
⎪ \n\
⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\
⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\
⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# XXX: We have to use evaluate=False here because Piecewise._eval_power
# denests the power.
expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False)
ascii_str = \
"""\
2\n\
//x for x > 0\\ \n\
|< | \n\
\\\\y otherwise/ \
"""
ucode_str = \
"""\
2\n\
⎛⎧x for x > 0⎞ \n\
⎜⎨ ⎟ \n\
⎝⎩y otherwise⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_ITE():
expr = ITE(x, y, z)
assert pretty(expr) == (
'/y for x \n'
'< \n'
'\\z otherwise'
)
assert upretty(expr) == """\
⎧y for x \n\
⎨ \n\
⎩z otherwise\
"""
def test_pretty_seq():
expr = ()
ascii_str = \
"""\
()\
"""
ucode_str = \
"""\
()\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = []
ascii_str = \
"""\
[]\
"""
ucode_str = \
"""\
[]\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {}
expr_2 = {}
ascii_str = \
"""\
{}\
"""
ucode_str = \
"""\
{}\
"""
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
expr = (1/x,)
ascii_str = \
"""\
1 \n\
(-,)\n\
x \
"""
ucode_str = \
"""\
⎛1 ⎞\n\
⎜─,⎟\n\
⎝x ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
[x , -, x, y, -----------]\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
"""\
⎡ 2 ⎤\n\
⎢ 2 1 sin (θ)⎥\n\
⎢x , ─, x, y, ───────⎥\n\
⎢ x 2 ⎥\n\
⎣ cos (φ)⎦\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
(x , -, x, y, -----------)\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
"""\
⎛ 2 ⎞\n\
⎜ 2 1 sin (θ)⎟\n\
⎜x , ─, x, y, ───────⎟\n\
⎜ x 2 ⎟\n\
⎝ cos (φ)⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
(x , -, x, y, -----------)\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
"""\
⎛ 2 ⎞\n\
⎜ 2 1 sin (θ)⎟\n\
⎜x , ─, x, y, ───────⎟\n\
⎜ x 2 ⎟\n\
⎝ cos (φ)⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {x: sin(x)}
expr_2 = Dict({x: sin(x)})
ascii_str = \
"""\
{x: sin(x)}\
"""
ucode_str = \
"""\
{x: sin(x)}\
"""
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
expr = {1/x: 1/y, x: sin(x)**2}
expr_2 = Dict({1/x: 1/y, x: sin(x)**2})
ascii_str = \
"""\
1 1 2 \n\
{-: -, x: sin (x)}\n\
x y \
"""
ucode_str = \
"""\
⎧1 1 2 ⎫\n\
⎨─: ─, x: sin (x)⎬\n\
⎩x y ⎭\
"""
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
# There used to be a bug with pretty-printing sequences of even height.
expr = [x**2]
ascii_str = \
"""\
2 \n\
[x ]\
"""
ucode_str = \
"""\
⎡ 2⎤\n\
⎣x ⎦\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2,)
ascii_str = \
"""\
2 \n\
(x ,)\
"""
ucode_str = \
"""\
⎛ 2 ⎞\n\
⎝x ,⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Tuple(x**2)
ascii_str = \
"""\
2 \n\
(x ,)\
"""
ucode_str = \
"""\
⎛ 2 ⎞\n\
⎝x ,⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {x**2: 1}
expr_2 = Dict({x**2: 1})
ascii_str = \
"""\
2 \n\
{x : 1}\
"""
ucode_str = \
"""\
⎧ 2 ⎫\n\
⎨x : 1⎬\n\
⎩ ⎭\
"""
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
def test_any_object_in_sequence():
# Cf. issue 5306
b1 = Basic()
b2 = Basic(Basic())
expr = [b2, b1]
assert pretty(expr) == "[Basic(Basic()), Basic()]"
assert upretty(expr) == "[Basic(Basic()), Basic()]"
expr = {b2, b1}
assert pretty(expr) == "{Basic(), Basic(Basic())}"
assert upretty(expr) == "{Basic(), Basic(Basic())}"
expr = {b2: b1, b1: b2}
expr2 = Dict({b2: b1, b1: b2})
assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert pretty(
expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert upretty(
expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert upretty(
expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
def test_print_builtin_set():
assert pretty(set()) == 'set()'
assert upretty(set()) == 'set()'
assert pretty(frozenset()) == 'frozenset()'
assert upretty(frozenset()) == 'frozenset()'
s1 = {1/x, x}
s2 = frozenset(s1)
assert pretty(s1) == \
"""\
1 \n\
{-, x}
x \
"""
assert upretty(s1) == \
"""\
⎧1 ⎫
⎨─, x⎬
⎩x ⎭\
"""
assert pretty(s2) == \
"""\
1 \n\
frozenset({-, x})
x \
"""
assert upretty(s2) == \
"""\
⎛⎧1 ⎫⎞
frozenset⎜⎨─, x⎬⎟
⎝⎩x ⎭⎠\
"""
def test_pretty_sets():
s = FiniteSet
assert pretty(s(*[x*y, x**2])) == \
"""\
2 \n\
{x , x*y}\
"""
assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}"
assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
assert pretty({x*y, x**2}) == \
"""\
2 \n\
{x , x*y}\
"""
assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}"
assert pretty(set(range(1, 13))) == \
"{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
assert pretty(frozenset([x*y, x**2])) == \
"""\
2 \n\
frozenset({x , x*y})\
"""
assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})"
assert pretty(frozenset(range(1, 13))) == \
"frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})"
assert pretty(Range(0, 3, 1)) == '{0, 1, 2}'
ascii_str = '{0, 1, ..., 29}'
ucode_str = '{0, 1, …, 29}'
assert pretty(Range(0, 30, 1)) == ascii_str
assert upretty(Range(0, 30, 1)) == ucode_str
ascii_str = '{30, 29, ..., 2}'
ucode_str = '{30, 29, …, 2}'
assert pretty(Range(30, 1, -1)) == ascii_str
assert upretty(Range(30, 1, -1)) == ucode_str
ascii_str = '{0, 2, ...}'
ucode_str = '{0, 2, …}'
assert pretty(Range(0, oo, 2)) == ascii_str
assert upretty(Range(0, oo, 2)) == ucode_str
ascii_str = '{..., 2, 0}'
ucode_str = '{…, 2, 0}'
assert pretty(Range(oo, -2, -2)) == ascii_str
assert upretty(Range(oo, -2, -2)) == ucode_str
ascii_str = '{-2, -3, ...}'
ucode_str = '{-2, -3, …}'
assert pretty(Range(-2, -oo, -1)) == ascii_str
assert upretty(Range(-2, -oo, -1)) == ucode_str
def test_pretty_SetExpr():
iv = Interval(1, 3)
se = SetExpr(iv)
ascii_str = "SetExpr([1, 3])"
ucode_str = "SetExpr([1, 3])"
assert pretty(se) == ascii_str
assert upretty(se) == ucode_str
def test_pretty_ImageSet():
imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
ascii_str = '{x + y | x in {1, 2, 3} , y in {3, 4}}'
ucode_str = '{x + y | x ∊ {1, 2, 3} , y ∊ {3, 4}}'
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}'
ucode_str = '{x + y | (x, y) ∊ {1, 2, 3} × {3, 4}}'
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
imgset = ImageSet(Lambda(x, x**2), S.Naturals)
ascii_str = \
' 2 \n'\
'{x | x in Naturals}'
ucode_str = '''\
⎧ 2 ⎫\n\
⎨x | x ∊ ℕ⎬\n\
⎩ ⎭'''
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
def test_pretty_ConditionSet():
from sympy import ConditionSet
ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}'
ucode_str = '{x | x ∊ ℝ ∧ (sin(x) = 0)}'
assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str
assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str
assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}'
assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}'
assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet"
assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "∅"
assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}'
assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}'
def test_pretty_ComplexRegion():
from sympy import ComplexRegion
ucode_str = '{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}'
assert upretty(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == ucode_str
ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}'
assert upretty(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
def test_pretty_Union_issue_10414():
a, b = Interval(2, 3), Interval(4, 7)
ucode_str = '[2, 3] ∪ [4, 7]'
ascii_str = '[2, 3] U [4, 7]'
assert upretty(Union(a, b)) == ucode_str
assert pretty(Union(a, b)) == ascii_str
def test_pretty_Intersection_issue_10414():
x, y, z, w = symbols('x, y, z, w')
a, b = Interval(x, y), Interval(z, w)
ucode_str = '[x, y] ∩ [z, w]'
ascii_str = '[x, y] n [z, w]'
assert upretty(Intersection(a, b)) == ucode_str
assert pretty(Intersection(a, b)) == ascii_str
def test_ProductSet_exponent():
ucode_str = ' 1\n[0, 1] '
assert upretty(Interval(0, 1)**1) == ucode_str
ucode_str = ' 2\n[0, 1] '
assert upretty(Interval(0, 1)**2) == ucode_str
def test_ProductSet_parenthesis():
ucode_str = '([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])'
a, b = Interval(2, 3), Interval(4, 7)
assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str
def test_ProductSet_prod_char_issue_10413():
ascii_str = '[2, 3] x [4, 7]'
ucode_str = '[2, 3] × [4, 7]'
a, b = Interval(2, 3), Interval(4, 7)
assert pretty(a*b) == ascii_str
assert upretty(a*b) == ucode_str
def test_pretty_sequences():
s1 = SeqFormula(a**2, (0, oo))
s2 = SeqPer((1, 2))
ascii_str = '[0, 1, 4, 9, ...]'
ucode_str = '[0, 1, 4, 9, …]'
assert pretty(s1) == ascii_str
assert upretty(s1) == ucode_str
ascii_str = '[1, 2, 1, 2, ...]'
ucode_str = '[1, 2, 1, 2, …]'
assert pretty(s2) == ascii_str
assert upretty(s2) == ucode_str
s3 = SeqFormula(a**2, (0, 2))
s4 = SeqPer((1, 2), (0, 2))
ascii_str = '[0, 1, 4]'
ucode_str = '[0, 1, 4]'
assert pretty(s3) == ascii_str
assert upretty(s3) == ucode_str
ascii_str = '[1, 2, 1]'
ucode_str = '[1, 2, 1]'
assert pretty(s4) == ascii_str
assert upretty(s4) == ucode_str
s5 = SeqFormula(a**2, (-oo, 0))
s6 = SeqPer((1, 2), (-oo, 0))
ascii_str = '[..., 9, 4, 1, 0]'
ucode_str = '[…, 9, 4, 1, 0]'
assert pretty(s5) == ascii_str
assert upretty(s5) == ucode_str
ascii_str = '[..., 2, 1, 2, 1]'
ucode_str = '[…, 2, 1, 2, 1]'
assert pretty(s6) == ascii_str
assert upretty(s6) == ucode_str
ascii_str = '[1, 3, 5, 11, ...]'
ucode_str = '[1, 3, 5, 11, …]'
assert pretty(SeqAdd(s1, s2)) == ascii_str
assert upretty(SeqAdd(s1, s2)) == ucode_str
ascii_str = '[1, 3, 5]'
ucode_str = '[1, 3, 5]'
assert pretty(SeqAdd(s3, s4)) == ascii_str
assert upretty(SeqAdd(s3, s4)) == ucode_str
ascii_str = '[..., 11, 5, 3, 1]'
ucode_str = '[…, 11, 5, 3, 1]'
assert pretty(SeqAdd(s5, s6)) == ascii_str
assert upretty(SeqAdd(s5, s6)) == ucode_str
ascii_str = '[0, 2, 4, 18, ...]'
ucode_str = '[0, 2, 4, 18, …]'
assert pretty(SeqMul(s1, s2)) == ascii_str
assert upretty(SeqMul(s1, s2)) == ucode_str
ascii_str = '[0, 2, 4]'
ucode_str = '[0, 2, 4]'
assert pretty(SeqMul(s3, s4)) == ascii_str
assert upretty(SeqMul(s3, s4)) == ucode_str
ascii_str = '[..., 18, 4, 2, 0]'
ucode_str = '[…, 18, 4, 2, 0]'
assert pretty(SeqMul(s5, s6)) == ascii_str
assert upretty(SeqMul(s5, s6)) == ucode_str
# Sequences with symbolic limits, issue 12629
s7 = SeqFormula(a**2, (a, 0, x))
raises(NotImplementedError, lambda: pretty(s7))
raises(NotImplementedError, lambda: upretty(s7))
b = Symbol('b')
s8 = SeqFormula(b*a**2, (a, 0, 2))
ascii_str = '[0, b, 4*b]'
ucode_str = '[0, b, 4⋅b]'
assert pretty(s8) == ascii_str
assert upretty(s8) == ucode_str
def test_pretty_FourierSeries():
f = fourier_series(x, (x, -pi, pi))
ascii_str = \
"""\
2*sin(3*x) \n\
2*sin(x) - sin(2*x) + ---------- + ...\n\
3 \
"""
ucode_str = \
"""\
2⋅sin(3⋅x) \n\
2⋅sin(x) - sin(2⋅x) + ────────── + …\n\
3 \
"""
assert pretty(f) == ascii_str
assert upretty(f) == ucode_str
def test_pretty_FormalPowerSeries():
f = fps(log(1 + x))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ -k k \n\
\\ -(-1) *x \n\
/ -----------\n\
/ k \n\
/___, \n\
k = 1 \
"""
ucode_str = \
"""\
∞ \n\
____ \n\
╲ \n\
╲ -k k \n\
╲ -(-1) ⋅x \n\
╱ ───────────\n\
╱ k \n\
╱ \n\
‾‾‾‾ \n\
k = 1 \
"""
assert pretty(f) == ascii_str
assert upretty(f) == ucode_str
def test_pretty_limits():
expr = Limit(x, x, oo)
ascii_str = \
"""\
lim x\n\
x->oo \
"""
ucode_str = \
"""\
lim x\n\
x─→∞ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x**2, x, 0)
ascii_str = \
"""\
2\n\
lim x \n\
x->0+ \
"""
ucode_str = \
"""\
2\n\
lim x \n\
x─→0⁺ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(1/x, x, 0)
ascii_str = \
"""\
1\n\
lim -\n\
x->0+x\
"""
ucode_str = \
"""\
1\n\
lim ─\n\
x─→0⁺x\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x)/x, x, 0)
ascii_str = \
"""\
/sin(x)\\\n\
lim |------|\n\
x->0+\\ x /\
"""
ucode_str = \
"""\
⎛sin(x)⎞\n\
lim ⎜──────⎟\n\
x─→0⁺⎝ x ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x)/x, x, 0, "-")
ascii_str = \
"""\
/sin(x)\\\n\
lim |------|\n\
x->0-\\ x /\
"""
ucode_str = \
"""\
⎛sin(x)⎞\n\
lim ⎜──────⎟\n\
x─→0⁻⎝ x ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x + sin(x), x, 0)
ascii_str = \
"""\
lim (x + sin(x))\n\
x->0+ \
"""
ucode_str = \
"""\
lim (x + sin(x))\n\
x─→0⁺ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x, x, 0)**2
ascii_str = \
"""\
2\n\
/ lim x\\ \n\
\\x->0+ / \
"""
ucode_str = \
"""\
2\n\
⎛ lim x⎞ \n\
⎝x─→0⁺ ⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x*Limit(y/2,y,0), x, 0)
ascii_str = \
"""\
/ /y\\\\\n\
lim |x* lim |-||\n\
x->0+\\ y->0+\\2//\
"""
ucode_str = \
"""\
⎛ ⎛y⎞⎞\n\
lim ⎜x⋅ lim ⎜─⎟⎟\n\
x─→0⁺⎝ y─→0⁺⎝2⎠⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*Limit(x*Limit(y/2,y,0), x, 0)
ascii_str = \
"""\
/ /y\\\\\n\
2* lim |x* lim |-||\n\
x->0+\\ y->0+\\2//\
"""
ucode_str = \
"""\
⎛ ⎛y⎞⎞\n\
2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\
x─→0⁺⎝ y─→0⁺⎝2⎠⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x), x, 0, dir='+-')
ascii_str = \
"""\
lim sin(x)\n\
x->0 \
"""
ucode_str = \
"""\
lim sin(x)\n\
x─→0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_ComplexRootOf():
expr = rootof(x**5 + 11*x - 2, 0)
ascii_str = \
"""\
/ 5 \\\n\
CRootOf\\x + 11*x - 2, 0/\
"""
ucode_str = \
"""\
⎛ 5 ⎞\n\
CRootOf⎝x + 11⋅x - 2, 0⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_RootSum():
expr = RootSum(x**5 + 11*x - 2, auto=False)
ascii_str = \
"""\
/ 5 \\\n\
RootSum\\x + 11*x - 2/\
"""
ucode_str = \
"""\
⎛ 5 ⎞\n\
RootSum⎝x + 11⋅x - 2⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z)))
ascii_str = \
"""\
/ 5 z\\\n\
RootSum\\x + 11*x - 2, z -> e /\
"""
ucode_str = \
"""\
⎛ 5 z⎞\n\
RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_GroebnerBasis():
expr = groebner([], x, y)
ascii_str = \
"""\
GroebnerBasis([], x, y, domain=ZZ, order=lex)\
"""
ucode_str = \
"""\
GroebnerBasis([], x, y, domain=ℤ, order=lex)\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
expr = groebner(F, x, y, order='grlex')
ascii_str = \
"""\
/[ 2 2 ] \\\n\
GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\
"""
ucode_str = \
"""\
⎛⎡ 2 2 ⎤ ⎞\n\
GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = expr.fglm('lex')
ascii_str = \
"""\
/[ 2 4 3 2 ] \\\n\
GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\
"""
ucode_str = \
"""\
⎛⎡ 2 4 3 2 ⎤ ⎞\n\
GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_UniversalSet():
assert pretty(S.UniversalSet) == "UniversalSet"
assert upretty(S.UniversalSet) == '𝕌'
def test_pretty_Boolean():
expr = Not(x, evaluate=False)
assert pretty(expr) == "Not(x)"
assert upretty(expr) == "¬x"
expr = And(x, y)
assert pretty(expr) == "And(x, y)"
assert upretty(expr) == "x ∧ y"
expr = Or(x, y)
assert pretty(expr) == "Or(x, y)"
assert upretty(expr) == "x ∨ y"
syms = symbols('a:f')
expr = And(*syms)
assert pretty(expr) == "And(a, b, c, d, e, f)"
assert upretty(expr) == "a ∧ b ∧ c ∧ d ∧ e ∧ f"
expr = Or(*syms)
assert pretty(expr) == "Or(a, b, c, d, e, f)"
assert upretty(expr) == "a ∨ b ∨ c ∨ d ∨ e ∨ f"
expr = Xor(x, y, evaluate=False)
assert pretty(expr) == "Xor(x, y)"
assert upretty(expr) == "x ⊻ y"
expr = Nand(x, y, evaluate=False)
assert pretty(expr) == "Nand(x, y)"
assert upretty(expr) == "x ⊼ y"
expr = Nor(x, y, evaluate=False)
assert pretty(expr) == "Nor(x, y)"
assert upretty(expr) == "x ⊽ y"
expr = Implies(x, y, evaluate=False)
assert pretty(expr) == "Implies(x, y)"
assert upretty(expr) == "x → y"
# don't sort args
expr = Implies(y, x, evaluate=False)
assert pretty(expr) == "Implies(y, x)"
assert upretty(expr) == "y → x"
expr = Equivalent(x, y, evaluate=False)
assert pretty(expr) == "Equivalent(x, y)"
assert upretty(expr) == "x ⇔ y"
expr = Equivalent(y, x, evaluate=False)
assert pretty(expr) == "Equivalent(x, y)"
assert upretty(expr) == "x ⇔ y"
def test_pretty_Domain():
expr = FF(23)
assert pretty(expr) == "GF(23)"
assert upretty(expr) == "ℤ₂₃"
expr = ZZ
assert pretty(expr) == "ZZ"
assert upretty(expr) == "ℤ"
expr = QQ
assert pretty(expr) == "QQ"
assert upretty(expr) == "ℚ"
expr = RR
assert pretty(expr) == "RR"
assert upretty(expr) == "ℝ"
expr = QQ[x]
assert pretty(expr) == "QQ[x]"
assert upretty(expr) == "ℚ[x]"
expr = QQ[x, y]
assert pretty(expr) == "QQ[x, y]"
assert upretty(expr) == "ℚ[x, y]"
expr = ZZ.frac_field(x)
assert pretty(expr) == "ZZ(x)"
assert upretty(expr) == "ℤ(x)"
expr = ZZ.frac_field(x, y)
assert pretty(expr) == "ZZ(x, y)"
assert upretty(expr) == "ℤ(x, y)"
expr = QQ.poly_ring(x, y, order=grlex)
assert pretty(expr) == "QQ[x, y, order=grlex]"
assert upretty(expr) == "ℚ[x, y, order=grlex]"
expr = QQ.poly_ring(x, y, order=ilex)
assert pretty(expr) == "QQ[x, y, order=ilex]"
assert upretty(expr) == "ℚ[x, y, order=ilex]"
def test_pretty_prec():
assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000"
assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000"
assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3"
assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [
"0.300000000000000*x",
"x*0.300000000000000"
]
assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [
"0.3*x",
"x*0.3"
]
assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [
"0.3*x",
"x*0.3"
]
def test_pprint():
import sys
from io import StringIO
fd = StringIO()
sso = sys.stdout
sys.stdout = fd
try:
pprint(pi, use_unicode=False, wrap_line=False)
finally:
sys.stdout = sso
assert fd.getvalue() == 'pi\n'
def test_pretty_class():
"""Test that the printer dispatcher correctly handles classes."""
class C:
pass # C has no .__class__ and this was causing problems
class D:
pass
assert pretty( C ) == str( C )
assert pretty( D ) == str( D )
def test_pretty_no_wrap_line():
huge_expr = 0
for i in range(20):
huge_expr += i*sin(i + x)
assert xpretty(huge_expr ).find('\n') != -1
assert xpretty(huge_expr, wrap_line=False).find('\n') == -1
def test_settings():
raises(TypeError, lambda: pretty(S(4), method="garbage"))
def test_pretty_sum():
from sympy.abc import x, a, b, k, m, n
expr = Sum(k**k, (k, 0, n))
ascii_str = \
"""\
n \n\
___ \n\
\\ ` \n\
\\ k\n\
/ k \n\
/__, \n\
k = 0 \
"""
ucode_str = \
"""\
n \n\
___ \n\
╲ \n\
╲ k\n\
╱ k \n\
╱ \n\
‾‾‾ \n\
k = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**k, (k, oo, n))
ascii_str = \
"""\
n \n\
___ \n\
\\ ` \n\
\\ k\n\
/ k \n\
/__, \n\
k = oo \
"""
ucode_str = \
"""\
n \n\
___ \n\
╲ \n\
╲ k\n\
╱ k \n\
╱ \n\
‾‾‾ \n\
k = ∞ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n))
ascii_str = \
"""\
n \n\
n \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
"""\
n \n\
n \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(
Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo))))
ascii_str = \
"""\
oo \n\
/ \n\
| \n\
| x \n\
| x dx \n\
| \n\
/ \n\
-oo \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
"""\
∞ \n\
⌠ \n\
⎮ x \n\
⎮ x dx \n\
⌡ \n\
-∞ \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (
k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo))))
ascii_str = \
"""\
oo \n\
/ \n\
| \n\
| x \n\
| x dx \n\
| \n\
/ \n\
-oo \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
2 2 1 x \n\
k = n + n + x + x + - + - \n\
x n \
"""
ucode_str = \
"""\
∞ \n\
⌠ \n\
⎮ x \n\
⎮ x dx \n\
⌡ \n\
-∞ \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
2 2 1 x \n\
k = n + n + x + x + ─ + ─ \n\
x n \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(
Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x)))
ascii_str = \
"""\
2 2 1 x \n\
n + n + x + x + - + - \n\
x n \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
"""\
2 2 1 x \n\
n + n + x + x + ─ + ─ \n\
x n \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x, (x, 0, oo))
ascii_str = \
"""\
oo \n\
__ \n\
\\ ` \n\
) x\n\
/_, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
___ \n\
╲ \n\
╲ \n\
╱ x\n\
╱ \n\
‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x**2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
___ \n\
\\ ` \n\
\\ 2\n\
/ x \n\
/__, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
___ \n\
╲ \n\
╲ 2\n\
╱ x \n\
╱ \n\
‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x/2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
___ \n\
\\ ` \n\
\\ x\n\
) -\n\
/ 2\n\
/__, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
____ \n\
╲ \n\
╲ \n\
╲ x\n\
╱ ─\n\
╱ 2\n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x**3/2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ 3\n\
\\ x \n\
/ --\n\
/ 2 \n\
/___, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
____ \n\
╲ \n\
╲ 3\n\
╲ x \n\
╱ ──\n\
╱ 2 \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum((x**3*y**(x/2))**n, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ n\n\
\\ / x\\ \n\
) | -| \n\
/ | 3 2| \n\
/ \\x *y / \n\
/___, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
_____ \n\
╲ \n\
╲ \n\
╲ n\n\
╲ ⎛ x⎞ \n\
╱ ⎜ ─⎟ \n\
╱ ⎜ 3 2⎟ \n\
╱ ⎝x ⋅y ⎠ \n\
╱ \n\
‾‾‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/x**2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ 1 \n\
\\ --\n\
/ 2\n\
/ x \n\
/___, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
____ \n\
╲ \n\
╲ 1 \n\
╲ ──\n\
╱ 2\n\
╱ x \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/y**(a/b), (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ -a \n\
\\ ---\n\
/ b \n\
/ y \n\
/___, \n\
x = 0 \
"""
ucode_str = \
"""\
∞ \n\
____ \n\
╲ \n\
╲ -a \n\
╲ ───\n\
╱ b \n\
╱ y \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2))
ascii_str = \
"""\
2 oo \n\
____ ____ \n\
\\ ` \\ ` \n\
\\ \\ -a\n\
\\ \\ --\n\
/ / b \n\
/ / y \n\
/___, /___, \n\
y = 1 x = 0 \
"""
ucode_str = \
"""\
2 ∞ \n\
____ ____ \n\
╲ ╲ \n\
╲ ╲ -a\n\
╲ ╲ ──\n\
╱ ╱ b \n\
╱ ╱ y \n\
╱ ╱ \n\
‾‾‾‾ ‾‾‾‾ \n\
y = 1 x = 0 \
"""
expr = Sum(1/(1 + 1/(
1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k)
ascii_str = \
"""\
1 \n\
1 + - \n\
oo n \n\
_____ _____ \n\
\\ ` \\ ` \n\
\\ \\ / 1 \\ \n\
\\ \\ |1 + ---------| \n\
\\ \\ | 1 | 1 \n\
) ) | 1 + -----| + -----\n\
/ / | 1| 1\n\
/ / | 1 + -| 1 + -\n\
/ / \\ k/ k\n\
/____, /____, \n\
1 k = 111 \n\
k = ----- \n\
m + 1 \
"""
ucode_str = \
"""\
1 \n\
1 + ─ \n\
∞ n \n\
______ ______ \n\
╲ ╲ \n\
╲ ╲ \n\
╲ ╲ ⎛ 1 ⎞ \n\
╲ ╲ ⎜1 + ─────────⎟ \n\
╲ ╲ ⎜ 1 ⎟ 1 \n\
╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\
╱ ╱ ⎜ 1⎟ 1\n\
╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\
╱ ╱ ⎝ k⎠ k\n\
╱ ╱ \n\
‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\
1 k = 111 \n\
k = ───── \n\
m + 1 \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_units():
expr = joule
ascii_str1 = \
"""\
2\n\
kilogram*meter \n\
---------------\n\
2 \n\
second \
"""
unicode_str1 = \
"""\
2\n\
kilogram⋅meter \n\
───────────────\n\
2 \n\
second \
"""
ascii_str2 = \
"""\
2\n\
3*x*y*kilogram*meter \n\
---------------------\n\
2 \n\
second \
"""
unicode_str2 = \
"""\
2\n\
3⋅x⋅y⋅kilogram⋅meter \n\
─────────────────────\n\
2 \n\
second \
"""
from sympy.physics.units import kg, m, s
assert upretty(expr) == "joule"
assert pretty(expr) == "joule"
assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1
assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1
assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2
assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2
def test_pretty_Subs():
f = Function('f')
expr = Subs(f(x), x, ph**2)
ascii_str = \
"""\
(f(x))| 2\n\
|x=phi \
"""
unicode_str = \
"""\
(f(x))│ 2\n\
│x=φ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Subs(f(x).diff(x), x, 0)
ascii_str = \
"""\
/d \\| \n\
|--(f(x))|| \n\
\\dx /|x=0\
"""
unicode_str = \
"""\
⎛d ⎞│ \n\
⎜──(f(x))⎟│ \n\
⎝dx ⎠│x=0\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
ascii_str = \
"""\
/d \\| \n\
|--(f(x))|| \n\
|dx || \n\
|--------|| \n\
\\ y /|x=0, y=1/2\
"""
unicode_str = \
"""\
⎛d ⎞│ \n\
⎜──(f(x))⎟│ \n\
⎜dx ⎟│ \n\
⎜────────⎟│ \n\
⎝ y ⎠│x=0, y=1/2\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
def test_gammas():
assert upretty(lowergamma(x, y)) == "γ(x, y)"
assert upretty(uppergamma(x, y)) == "Γ(x, y)"
assert xpretty(gamma(x), use_unicode=True) == 'Γ(x)'
assert xpretty(gamma, use_unicode=True) == 'Γ'
assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == 'γ(x)'
assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == 'γ'
def test_beta():
assert xpretty(beta(x,y), use_unicode=True) == 'Β(x, y)'
assert xpretty(beta(x,y), use_unicode=False) == 'B(x, y)'
assert xpretty(beta, use_unicode=True) == 'Β'
assert xpretty(beta, use_unicode=False) == 'B'
mybeta = Function('beta')
assert xpretty(mybeta(x), use_unicode=True) == 'β(x)'
assert xpretty(mybeta(x, y, z), use_unicode=False) == 'beta(x, y, z)'
assert xpretty(mybeta, use_unicode=True) == 'β'
# test that notation passes to subclasses of the same name only
def test_function_subclass_different_name():
class mygamma(gamma):
pass
assert xpretty(mygamma, use_unicode=True) == r"mygamma"
assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)"
def test_SingularityFunction():
assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == (
"""\
n\n\
<x> \
""")
assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == (
"""\
n\n\
<x - 1> \
""")
assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == (
"""\
n\n\
<x + 1> \
""")
assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == (
"""\
n\n\
<-a + x> \
""")
assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == (
"""\
n\n\
<x - y> \
""")
assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == (
"""\
n\n\
<x> \
""")
assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == (
"""\
n\n\
<x - 1> \
""")
assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == (
"""\
n\n\
<x + 1> \
""")
assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == (
"""\
n\n\
<-a + x> \
""")
assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == (
"""\
n\n\
<x - y> \
""")
def test_deltas():
assert xpretty(DiracDelta(x), use_unicode=True) == 'δ(x)'
assert xpretty(DiracDelta(x, 1), use_unicode=True) == \
"""\
(1) \n\
δ (x)\
"""
assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \
"""\
(1) \n\
x⋅δ (x)\
"""
def test_hyper():
expr = hyper((), (), z)
ucode_str = \
"""\
┌─ ⎛ │ ⎞\n\
├─ ⎜ │ z⎟\n\
0╵ 0 ⎝ │ ⎠\
"""
ascii_str = \
"""\
_ \n\
|_ / | \\\n\
| | | z|\n\
0 0 \\ | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((), (1,), x)
ucode_str = \
"""\
┌─ ⎛ │ ⎞\n\
├─ ⎜ │ x⎟\n\
0╵ 1 ⎝1 │ ⎠\
"""
ascii_str = \
"""\
_ \n\
|_ / | \\\n\
| | | x|\n\
0 1 \\1 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper([2], [1], x)
ucode_str = \
"""\
┌─ ⎛2 │ ⎞\n\
├─ ⎜ │ x⎟\n\
1╵ 1 ⎝1 │ ⎠\
"""
ascii_str = \
"""\
_ \n\
|_ /2 | \\\n\
| | | x|\n\
1 1 \\1 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x)
ucode_str = \
"""\
⎛ π │ ⎞\n\
┌─ ⎜ ─, -2⋅k │ ⎟\n\
├─ ⎜ 3 │ x⎟\n\
2╵ 4 ⎜ │ ⎟\n\
⎝3, 4, 5, -3 │ ⎠\
"""
ascii_str = \
"""\
\n\
_ / pi | \\\n\
|_ | --, -2*k | |\n\
| | 3 | x|\n\
2 4 | | |\n\
\\3, 4, 5, -3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2)
ucode_str = \
"""\
┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\
├─ ⎜ │ x ⎟\n\
3╵ 4 ⎝3, 4, 5, -3 │ ⎠\
"""
ascii_str = \
"""\
_ \n\
|_ /pi, 2/3, -2*k | 2\\\n\
| | | x |\n\
3 4 \\ 3, 4, 5, -3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1))
ucode_str = \
"""\
⎛ │ 1 ⎞\n\
⎜ │ ─────────────⎟\n\
⎜ │ 1 ⎟\n\
┌─ ⎜1, 2 │ 1 + ─────────⎟\n\
├─ ⎜ │ 1 ⎟\n\
2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\
⎜ │ 1⎟\n\
⎜ │ 1 + ─⎟\n\
⎝ │ x⎠\
"""
ascii_str = \
"""\
\n\
/ | 1 \\\n\
| | -------------|\n\
_ | | 1 |\n\
|_ |1, 2 | 1 + ---------|\n\
| | | 1 |\n\
2 2 |3, 4 | 1 + -----|\n\
| | 1|\n\
| | 1 + -|\n\
\\ | x/\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_meijerg():
expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z)
ucode_str = \
"""\
╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\
│╶┐ ⎜ │ z⎟\n\
╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\
"""
ascii_str = \
"""\
__2, 3 /pi, pi, x 1 | \\\n\
/__ | | z|\n\
\\_|4, 5 \\ 0, 1 1, 2, 3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2)
ucode_str = \
"""\
⎛ π │ ⎞\n\
╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\
│╶┐ ⎜ 7 │ z ⎟\n\
╰─╯5, 0 ⎜ │ ⎟\n\
⎝ │ ⎠\
"""
ascii_str = \
"""\
/ pi | \\\n\
__0, 2 |1, -- 2, pi, 5 | 2|\n\
/__ | 7 | z |\n\
\\_|5, 0 | | |\n\
\\ | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ucode_str = \
"""\
╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\
│╶┐ ⎜ │ z⎟\n\
╰─╯11, 2 ⎝ 1 1 │ ⎠\
"""
ascii_str = \
"""\
__ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\
/__ | | z|\n\
\\_|11, 2 \\ 1 1 | /\
"""
expr = meijerg([1]*10, [1], [1], [1], z)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1))
ucode_str = \
"""\
⎛ │ 1 ⎞\n\
⎜ │ ─────────────⎟\n\
⎜ │ 1 ⎟\n\
╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\
│╶┐ ⎜ │ 1 ⎟\n\
╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\
⎜ │ 1⎟\n\
⎜ │ 1 + ─⎟\n\
⎝ │ x⎠\
"""
ascii_str = \
"""\
/ | 1 \\\n\
| | -------------|\n\
| | 1 |\n\
__1, 2 |1, 2 4, 3 | 1 + ---------|\n\
/__ | | 1 |\n\
\\_|4, 3 | 3 4, 5 | 1 + -----|\n\
| | 1|\n\
| | 1 + -|\n\
\\ | x/\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(expr, x)
ucode_str = \
"""\
⌠ \n\
⎮ ⎛ │ 1 ⎞ \n\
⎮ ⎜ │ ─────────────⎟ \n\
⎮ ⎜ │ 1 ⎟ \n\
⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\
⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\
⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\
⎮ ⎜ │ 1⎟ \n\
⎮ ⎜ │ 1 + ─⎟ \n\
⎮ ⎝ │ x⎠ \n\
⌡ \
"""
ascii_str = \
"""\
/ \n\
| \n\
| / | 1 \\ \n\
| | | -------------| \n\
| | | 1 | \n\
| __1, 2 |1, 2 4, 3 | 1 + ---------| \n\
| /__ | | 1 | dx\n\
| \\_|4, 3 | 3 4, 5 | 1 + -----| \n\
| | | 1| \n\
| | | 1 + -| \n\
| \\ | x/ \n\
| \n\
/ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_noncommutative():
A, B, C = symbols('A,B,C', commutative=False)
expr = A*B*C**-1
ascii_str = \
"""\
-1\n\
A*B*C \
"""
ucode_str = \
"""\
-1\n\
A⋅B⋅C \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = C**-1*A*B
ascii_str = \
"""\
-1 \n\
C *A*B\
"""
ucode_str = \
"""\
-1 \n\
C ⋅A⋅B\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A*C**-1*B
ascii_str = \
"""\
-1 \n\
A*C *B\
"""
ucode_str = \
"""\
-1 \n\
A⋅C ⋅B\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A*C**-1*B/x
ascii_str = \
"""\
-1 \n\
A*C *B\n\
-------\n\
x \
"""
ucode_str = \
"""\
-1 \n\
A⋅C ⋅B\n\
───────\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_special_functions():
x, y = symbols("x y")
# atan2
expr = atan2(y/sqrt(200), sqrt(x))
ascii_str = \
"""\
/ ___ \\\n\
|\\/ 2 *y ___|\n\
atan2|-------, \\/ x |\n\
\\ 20 /\
"""
ucode_str = \
"""\
⎛√2⋅y ⎞\n\
atan2⎜────, √x⎟\n\
⎝ 20 ⎠\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_geometry():
e = Segment((0, 1), (0, 2))
assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))'
e = Ray((1, 1), angle=4.02*pi)
assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))'
def test_expint():
expr = Ei(x)
string = 'Ei(x)'
assert pretty(expr) == string
assert upretty(expr) == string
expr = expint(1, z)
ucode_str = "E₁(z)"
ascii_str = "expint(1, z)"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
assert pretty(Shi(x)) == 'Shi(x)'
assert pretty(Si(x)) == 'Si(x)'
assert pretty(Ci(x)) == 'Ci(x)'
assert pretty(Chi(x)) == 'Chi(x)'
assert upretty(Shi(x)) == 'Shi(x)'
assert upretty(Si(x)) == 'Si(x)'
assert upretty(Ci(x)) == 'Ci(x)'
assert upretty(Chi(x)) == 'Chi(x)'
def test_elliptic_functions():
ascii_str = \
"""\
/ 1 \\\n\
K|-----|\n\
\\z + 1/\
"""
ucode_str = \
"""\
⎛ 1 ⎞\n\
K⎜─────⎟\n\
⎝z + 1⎠\
"""
expr = elliptic_k(1/(z + 1))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ | 1 \\\n\
F|1|-----|\n\
\\ |z + 1/\
"""
ucode_str = \
"""\
⎛ │ 1 ⎞\n\
F⎜1│─────⎟\n\
⎝ │z + 1⎠\
"""
expr = elliptic_f(1, 1/(1 + z))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ 1 \\\n\
E|-----|\n\
\\z + 1/\
"""
ucode_str = \
"""\
⎛ 1 ⎞\n\
E⎜─────⎟\n\
⎝z + 1⎠\
"""
expr = elliptic_e(1/(z + 1))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ | 1 \\\n\
E|1|-----|\n\
\\ |z + 1/\
"""
ucode_str = \
"""\
⎛ │ 1 ⎞\n\
E⎜1│─────⎟\n\
⎝ │z + 1⎠\
"""
expr = elliptic_e(1, 1/(1 + z))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ |4\\\n\
Pi|3|-|\n\
\\ |x/\
"""
ucode_str = \
"""\
⎛ │4⎞\n\
Π⎜3│─⎟\n\
⎝ │x⎠\
"""
expr = elliptic_pi(3, 4/x)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ 4| \\\n\
Pi|3; -|6|\n\
\\ x| /\
"""
ucode_str = \
"""\
⎛ 4│ ⎞\n\
Π⎜3; ─│6⎟\n\
⎝ x│ ⎠\
"""
expr = elliptic_pi(3, 4/x, 6)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_RandomDomain():
from sympy.stats import Normal, Die, Exponential, pspace, where
X = Normal('x1', 0, 1)
assert upretty(where(X > 0)) == "Domain: 0 < x₁ ∧ x₁ < ∞"
D = Die('d1', 6)
assert upretty(where(D > 4)) == 'Domain: d₁ = 5 ∨ d₁ = 6'
A = Exponential('a', 1)
B = Exponential('b', 1)
assert upretty(pspace(Tuple(A, B)).domain) == \
'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞'
def test_PrettyPoly():
F = QQ.frac_field(x, y)
R = QQ.poly_ring(x, y)
expr = F.convert(x/(x + y))
assert pretty(expr) == "x/(x + y)"
assert upretty(expr) == "x/(x + y)"
expr = R.convert(x + y)
assert pretty(expr) == "x + y"
assert upretty(expr) == "x + y"
def test_issue_6285():
assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 '
assert pretty(Pow(x, (1/pi))) == 'pi___\n\\/ x '
def test_issue_6359():
assert pretty(Integral(x**2, x)**2) == \
"""\
2
/ / \\ \n\
| | | \n\
| | 2 | \n\
| | x dx| \n\
| | | \n\
\\/ / \
"""
assert upretty(Integral(x**2, x)**2) == \
"""\
2
⎛⌠ ⎞ \n\
⎜⎮ 2 ⎟ \n\
⎜⎮ x dx⎟ \n\
⎝⌡ ⎠ \
"""
assert pretty(Sum(x**2, (x, 0, 1))**2) == \
"""\
2
/ 1 \\ \n\
| ___ | \n\
| \\ ` | \n\
| \\ 2| \n\
| / x | \n\
| /__, | \n\
\\x = 0 / \
"""
assert upretty(Sum(x**2, (x, 0, 1))**2) == \
"""\
2
⎛ 1 ⎞ \n\
⎜ ___ ⎟ \n\
⎜ ╲ ⎟ \n\
⎜ ╲ 2⎟ \n\
⎜ ╱ x ⎟ \n\
⎜ ╱ ⎟ \n\
⎜ ‾‾‾ ⎟ \n\
⎝x = 0 ⎠ \
"""
assert pretty(Product(x**2, (x, 1, 2))**2) == \
"""\
2
/ 2 \\ \n\
|______ | \n\
| | | 2| \n\
| | | x | \n\
| | | | \n\
\\x = 1 / \
"""
assert upretty(Product(x**2, (x, 1, 2))**2) == \
"""\
2
⎛ 2 ⎞ \n\
⎜─┬──┬─ ⎟ \n\
⎜ │ │ 2⎟ \n\
⎜ │ │ x ⎟ \n\
⎜ │ │ ⎟ \n\
⎝x = 1 ⎠ \
"""
f = Function('f')
assert pretty(Derivative(f(x), x)**2) == \
"""\
2
/d \\ \n\
|--(f(x))| \n\
\\dx / \
"""
assert upretty(Derivative(f(x), x)**2) == \
"""\
2
⎛d ⎞ \n\
⎜──(f(x))⎟ \n\
⎝dx ⎠ \
"""
def test_issue_6739():
ascii_str = \
"""\
1 \n\
-----\n\
___\n\
\\/ x \
"""
ucode_str = \
"""\
1 \n\
──\n\
√x\
"""
assert pretty(1/sqrt(x)) == ascii_str
assert upretty(1/sqrt(x)) == ucode_str
def test_complicated_symbol_unchanged():
for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]:
assert pretty(Symbol(symb_name)) == symb_name
def test_categories():
from sympy.categories import (Object, IdentityMorphism,
NamedMorphism, Category, Diagram, DiagramGrid)
A1 = Object("A1")
A2 = Object("A2")
A3 = Object("A3")
f1 = NamedMorphism(A1, A2, "f1")
f2 = NamedMorphism(A2, A3, "f2")
id_A1 = IdentityMorphism(A1)
K1 = Category("K1")
assert pretty(A1) == "A1"
assert upretty(A1) == "A₁"
assert pretty(f1) == "f1:A1-->A2"
assert upretty(f1) == "f₁:A₁——▶A₂"
assert pretty(id_A1) == "id:A1-->A1"
assert upretty(id_A1) == "id:A₁——▶A₁"
assert pretty(f2*f1) == "f2*f1:A1-->A3"
assert upretty(f2*f1) == "f₂∘f₁:A₁——▶A₃"
assert pretty(K1) == "K1"
assert upretty(K1) == "K₁"
# Test how diagrams are printed.
d = Diagram()
assert pretty(d) == "EmptySet"
assert upretty(d) == "∅"
d = Diagram({f1: "unique", f2: S.EmptySet})
assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \
"EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \
"EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}"
assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \
"id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}"
d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \
"EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \
"EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \
" ==> {f2*f1:A1-->A3: {unique}}"
assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \
"∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \
" ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}"
grid = DiagramGrid(d)
assert pretty(grid) == "A1 A2\n \nA3 "
assert upretty(grid) == "A₁ A₂\n \nA₃ "
def test_PrettyModules():
R = QQ.old_poly_ring(x, y)
F = R.free_module(2)
M = F.submodule([x, y], [1, x**2])
ucode_str = \
"""\
2\n\
ℚ[x, y] \
"""
ascii_str = \
"""\
2\n\
QQ[x, y] \
"""
assert upretty(F) == ucode_str
assert pretty(F) == ascii_str
ucode_str = \
"""\
╱ ⎡ 2⎤╲\n\
╲[x, y], ⎣1, x ⎦╱\
"""
ascii_str = \
"""\
2 \n\
<[x, y], [1, x ]>\
"""
assert upretty(M) == ucode_str
assert pretty(M) == ascii_str
I = R.ideal(x**2, y)
ucode_str = \
"""\
╱ 2 ╲\n\
╲x , y╱\
"""
ascii_str = \
"""\
2 \n\
<x , y>\
"""
assert upretty(I) == ucode_str
assert pretty(I) == ascii_str
Q = F / M
ucode_str = \
"""\
2 \n\
ℚ[x, y] \n\
─────────────────\n\
╱ ⎡ 2⎤╲\n\
╲[x, y], ⎣1, x ⎦╱\
"""
ascii_str = \
"""\
2 \n\
QQ[x, y] \n\
-----------------\n\
2 \n\
<[x, y], [1, x ]>\
"""
assert upretty(Q) == ucode_str
assert pretty(Q) == ascii_str
ucode_str = \
"""\
╱⎡ 3⎤ ╲\n\
│⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\
│⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\
╲⎣ 2 ⎦ ╱\
"""
ascii_str = \
"""\
3 \n\
x 2 2 \n\
<[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\
2 \
"""
def test_QuotientRing():
R = QQ.old_poly_ring(x)/[x**2 + 1]
ucode_str = \
"""\
ℚ[x] \n\
────────\n\
╱ 2 ╲\n\
╲x + 1╱\
"""
ascii_str = \
"""\
QQ[x] \n\
--------\n\
2 \n\
<x + 1>\
"""
assert upretty(R) == ucode_str
assert pretty(R) == ascii_str
ucode_str = \
"""\
╱ 2 ╲\n\
1 + ╲x + 1╱\
"""
ascii_str = \
"""\
2 \n\
1 + <x + 1>\
"""
assert upretty(R.one) == ucode_str
assert pretty(R.one) == ascii_str
def test_Homomorphism():
from sympy.polys.agca import homomorphism
R = QQ.old_poly_ring(x)
expr = homomorphism(R.free_module(1), R.free_module(1), [0])
ucode_str = \
"""\
1 1\n\
[0] : ℚ[x] ──> ℚ[x] \
"""
ascii_str = \
"""\
1 1\n\
[0] : QQ[x] --> QQ[x] \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0])
ucode_str = \
"""\
⎡0 0⎤ 2 2\n\
⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\
⎣0 0⎦ \
"""
ascii_str = \
"""\
[0 0] 2 2\n\
[ ] : QQ[x] --> QQ[x] \n\
[0 0] \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])
ucode_str = \
"""\
1\n\
1 ℚ[x] \n\
[0] : ℚ[x] ──> ─────\n\
<[x]>\
"""
ascii_str = \
"""\
1\n\
1 QQ[x] \n\
[0] : QQ[x] --> ------\n\
<[x]> \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
def test_Tr():
A, B = symbols('A B', commutative=False)
t = Tr(A*B)
assert pretty(t) == r'Tr(A*B)'
assert upretty(t) == 'Tr(A⋅B)'
def test_pretty_Add():
eq = Mul(-2, x - 2, evaluate=False) + 5
assert pretty(eq) == '5 - 2*(x - 2)'
def test_issue_7179():
assert upretty(Not(Equivalent(x, y))) == 'x ⇎ y'
assert upretty(Not(Implies(x, y))) == 'x ↛ y'
def test_issue_7180():
assert upretty(Equivalent(x, y)) == 'x ⇔ y'
def test_pretty_Complement():
assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals'
assert upretty(S.Reals - S.Naturals) == 'ℝ \\ ℕ'
assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0'
assert upretty(S.Reals - S.Naturals0) == 'ℝ \\ ℕ₀'
def test_pretty_SymmetricDifference():
from sympy import SymmetricDifference, Interval
from sympy.testing.pytest import raises
assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \
evaluate = False)) == '[2, 3] ∆ [3, 5]'
with raises(NotImplementedError):
pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False))
def test_pretty_Contains():
assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)'
assert upretty(Contains(x, S.Integers)) == 'x ∈ ℤ'
def test_issue_8292():
from sympy.core import sympify
e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False)
ucode_str = \
"""\
4 4 \n\
2⋅(x - 1) x + x\n\
- ────────── + ──────\n\
4 x - 1 \n\
(x - 1) \
"""
ascii_str = \
"""\
4 4 \n\
2*(x - 1) x + x\n\
- ---------- + ------\n\
4 x - 1 \n\
(x - 1) \
"""
assert pretty(e) == ascii_str
assert upretty(e) == ucode_str
def test_issue_4335():
y = Function('y')
expr = -y(x).diff(x)
ucode_str = \
"""\
d \n\
-──(y(x))\n\
dx \
"""
ascii_str = \
"""\
d \n\
- --(y(x))\n\
dx \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_8344():
from sympy.core import sympify
e = sympify('2*x*y**2/1**2 + 1', evaluate=False)
ucode_str = \
"""\
2 \n\
2⋅x⋅y \n\
────── + 1\n\
2 \n\
1 \
"""
assert upretty(e) == ucode_str
def test_issue_6324():
x = Pow(2, 3, evaluate=False)
y = Pow(10, -2, evaluate=False)
e = Mul(x, y, evaluate=False)
ucode_str = \
"""\
3\n\
2 \n\
───\n\
2\n\
10 \
"""
assert upretty(e) == ucode_str
def test_issue_7927():
e = sin(x/2)**cos(x/2)
ucode_str = \
"""\
⎛x⎞\n\
cos⎜─⎟\n\
⎝2⎠\n\
⎛ ⎛x⎞⎞ \n\
⎜sin⎜─⎟⎟ \n\
⎝ ⎝2⎠⎠ \
"""
assert upretty(e) == ucode_str
e = sin(x)**(S(11)/13)
ucode_str = \
"""\
11\n\
──\n\
13\n\
(sin(x)) \
"""
assert upretty(e) == ucode_str
def test_issue_6134():
from sympy.abc import lamda, t
phi = Function('phi')
e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1))
ucode_str = \
"""\
1 1 \n\
2 ⌠ ⌠ \n\
λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\
⌡ ⌡ \n\
0 0 \
"""
assert upretty(e) == ucode_str
def test_issue_9877():
ucode_str1 = '(2, 3) ∪ ([1, 2] \\ {x})'
a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x)
assert upretty(Union(a, Complement(b, c))) == ucode_str1
ucode_str2 = '{x} ∩ {y} ∩ ({z} \\ [1, 2])'
d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2)
assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2
def test_issue_13651():
expr1 = c + Mul(-1, a + b, evaluate=False)
assert pretty(expr1) == 'c - (a + b)'
expr2 = c + Mul(-1, a - b + d, evaluate=False)
assert pretty(expr2) == 'c - (a - b + d)'
def test_pretty_primenu():
from sympy.ntheory.factor_ import primenu
ascii_str1 = "nu(n)"
ucode_str1 = "ν(n)"
n = symbols('n', integer=True)
assert pretty(primenu(n)) == ascii_str1
assert upretty(primenu(n)) == ucode_str1
def test_pretty_primeomega():
from sympy.ntheory.factor_ import primeomega
ascii_str1 = "Omega(n)"
ucode_str1 = "Ω(n)"
n = symbols('n', integer=True)
assert pretty(primeomega(n)) == ascii_str1
assert upretty(primeomega(n)) == ucode_str1
def test_pretty_Mod():
from sympy.core import Mod
ascii_str1 = "x mod 7"
ucode_str1 = "x mod 7"
ascii_str2 = "(x + 1) mod 7"
ucode_str2 = "(x + 1) mod 7"
ascii_str3 = "2*x mod 7"
ucode_str3 = "2⋅x mod 7"
ascii_str4 = "(x mod 7) + 1"
ucode_str4 = "(x mod 7) + 1"
ascii_str5 = "2*(x mod 7)"
ucode_str5 = "2⋅(x mod 7)"
x = symbols('x', integer=True)
assert pretty(Mod(x, 7)) == ascii_str1
assert upretty(Mod(x, 7)) == ucode_str1
assert pretty(Mod(x + 1, 7)) == ascii_str2
assert upretty(Mod(x + 1, 7)) == ucode_str2
assert pretty(Mod(2 * x, 7)) == ascii_str3
assert upretty(Mod(2 * x, 7)) == ucode_str3
assert pretty(Mod(x, 7) + 1) == ascii_str4
assert upretty(Mod(x, 7) + 1) == ucode_str4
assert pretty(2 * Mod(x, 7)) == ascii_str5
assert upretty(2 * Mod(x, 7)) == ucode_str5
def test_issue_11801():
assert pretty(Symbol("")) == ""
assert upretty(Symbol("")) == ""
def test_pretty_UnevaluatedExpr():
x = symbols('x')
he = UnevaluatedExpr(1/x)
ucode_str = \
"""\
1\n\
─\n\
x\
"""
assert upretty(he) == ucode_str
ucode_str = \
"""\
2\n\
⎛1⎞ \n\
⎜─⎟ \n\
⎝x⎠ \
"""
assert upretty(he**2) == ucode_str
ucode_str = \
"""\
1\n\
1 + ─\n\
x\
"""
assert upretty(he + 1) == ucode_str
ucode_str = \
('''\
1\n\
x⋅─\n\
x\
''')
assert upretty(x*he) == ucode_str
def test_issue_10472():
M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0]))
ucode_str = \
"""\
⎛⎡0 0⎤ ⎡0⎤⎞
⎜⎢ ⎥, ⎢ ⎥⎟
⎝⎣0 0⎦ ⎣0⎦⎠\
"""
assert upretty(M) == ucode_str
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
ascii_str1 = "A_00"
ucode_str1 = "A₀₀"
assert pretty(A[0, 0]) == ascii_str1
assert upretty(A[0, 0]) == ucode_str1
ascii_str1 = "3*A_00"
ucode_str1 = "3⋅A₀₀"
assert pretty(3*A[0, 0]) == ascii_str1
assert upretty(3*A[0, 0]) == ucode_str1
ascii_str1 = "(-B + A)[0, 0]"
ucode_str1 = "(-B + A)[0, 0]"
F = C[0, 0].subs(C, A - B)
assert pretty(F) == ascii_str1
assert upretty(F) == ucode_str1
def test_issue_12675():
from sympy.vector import CoordSys3D
x, y, t, j = symbols('x y t j')
e = CoordSys3D('e')
ucode_str = \
"""\
⎛ t⎞ \n\
⎜⎛x⎞ ⎟ j_e\n\
⎜⎜─⎟ ⎟ \n\
⎝⎝y⎠ ⎠ \
"""
assert upretty((x/y)**t*e.j) == ucode_str
ucode_str = \
"""\
⎛1⎞ \n\
⎜─⎟ j_e\n\
⎝y⎠ \
"""
assert upretty((1/y)*e.j) == ucode_str
def test_MatrixSymbol_printing():
# test cases for issue #14237
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert pretty(-A*B*C) == "-A*B*C"
assert pretty(A - B) == "-B + A"
assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C"
# issue #14814
x = MatrixSymbol('x', n, n)
y = MatrixSymbol('y*', n, n)
assert pretty(x + y) == "x + y*"
ascii_str = \
"""\
2 \n\
-2*y* -a*x\
"""
assert pretty(-a*x + -2*y*y) == ascii_str
def test_degree_printing():
expr1 = 90*degree
assert pretty(expr1) == '90°'
expr2 = x*degree
assert pretty(expr2) == 'x°'
expr3 = cos(x*degree + 90*degree)
assert pretty(expr3) == 'cos(x° + 90°)'
def test_vector_expr_pretty_printing():
A = CoordSys3D('A')
assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)×((x_A) i_A + (3⋅y_A) j_A)"
assert upretty(x*Cross(A.i, A.j)) == 'x⋅(i_A)×(j_A)'
assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == "∇×((x_A) i_A + (3⋅y_A) j_A)"
assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == "∇⋅((x_A) i_A + (3⋅y_A) j_A)"
assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)"
assert upretty(Gradient(A.x+3*A.y)) == "∇(x_A + 3⋅y_A)"
assert upretty(Laplacian(A.x+3*A.y)) == "∆(x_A + 3⋅y_A)"
# TODO: add support for ASCII pretty.
def test_pretty_print_tensor_expr():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
i0 = tensor_indices("i_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
expr = -i
ascii_str = \
"""\
-i\
"""
ucode_str = \
"""\
-i\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)
ascii_str = \
"""\
i\n\
A \n\
\
"""
ucode_str = \
"""\
i\n\
A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i0)
ascii_str = \
"""\
i_0\n\
A \n\
\
"""
ucode_str = \
"""\
i₀\n\
A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(-i)
ascii_str = \
"""\
\n\
A \n\
i\
"""
ucode_str = \
"""\
\n\
A \n\
i\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -3*A(-i)
ascii_str = \
"""\
\n\
-3*A \n\
i\
"""
ucode_str = \
"""\
\n\
-3⋅A \n\
i\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -j)
ascii_str = \
"""\
i \n\
H \n\
j\
"""
ucode_str = \
"""\
i \n\
H \n\
j\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -i)
ascii_str = \
"""\
L_0 \n\
H \n\
L_0\
"""
ucode_str = \
"""\
L₀ \n\
H \n\
L₀\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -j)*A(j)*B(k)
ascii_str = \
"""\
i L_0 k\n\
H *A *B \n\
L_0 \
"""
ucode_str = \
"""\
i L₀ k\n\
H ⋅A ⋅B \n\
L₀ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (1+x)*A(i)
ascii_str = \
"""\
i\n\
(x + 1)*A \n\
\
"""
ucode_str = \
"""\
i\n\
(x + 1)⋅A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i) + 3*B(i)
ascii_str = \
"""\
i i\n\
3*B + A \n\
\
"""
ucode_str = \
"""\
i i\n\
3⋅B + A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_print_tensor_partial_deriv():
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
expr = PartialDerivative(A(i), A(j))
ascii_str = \
"""\
d / i\\\n\
---|A |\n\
j\\ /\n\
dA \n\
\
"""
ucode_str = \
"""\
∂ ⎛ i⎞\n\
───⎜A ⎟\n\
j⎝ ⎠\n\
∂A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)*PartialDerivative(H(k, -i), A(j))
ascii_str = \
"""\
L_0 d / k \\\n\
A *---|H |\n\
j\\ L_0/\n\
dA \n\
\
"""
ucode_str = \
"""\
L₀ ∂ ⎛ k ⎞\n\
A ⋅───⎜H ⎟\n\
j⎝ L₀⎠\n\
∂A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
ascii_str = \
"""\
L_0 d / k k \\\n\
A *---|3*H + B *C |\n\
j\\ L_0 L_0/\n\
dA \n\
\
"""
ucode_str = \
"""\
L₀ ∂ ⎛ k k ⎞\n\
A ⋅───⎜3⋅H + B ⋅C ⎟\n\
j⎝ L₀ L₀⎠\n\
∂A \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (A(i) + B(i))*PartialDerivative(C(j), D(j))
ascii_str = \
"""\
/ i i\\ d / L_0\\\n\
|A + B |*-----|C |\n\
\\ / L_0\\ /\n\
dD \n\
\
"""
ucode_str = \
"""\
⎛ i i⎞ ∂ ⎛ L₀⎞\n\
⎜A + B ⎟⋅────⎜C ⎟\n\
⎝ ⎠ L₀⎝ ⎠\n\
∂D \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
ascii_str = \
"""\
/ L_0 L_0\\ d / \\\n\
|A + B |*---|C |\n\
\\ / j\\ L_0/\n\
dD \n\
\
"""
ucode_str = \
"""\
⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\
⎜A + B ⎟⋅───⎜C ⎟\n\
⎝ ⎠ j⎝ L₀⎠\n\
∂D \n\
\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n))
ucode_str = """\
2 \n\
∂ ⎛ ⎞\n\
───────⎜A + B ⎟\n\
⎝ i i⎠\n\
∂A ∂A \n\
n j \
"""
assert upretty(expr) == ucode_str
expr = PartialDerivative(3*A(-i), A(-j), A(-n))
ucode_str = """\
2 \n\
∂ ⎛ ⎞\n\
───────⎜3⋅A ⎟\n\
⎝ i⎠\n\
∂A ∂A \n\
n j \
"""
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {i:1})
ascii_str = \
"""\
i=1,j\n\
H \n\
\
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {i: 1, j: 1})
ascii_str = \
"""\
i=1,j=1\n\
H \n\
\
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {j: 1})
ascii_str = \
"""\
i,j=1\n\
H \n\
\
"""
ucode_str = ascii_str
expr = TensorElement(H(-i, j), {-i: 1})
ascii_str = \
"""\
j\n\
H \n\
i=1 \
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_15560():
a = MatrixSymbol('a', 1, 1)
e = pretty(a*(KroneckerProduct(a, a)))
result = 'a*(a x a)'
assert e == result
def test_print_lerchphi():
# Part of issue 6013
a = Symbol('a')
pretty(lerchphi(a, 1, 2))
uresult = 'Φ(a, 1, 2)'
aresult = 'lerchphi(a, 1, 2)'
assert pretty(lerchphi(a, 1, 2)) == aresult
assert upretty(lerchphi(a, 1, 2)) == uresult
def test_issue_15583():
N = mechanics.ReferenceFrame('N')
result = '(n_x, n_y, n_z)'
e = pretty((N.x, N.y, N.z))
assert e == result
def test_matrixSymbolBold():
# Issue 15871
def boldpretty(expr):
return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold")
from sympy import trace
A = MatrixSymbol("A", 2, 2)
assert boldpretty(trace(A)) == 'tr(𝐀)'
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert boldpretty(-A) == '-𝐀'
assert boldpretty(A - A*B - B) == '-𝐁 -𝐀⋅𝐁 + 𝐀'
assert boldpretty(-A*B - A*B*C - B) == '-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂'
A = MatrixSymbol("Addot", 3, 3)
assert boldpretty(A) == '𝐀̈'
omega = MatrixSymbol("omega", 3, 3)
assert boldpretty(omega) == 'ω'
omega = MatrixSymbol("omeganorm", 3, 3)
assert boldpretty(omega) == '‖ω‖'
a = Symbol('alpha')
b = Symbol('b')
c = MatrixSymbol("c", 3, 1)
d = MatrixSymbol("d", 3, 1)
assert boldpretty(a*B*c+b*d) == 'b⋅𝐝 + α⋅𝐁⋅𝐜'
d = MatrixSymbol("delta", 3, 1)
B = MatrixSymbol("Beta", 3, 3)
assert boldpretty(a*B*c+b*d) == 'b⋅δ + α⋅Β⋅𝐜'
A = MatrixSymbol("A_2", 3, 3)
assert boldpretty(A) == '𝐀₂'
def test_center_accent():
assert center_accent('a', '\N{COMBINING TILDE}') == 'ã'
assert center_accent('aa', '\N{COMBINING TILDE}') == 'aã'
assert center_accent('aaa', '\N{COMBINING TILDE}') == 'aãa'
assert center_accent('aaaa', '\N{COMBINING TILDE}') == 'aaãa'
assert center_accent('aaaaa', '\N{COMBINING TILDE}') == 'aaãaa'
assert center_accent('abcdefg', '\N{COMBINING FOUR DOTS ABOVE}') == 'abcd⃜efg'
def test_imaginary_unit():
from sympy import pretty # As it is redefined above
assert pretty(1 + I, use_unicode=False) == '1 + I'
assert pretty(1 + I, use_unicode=True) == '1 + ⅈ'
assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I'
assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == '1 + ⅉ'
raises(TypeError, lambda: pretty(I, imaginary_unit=I))
raises(ValueError, lambda: pretty(I, imaginary_unit="kkk"))
def test_str_special_matrices():
from sympy.matrices import Identity, ZeroMatrix, OneMatrix
assert pretty(Identity(4)) == 'I'
assert upretty(Identity(4)) == '𝕀'
assert pretty(ZeroMatrix(2, 2)) == '0'
assert upretty(ZeroMatrix(2, 2)) == '𝟘'
assert pretty(OneMatrix(2, 2)) == '1'
assert upretty(OneMatrix(2, 2)) == '𝟙'
def test_pretty_misc_functions():
assert pretty(LambertW(x)) == 'W(x)'
assert upretty(LambertW(x)) == 'W(x)'
assert pretty(LambertW(x, y)) == 'W(x, y)'
assert upretty(LambertW(x, y)) == 'W(x, y)'
assert pretty(airyai(x)) == 'Ai(x)'
assert upretty(airyai(x)) == 'Ai(x)'
assert pretty(airybi(x)) == 'Bi(x)'
assert upretty(airybi(x)) == 'Bi(x)'
assert pretty(airyaiprime(x)) == "Ai'(x)"
assert upretty(airyaiprime(x)) == "Ai'(x)"
assert pretty(airybiprime(x)) == "Bi'(x)"
assert upretty(airybiprime(x)) == "Bi'(x)"
assert pretty(fresnelc(x)) == 'C(x)'
assert upretty(fresnelc(x)) == 'C(x)'
assert pretty(fresnels(x)) == 'S(x)'
assert upretty(fresnels(x)) == 'S(x)'
assert pretty(Heaviside(x)) == 'Heaviside(x)'
assert upretty(Heaviside(x)) == 'θ(x)'
assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)'
assert upretty(Heaviside(x, y)) == 'θ(x, y)'
assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)'
assert upretty(dirichlet_eta(x)) == 'η(x)'
def test_hadamard_power():
m, n, p = symbols('m, n, p', integer=True)
A = MatrixSymbol('A', m, n)
B = MatrixSymbol('B', m, n)
# Testing printer:
expr = hadamard_power(A, n)
ascii_str = \
"""\
.n\n\
A \
"""
ucode_str = \
"""\
∘n\n\
A \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hadamard_power(A, 1+n)
ascii_str = \
"""\
.(n + 1)\n\
A \
"""
ucode_str = \
"""\
∘(n + 1)\n\
A \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hadamard_power(A*B.T, 1+n)
ascii_str = \
"""\
.(n + 1)\n\
/ T\\ \n\
\\A*B / \
"""
ucode_str = \
"""\
∘(n + 1)\n\
⎛ T⎞ \n\
⎝A⋅B ⎠ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_17258():
n = Symbol('n', integer=True)
assert pretty(Sum(n, (n, -oo, 1))) == \
' 1 \n'\
' __ \n'\
' \\ ` \n'\
' ) n\n'\
' /_, \n'\
'n = -oo '
assert upretty(Sum(n, (n, -oo, 1))) == \
"""\
1 \n\
___ \n\
╲ \n\
╲ \n\
╱ n\n\
╱ \n\
‾‾‾ \n\
n = -∞ \
"""
def test_is_combining():
line = "v̇_m"
assert [is_combining(sym) for sym in line] == \
[False, True, False, False]
def test_issue_17857():
assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}'
assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}'
def test_issue_18272():
x = Symbol('x')
n = Symbol('n')
assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \
'⎧ ⎛ x ⎞⎫\n'\
'⎨x | x ∊ ℂ ∧ ⎝-x + ℯ = 0⎠⎬\n'\
'⎩ ⎭'
assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \
'⎧ ⎧-n n⎫ ⎛n ⎞⎫\n'\
'⎨x | x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\
'⎩ ⎩ 2 2⎭ ⎝2 ⎠⎭'
assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1),
(x/2, True)) - 1/2, 0), Interval(0, 3))) == \
'⎧ ⎛⎛⎧ 1 for x ≥ 3⎞ ⎞⎫\n'\
'⎪ ⎜⎜⎪ ⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪x ⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪─ - 0.5 for x ≥ 2⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪2 ⎟ ⎟⎪\n'\
'⎨x | x ∊ [0, 3] ∧ ⎜⎜⎨ ⎟ - 0.5 = 0⎟⎬\n'\
'⎪ ⎜⎜⎪ 0.5 for x ≥ 1⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪ ⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪ x ⎟ ⎟⎪\n'\
'⎪ ⎜⎜⎪ ─ otherwise⎟ ⎟⎪\n'\
'⎩ ⎝⎝⎩ 2 ⎠ ⎠⎭'
def test_Str():
from sympy.core.symbol import Str
assert pretty(Str('x')) == 'x'
def test_diffgeom():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
x,y = symbols('x y', real=True)
m = Manifold('M', 2)
assert pretty(m) == 'M'
p = Patch('P', m)
assert pretty(p) == "P"
rect = CoordSystem('rect', p, [x, y])
assert pretty(rect) == "rect"
b = BaseScalarField(rect, 0)
assert pretty(b) == "x"
|
171fc02e36f76d377f02e8c92e430dde037894e37a52844e4afb7db1e0e787e3 | """Test whether all elements of cls.args are instances of Basic. """
# NOTE: keep tests sorted by (module, class name) key. If a class can't
# be instantiated, add it here anyway with @SKIP("abstract class) (see
# e.g. Function).
import os
import re
from sympy import (Basic, S, symbols, sqrt, sin, oo, Interval, exp, Lambda, pi,
Eq, log, Function, Rational)
from sympy.testing.pytest import XFAIL, SKIP
a, b, c, x, y, z = symbols('a,b,c,x,y,z')
def test_all_classes_are_tested():
this = os.path.split(__file__)[0]
path = os.path.join(this, os.pardir, os.pardir)
sympy_path = os.path.abspath(path)
prefix = os.path.split(sympy_path)[0] + os.sep
re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
modules = {}
for root, dirs, files in os.walk(sympy_path):
module = root.replace(prefix, "").replace(os.sep, ".")
for file in files:
if file.startswith(("_", "test_", "bench_")):
continue
if not file.endswith(".py"):
continue
with open(os.path.join(root, file), encoding='utf-8') as f:
text = f.read()
submodule = module + '.' + file[:-3]
names = re_cls.findall(text)
if not names:
continue
try:
mod = __import__(submodule, fromlist=names)
except ImportError:
continue
def is_Basic(name):
cls = getattr(mod, name)
if hasattr(cls, '_sympy_deprecated_func'):
cls = cls._sympy_deprecated_func
return issubclass(cls, Basic)
names = list(filter(is_Basic, names))
if names:
modules[submodule] = names
ns = globals()
failed = []
for module, names in modules.items():
mod = module.replace('.', '__')
for name in names:
test = 'test_' + mod + '__' + name
if test not in ns:
failed.append(module + '.' + name)
assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)
def _test_args(obj):
all_basic = all(isinstance(arg, Basic) for arg in obj.args)
# Ideally obj.func(*obj.args) would always recreate the object, but for
# now, we only require it for objects with non-empty .args
recreatable = not obj.args or obj.func(*obj.args) == obj
return all_basic and recreatable
def test_sympy__assumptions__assume__AppliedPredicate():
from sympy.assumptions.assume import AppliedPredicate, Predicate
from sympy import Q
assert _test_args(AppliedPredicate(Predicate("test"), 2))
assert _test_args(Q.is_true(True))
def test_sympy__assumptions__assume__Predicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
def test_sympy__assumptions__sathandlers__UnevaluatedOnFree():
from sympy.assumptions.sathandlers import UnevaluatedOnFree
from sympy import Q
assert _test_args(UnevaluatedOnFree(Q.positive))
def test_sympy__assumptions__sathandlers__AllArgs():
from sympy.assumptions.sathandlers import AllArgs
from sympy import Q
assert _test_args(AllArgs(Q.positive))
def test_sympy__assumptions__sathandlers__AnyArgs():
from sympy.assumptions.sathandlers import AnyArgs
from sympy import Q
assert _test_args(AnyArgs(Q.positive))
def test_sympy__assumptions__sathandlers__ExactlyOneArg():
from sympy.assumptions.sathandlers import ExactlyOneArg
from sympy import Q
assert _test_args(ExactlyOneArg(Q.positive))
def test_sympy__assumptions__sathandlers__CheckOldAssump():
from sympy.assumptions.sathandlers import CheckOldAssump
from sympy import Q
assert _test_args(CheckOldAssump(Q.positive))
def test_sympy__assumptions__sathandlers__CheckIsPrime():
from sympy.assumptions.sathandlers import CheckIsPrime
from sympy import Q
# Input must be a number
assert _test_args(CheckIsPrime(Q.positive))
@SKIP("abstract Class")
def test_sympy__codegen__ast__AssignmentBase():
from sympy.codegen.ast import AssignmentBase
assert _test_args(AssignmentBase(x, 1))
@SKIP("abstract Class")
def test_sympy__codegen__ast__AugmentedAssignment():
from sympy.codegen.ast import AugmentedAssignment
assert _test_args(AugmentedAssignment(x, 1))
def test_sympy__codegen__ast__AddAugmentedAssignment():
from sympy.codegen.ast import AddAugmentedAssignment
assert _test_args(AddAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__SubAugmentedAssignment():
from sympy.codegen.ast import SubAugmentedAssignment
assert _test_args(SubAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__MulAugmentedAssignment():
from sympy.codegen.ast import MulAugmentedAssignment
assert _test_args(MulAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__DivAugmentedAssignment():
from sympy.codegen.ast import DivAugmentedAssignment
assert _test_args(DivAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__ModAugmentedAssignment():
from sympy.codegen.ast import ModAugmentedAssignment
assert _test_args(ModAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__CodeBlock():
from sympy.codegen.ast import CodeBlock, Assignment
assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2)))
def test_sympy__codegen__ast__For():
from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment
from sympy import Range
assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1))))
def test_sympy__codegen__ast__Token():
from sympy.codegen.ast import Token
assert _test_args(Token())
def test_sympy__codegen__ast__ContinueToken():
from sympy.codegen.ast import ContinueToken
assert _test_args(ContinueToken())
def test_sympy__codegen__ast__BreakToken():
from sympy.codegen.ast import BreakToken
assert _test_args(BreakToken())
def test_sympy__codegen__ast__NoneToken():
from sympy.codegen.ast import NoneToken
assert _test_args(NoneToken())
def test_sympy__codegen__ast__String():
from sympy.codegen.ast import String
assert _test_args(String('foobar'))
def test_sympy__codegen__ast__QuotedString():
from sympy.codegen.ast import QuotedString
assert _test_args(QuotedString('foobar'))
def test_sympy__codegen__ast__Comment():
from sympy.codegen.ast import Comment
assert _test_args(Comment('this is a comment'))
def test_sympy__codegen__ast__Node():
from sympy.codegen.ast import Node
assert _test_args(Node())
assert _test_args(Node(attrs={1, 2, 3}))
def test_sympy__codegen__ast__Type():
from sympy.codegen.ast import Type
assert _test_args(Type('float128'))
def test_sympy__codegen__ast__IntBaseType():
from sympy.codegen.ast import IntBaseType
assert _test_args(IntBaseType('bigint'))
def test_sympy__codegen__ast___SizedIntType():
from sympy.codegen.ast import _SizedIntType
assert _test_args(_SizedIntType('int128', 128))
def test_sympy__codegen__ast__SignedIntType():
from sympy.codegen.ast import SignedIntType
assert _test_args(SignedIntType('int128_with_sign', 128))
def test_sympy__codegen__ast__UnsignedIntType():
from sympy.codegen.ast import UnsignedIntType
assert _test_args(UnsignedIntType('unt128', 128))
def test_sympy__codegen__ast__FloatBaseType():
from sympy.codegen.ast import FloatBaseType
assert _test_args(FloatBaseType('positive_real'))
def test_sympy__codegen__ast__FloatType():
from sympy.codegen.ast import FloatType
assert _test_args(FloatType('float242', 242, nmant=142, nexp=99))
def test_sympy__codegen__ast__ComplexBaseType():
from sympy.codegen.ast import ComplexBaseType
assert _test_args(ComplexBaseType('positive_cmplx'))
def test_sympy__codegen__ast__ComplexType():
from sympy.codegen.ast import ComplexType
assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5))
def test_sympy__codegen__ast__Attribute():
from sympy.codegen.ast import Attribute
assert _test_args(Attribute('noexcept'))
def test_sympy__codegen__ast__Variable():
from sympy.codegen.ast import Variable, Type, value_const
assert _test_args(Variable(x))
assert _test_args(Variable(y, Type('float32'), {value_const}))
assert _test_args(Variable(z, type=Type('float64')))
def test_sympy__codegen__ast__Pointer():
from sympy.codegen.ast import Pointer, Type, pointer_const
assert _test_args(Pointer(x))
assert _test_args(Pointer(y, type=Type('float32')))
assert _test_args(Pointer(z, Type('float64'), {pointer_const}))
def test_sympy__codegen__ast__Declaration():
from sympy.codegen.ast import Declaration, Variable, Type
vx = Variable(x, type=Type('float'))
assert _test_args(Declaration(vx))
def test_sympy__codegen__ast__While():
from sympy.codegen.ast import While, AddAugmentedAssignment
assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Scope():
from sympy.codegen.ast import Scope, AddAugmentedAssignment
assert _test_args(Scope([AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Stream():
from sympy.codegen.ast import Stream
assert _test_args(Stream('stdin'))
def test_sympy__codegen__ast__Print():
from sympy.codegen.ast import Print
assert _test_args(Print([x, y]))
assert _test_args(Print([x, y], "%d %d"))
def test_sympy__codegen__ast__FunctionPrototype():
from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionPrototype(real, 'pwer', [inp_x]))
def test_sympy__codegen__ast__FunctionDefinition():
from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)]))
def test_sympy__codegen__ast__Return():
from sympy.codegen.ast import Return
assert _test_args(Return(x))
def test_sympy__codegen__ast__FunctionCall():
from sympy.codegen.ast import FunctionCall
assert _test_args(FunctionCall('pwer', [x]))
def test_sympy__codegen__ast__Element():
from sympy.codegen.ast import Element
assert _test_args(Element('x', range(3)))
def test_sympy__codegen__cnodes__CommaOperator():
from sympy.codegen.cnodes import CommaOperator
assert _test_args(CommaOperator(1, 2))
def test_sympy__codegen__cnodes__goto():
from sympy.codegen.cnodes import goto
assert _test_args(goto('early_exit'))
def test_sympy__codegen__cnodes__Label():
from sympy.codegen.cnodes import Label
assert _test_args(Label('early_exit'))
def test_sympy__codegen__cnodes__PreDecrement():
from sympy.codegen.cnodes import PreDecrement
assert _test_args(PreDecrement(x))
def test_sympy__codegen__cnodes__PostDecrement():
from sympy.codegen.cnodes import PostDecrement
assert _test_args(PostDecrement(x))
def test_sympy__codegen__cnodes__PreIncrement():
from sympy.codegen.cnodes import PreIncrement
assert _test_args(PreIncrement(x))
def test_sympy__codegen__cnodes__PostIncrement():
from sympy.codegen.cnodes import PostIncrement
assert _test_args(PostIncrement(x))
def test_sympy__codegen__cnodes__struct():
from sympy.codegen.ast import real, Variable
from sympy.codegen.cnodes import struct
assert _test_args(struct(declarations=[
Variable(x, type=real),
Variable(y, type=real)
]))
def test_sympy__codegen__cnodes__union():
from sympy.codegen.ast import float32, int32, Variable
from sympy.codegen.cnodes import union
assert _test_args(union(declarations=[
Variable(x, type=float32),
Variable(y, type=int32)
]))
def test_sympy__codegen__cxxnodes__using():
from sympy.codegen.cxxnodes import using
assert _test_args(using('std::vector'))
assert _test_args(using('std::vector', 'vec'))
def test_sympy__codegen__fnodes__Program():
from sympy.codegen.fnodes import Program
assert _test_args(Program('foobar', []))
def test_sympy__codegen__fnodes__Module():
from sympy.codegen.fnodes import Module
assert _test_args(Module('foobar', [], []))
def test_sympy__codegen__fnodes__Subroutine():
from sympy.codegen.fnodes import Subroutine
x = symbols('x', real=True)
assert _test_args(Subroutine('foo', [x], []))
def test_sympy__codegen__fnodes__GoTo():
from sympy.codegen.fnodes import GoTo
assert _test_args(GoTo([10]))
assert _test_args(GoTo([10, 20], x > 1))
def test_sympy__codegen__fnodes__FortranReturn():
from sympy.codegen.fnodes import FortranReturn
assert _test_args(FortranReturn(10))
def test_sympy__codegen__fnodes__Extent():
from sympy.codegen.fnodes import Extent
assert _test_args(Extent())
assert _test_args(Extent(None))
assert _test_args(Extent(':'))
assert _test_args(Extent(-3, 4))
assert _test_args(Extent(x, y))
def test_sympy__codegen__fnodes__use_rename():
from sympy.codegen.fnodes import use_rename
assert _test_args(use_rename('loc', 'glob'))
def test_sympy__codegen__fnodes__use():
from sympy.codegen.fnodes import use
assert _test_args(use('modfoo', only='bar'))
def test_sympy__codegen__fnodes__SubroutineCall():
from sympy.codegen.fnodes import SubroutineCall
assert _test_args(SubroutineCall('foo', ['bar', 'baz']))
def test_sympy__codegen__fnodes__Do():
from sympy.codegen.fnodes import Do
assert _test_args(Do([], 'i', 1, 42))
def test_sympy__codegen__fnodes__ImpliedDoLoop():
from sympy.codegen.fnodes import ImpliedDoLoop
assert _test_args(ImpliedDoLoop('i', 'i', 1, 42))
def test_sympy__codegen__fnodes__ArrayConstructor():
from sympy.codegen.fnodes import ArrayConstructor
assert _test_args(ArrayConstructor([1, 2, 3]))
from sympy.codegen.fnodes import ImpliedDoLoop
idl = ImpliedDoLoop('i', 'i', 1, 42)
assert _test_args(ArrayConstructor([1, idl, 3]))
def test_sympy__codegen__fnodes__sum_():
from sympy.codegen.fnodes import sum_
assert _test_args(sum_('arr'))
def test_sympy__codegen__fnodes__product_():
from sympy.codegen.fnodes import product_
assert _test_args(product_('arr'))
def test_sympy__codegen__numpy_nodes__logaddexp():
from sympy.codegen.numpy_nodes import logaddexp
assert _test_args(logaddexp(x, y))
def test_sympy__codegen__numpy_nodes__logaddexp2():
from sympy.codegen.numpy_nodes import logaddexp2
assert _test_args(logaddexp2(x, y))
def test_sympy__codegen__scipy_nodes__cosm1():
from sympy.codegen.scipy_nodes import cosm1
assert _test_args(cosm1(x))
@XFAIL
def test_sympy__combinatorics__graycode__GrayCode():
from sympy.combinatorics.graycode import GrayCode
# an integer is given and returned from GrayCode as the arg
assert _test_args(GrayCode(3, start='100'))
assert _test_args(GrayCode(3, rank=1))
def test_sympy__combinatorics__subsets__Subset():
from sympy.combinatorics.subsets import Subset
assert _test_args(Subset([0, 1], [0, 1, 2, 3]))
assert _test_args(Subset(['c', 'd'], ['a', 'b', 'c', 'd']))
def test_sympy__combinatorics__permutations__Permutation():
from sympy.combinatorics.permutations import Permutation
assert _test_args(Permutation([0, 1, 2, 3]))
def test_sympy__combinatorics__permutations__AppliedPermutation():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.permutations import AppliedPermutation
p = Permutation([0, 1, 2, 3])
assert _test_args(AppliedPermutation(p, 1))
def test_sympy__combinatorics__perm_groups__PermutationGroup():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
assert _test_args(PermutationGroup([Permutation([0, 1])]))
def test_sympy__combinatorics__polyhedron__Polyhedron():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.polyhedron import Polyhedron
from sympy.abc import w, x, y, z
pgroup = [Permutation([[0, 1, 2], [3]]),
Permutation([[0, 1, 3], [2]]),
Permutation([[0, 2, 3], [1]]),
Permutation([[1, 2, 3], [0]]),
Permutation([[0, 1], [2, 3]]),
Permutation([[0, 2], [1, 3]]),
Permutation([[0, 3], [1, 2]]),
Permutation([[0, 1, 2, 3]])]
corners = [w, x, y, z]
faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)]
assert _test_args(Polyhedron(corners, faces, pgroup))
@XFAIL
def test_sympy__combinatorics__prufer__Prufer():
from sympy.combinatorics.prufer import Prufer
assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))
def test_sympy__combinatorics__partitions__Partition():
from sympy.combinatorics.partitions import Partition
assert _test_args(Partition([1]))
@XFAIL
def test_sympy__combinatorics__partitions__IntegerPartition():
from sympy.combinatorics.partitions import IntegerPartition
assert _test_args(IntegerPartition([1]))
def test_sympy__concrete__products__Product():
from sympy.concrete.products import Product
assert _test_args(Product(x, (x, 0, 10)))
assert _test_args(Product(x, (x, 0, y), (y, 0, 10)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__ExprWithLimits():
from sympy.concrete.expr_with_limits import ExprWithLimits
assert _test_args(ExprWithLimits(x, (x, 0, 10)))
assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__AddWithLimits():
from sympy.concrete.expr_with_limits import AddWithLimits
assert _test_args(AddWithLimits(x, (x, 0, 10)))
assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits():
from sympy.concrete.expr_with_intlimits import ExprWithIntLimits
assert _test_args(ExprWithIntLimits(x, (x, 0, 10)))
assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3)))
def test_sympy__concrete__summations__Sum():
from sympy.concrete.summations import Sum
assert _test_args(Sum(x, (x, 0, 10)))
assert _test_args(Sum(x, (x, 0, y), (y, 0, 10)))
def test_sympy__core__add__Add():
from sympy.core.add import Add
assert _test_args(Add(x, y, z, 2))
def test_sympy__core__basic__Atom():
from sympy.core.basic import Atom
assert _test_args(Atom())
def test_sympy__core__basic__Basic():
from sympy.core.basic import Basic
assert _test_args(Basic())
def test_sympy__core__containers__Dict():
from sympy.core.containers import Dict
assert _test_args(Dict({x: y, y: z}))
def test_sympy__core__containers__Tuple():
from sympy.core.containers import Tuple
assert _test_args(Tuple(x, y, z, 2))
def test_sympy__core__expr__AtomicExpr():
from sympy.core.expr import AtomicExpr
assert _test_args(AtomicExpr())
def test_sympy__core__expr__Expr():
from sympy.core.expr import Expr
assert _test_args(Expr())
def test_sympy__core__expr__UnevaluatedExpr():
from sympy.core.expr import UnevaluatedExpr
from sympy.abc import x
assert _test_args(UnevaluatedExpr(x))
def test_sympy__core__function__Application():
from sympy.core.function import Application
assert _test_args(Application(1, 2, 3))
def test_sympy__core__function__AppliedUndef():
from sympy.core.function import AppliedUndef
assert _test_args(AppliedUndef(1, 2, 3))
def test_sympy__core__function__Derivative():
from sympy.core.function import Derivative
assert _test_args(Derivative(2, x, y, 3))
@SKIP("abstract class")
def test_sympy__core__function__Function():
pass
def test_sympy__core__function__Lambda():
assert _test_args(Lambda((x, y), x + y + z))
def test_sympy__core__function__Subs():
from sympy.core.function import Subs
assert _test_args(Subs(x + y, x, 2))
def test_sympy__core__function__WildFunction():
from sympy.core.function import WildFunction
assert _test_args(WildFunction('f'))
def test_sympy__core__mod__Mod():
from sympy.core.mod import Mod
assert _test_args(Mod(x, 2))
def test_sympy__core__mul__Mul():
from sympy.core.mul import Mul
assert _test_args(Mul(2, x, y, z))
def test_sympy__core__numbers__Catalan():
from sympy.core.numbers import Catalan
assert _test_args(Catalan())
def test_sympy__core__numbers__ComplexInfinity():
from sympy.core.numbers import ComplexInfinity
assert _test_args(ComplexInfinity())
def test_sympy__core__numbers__EulerGamma():
from sympy.core.numbers import EulerGamma
assert _test_args(EulerGamma())
def test_sympy__core__numbers__Exp1():
from sympy.core.numbers import Exp1
assert _test_args(Exp1())
def test_sympy__core__numbers__Float():
from sympy.core.numbers import Float
assert _test_args(Float(1.23))
def test_sympy__core__numbers__GoldenRatio():
from sympy.core.numbers import GoldenRatio
assert _test_args(GoldenRatio())
def test_sympy__core__numbers__TribonacciConstant():
from sympy.core.numbers import TribonacciConstant
assert _test_args(TribonacciConstant())
def test_sympy__core__numbers__Half():
from sympy.core.numbers import Half
assert _test_args(Half())
def test_sympy__core__numbers__ImaginaryUnit():
from sympy.core.numbers import ImaginaryUnit
assert _test_args(ImaginaryUnit())
def test_sympy__core__numbers__Infinity():
from sympy.core.numbers import Infinity
assert _test_args(Infinity())
def test_sympy__core__numbers__Integer():
from sympy.core.numbers import Integer
assert _test_args(Integer(7))
@SKIP("abstract class")
def test_sympy__core__numbers__IntegerConstant():
pass
def test_sympy__core__numbers__NaN():
from sympy.core.numbers import NaN
assert _test_args(NaN())
def test_sympy__core__numbers__NegativeInfinity():
from sympy.core.numbers import NegativeInfinity
assert _test_args(NegativeInfinity())
def test_sympy__core__numbers__NegativeOne():
from sympy.core.numbers import NegativeOne
assert _test_args(NegativeOne())
def test_sympy__core__numbers__Number():
from sympy.core.numbers import Number
assert _test_args(Number(1, 7))
def test_sympy__core__numbers__NumberSymbol():
from sympy.core.numbers import NumberSymbol
assert _test_args(NumberSymbol())
def test_sympy__core__numbers__One():
from sympy.core.numbers import One
assert _test_args(One())
def test_sympy__core__numbers__Pi():
from sympy.core.numbers import Pi
assert _test_args(Pi())
def test_sympy__core__numbers__Rational():
from sympy.core.numbers import Rational
assert _test_args(Rational(1, 7))
@SKIP("abstract class")
def test_sympy__core__numbers__RationalConstant():
pass
def test_sympy__core__numbers__Zero():
from sympy.core.numbers import Zero
assert _test_args(Zero())
@SKIP("abstract class")
def test_sympy__core__operations__AssocOp():
pass
@SKIP("abstract class")
def test_sympy__core__operations__LatticeOp():
pass
def test_sympy__core__power__Pow():
from sympy.core.power import Pow
assert _test_args(Pow(x, 2))
def test_sympy__algebras__quaternion__Quaternion():
from sympy.algebras.quaternion import Quaternion
assert _test_args(Quaternion(x, 1, 2, 3))
def test_sympy__core__relational__Equality():
from sympy.core.relational import Equality
assert _test_args(Equality(x, 2))
def test_sympy__core__relational__GreaterThan():
from sympy.core.relational import GreaterThan
assert _test_args(GreaterThan(x, 2))
def test_sympy__core__relational__LessThan():
from sympy.core.relational import LessThan
assert _test_args(LessThan(x, 2))
@SKIP("abstract class")
def test_sympy__core__relational__Relational():
pass
def test_sympy__core__relational__StrictGreaterThan():
from sympy.core.relational import StrictGreaterThan
assert _test_args(StrictGreaterThan(x, 2))
def test_sympy__core__relational__StrictLessThan():
from sympy.core.relational import StrictLessThan
assert _test_args(StrictLessThan(x, 2))
def test_sympy__core__relational__Unequality():
from sympy.core.relational import Unequality
assert _test_args(Unequality(x, 2))
def test_sympy__sandbox__indexed_integrals__IndexedIntegral():
from sympy.tensor import IndexedBase, Idx
from sympy.sandbox.indexed_integrals import IndexedIntegral
A = IndexedBase('A')
i, j = symbols('i j', integer=True)
a1, a2 = symbols('a1:3', cls=Idx)
assert _test_args(IndexedIntegral(A[a1], A[a2]))
assert _test_args(IndexedIntegral(A[i], A[j]))
def test_sympy__calculus__util__AccumulationBounds():
from sympy.calculus.util import AccumulationBounds
assert _test_args(AccumulationBounds(0, 1))
def test_sympy__sets__ordinals__OmegaPower():
from sympy.sets.ordinals import OmegaPower
assert _test_args(OmegaPower(1, 1))
def test_sympy__sets__ordinals__Ordinal():
from sympy.sets.ordinals import Ordinal, OmegaPower
assert _test_args(Ordinal(OmegaPower(2, 1)))
def test_sympy__sets__ordinals__OrdinalOmega():
from sympy.sets.ordinals import OrdinalOmega
assert _test_args(OrdinalOmega())
def test_sympy__sets__ordinals__OrdinalZero():
from sympy.sets.ordinals import OrdinalZero
assert _test_args(OrdinalZero())
def test_sympy__sets__powerset__PowerSet():
from sympy.sets.powerset import PowerSet
from sympy.core.singleton import S
assert _test_args(PowerSet(S.EmptySet))
def test_sympy__sets__sets__EmptySet():
from sympy.sets.sets import EmptySet
assert _test_args(EmptySet())
def test_sympy__sets__sets__UniversalSet():
from sympy.sets.sets import UniversalSet
assert _test_args(UniversalSet())
def test_sympy__sets__sets__FiniteSet():
from sympy.sets.sets import FiniteSet
assert _test_args(FiniteSet(x, y, z))
def test_sympy__sets__sets__Interval():
from sympy.sets.sets import Interval
assert _test_args(Interval(0, 1))
def test_sympy__sets__sets__ProductSet():
from sympy.sets.sets import ProductSet, Interval
assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1)))
@SKIP("does it make sense to test this?")
def test_sympy__sets__sets__Set():
from sympy.sets.sets import Set
assert _test_args(Set())
def test_sympy__sets__sets__Intersection():
from sympy.sets.sets import Intersection, Interval
from sympy.core.symbol import Symbol
x = Symbol('x')
y = Symbol('y')
S = Intersection(Interval(0, x), Interval(y, 1))
assert isinstance(S, Intersection)
assert _test_args(S)
def test_sympy__sets__sets__Union():
from sympy.sets.sets import Union, Interval
assert _test_args(Union(Interval(0, 1), Interval(2, 3)))
def test_sympy__sets__sets__Complement():
from sympy.sets.sets import Complement
assert _test_args(Complement(Interval(0, 2), Interval(0, 1)))
def test_sympy__sets__sets__SymmetricDifference():
from sympy.sets.sets import FiniteSet, SymmetricDifference
assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__sets__sets__DisjointUnion():
from sympy.sets.sets import FiniteSet, DisjointUnion
assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__core__trace__Tr():
from sympy.core.trace import Tr
a, b = symbols('a b')
assert _test_args(Tr(a + b))
def test_sympy__sets__setexpr__SetExpr():
from sympy.sets.setexpr import SetExpr
assert _test_args(SetExpr(Interval(0, 1)))
def test_sympy__sets__fancysets__Rationals():
from sympy.sets.fancysets import Rationals
assert _test_args(Rationals())
def test_sympy__sets__fancysets__Naturals():
from sympy.sets.fancysets import Naturals
assert _test_args(Naturals())
def test_sympy__sets__fancysets__Naturals0():
from sympy.sets.fancysets import Naturals0
assert _test_args(Naturals0())
def test_sympy__sets__fancysets__Integers():
from sympy.sets.fancysets import Integers
assert _test_args(Integers())
def test_sympy__sets__fancysets__Reals():
from sympy.sets.fancysets import Reals
assert _test_args(Reals())
def test_sympy__sets__fancysets__Complexes():
from sympy.sets.fancysets import Complexes
assert _test_args(Complexes())
def test_sympy__sets__fancysets__ComplexRegion():
from sympy.sets.fancysets import ComplexRegion
from sympy import S
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
theta = Interval(0, 2*S.Pi)
assert _test_args(ComplexRegion(a*b))
assert _test_args(ComplexRegion(a*theta, polar=True))
def test_sympy__sets__fancysets__CartesianComplexRegion():
from sympy.sets.fancysets import CartesianComplexRegion
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
assert _test_args(CartesianComplexRegion(a*b))
def test_sympy__sets__fancysets__PolarComplexRegion():
from sympy.sets.fancysets import PolarComplexRegion
from sympy import S
from sympy.sets import Interval
a = Interval(0, 1)
theta = Interval(0, 2*S.Pi)
assert _test_args(PolarComplexRegion(a*theta))
def test_sympy__sets__fancysets__ImageSet():
from sympy.sets.fancysets import ImageSet
from sympy import S, Symbol
x = Symbol('x')
assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals))
def test_sympy__sets__fancysets__Range():
from sympy.sets.fancysets import Range
assert _test_args(Range(1, 5, 1))
def test_sympy__sets__conditionset__ConditionSet():
from sympy.sets.conditionset import ConditionSet
from sympy import S, Symbol
x = Symbol('x')
assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals))
def test_sympy__sets__contains__Contains():
from sympy.sets.fancysets import Range
from sympy.sets.contains import Contains
assert _test_args(Contains(x, Range(0, 10, 2)))
# STATS
from sympy.stats.crv_types import NormalDistribution
nd = NormalDistribution(0, 1)
from sympy.stats.frv_types import DieDistribution
die = DieDistribution(6)
def test_sympy__stats__crv__ContinuousDomain():
from sympy.stats.crv import ContinuousDomain
assert _test_args(ContinuousDomain({x}, Interval(-oo, oo)))
def test_sympy__stats__crv__SingleContinuousDomain():
from sympy.stats.crv import SingleContinuousDomain
assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))
def test_sympy__stats__crv__ProductContinuousDomain():
from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
E = SingleContinuousDomain(y, Interval(0, oo))
assert _test_args(ProductContinuousDomain(D, E))
def test_sympy__stats__crv__ConditionalContinuousDomain():
from sympy.stats.crv import (SingleContinuousDomain,
ConditionalContinuousDomain)
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ConditionalContinuousDomain(D, x > 0))
def test_sympy__stats__crv__ContinuousPSpace():
from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ContinuousPSpace(D, nd))
def test_sympy__stats__crv__SingleContinuousPSpace():
from sympy.stats.crv import SingleContinuousPSpace
assert _test_args(SingleContinuousPSpace(x, nd))
@SKIP("abstract class")
def test_sympy__stats__crv__SingleContinuousDistribution():
pass
def test_sympy__stats__drv__SingleDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain
assert _test_args(SingleDiscreteDomain(x, S.Naturals))
def test_sympy__stats__drv__ProductDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals)
Y = SingleDiscreteDomain(y, S.Integers)
assert _test_args(ProductDiscreteDomain(X, Y))
def test_sympy__stats__drv__SingleDiscretePSpace():
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))
def test_sympy__stats__drv__DiscretePSpace():
from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain
density = Lambda(x, 2**(-x))
domain = SingleDiscreteDomain(x, S.Naturals)
assert _test_args(DiscretePSpace(domain, density))
def test_sympy__stats__drv__ConditionalDiscreteDomain():
from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals0)
assert _test_args(ConditionalDiscreteDomain(X, x > 2))
def test_sympy__stats__joint_rv__JointPSpace():
from sympy.stats.joint_rv import JointPSpace, JointDistribution
assert _test_args(JointPSpace('X', JointDistribution(1)))
def test_sympy__stats__joint_rv__JointRandomSymbol():
from sympy.stats.joint_rv import JointRandomSymbol
assert _test_args(JointRandomSymbol(x))
def test_sympy__stats__joint_rv_types__JointDistributionHandmade():
from sympy import Indexed
from sympy.stats.joint_rv_types import JointDistributionHandmade
x1, x2 = (Indexed('x', i) for i in (1, 2))
assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2))
def test_sympy__stats__joint_rv__MarginalDistribution():
from sympy.stats.rv import RandomSymbol
from sympy.stats.joint_rv import MarginalDistribution
r = RandomSymbol(S('r'))
assert _test_args(MarginalDistribution(r, (r,)))
def test_sympy__stats__compound_rv__CompoundDistribution():
from sympy.stats.compound_rv import CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 10)
assert _test_args(CompoundDistribution(PoissonDistribution(r)))
def test_sympy__stats__compound_rv__CompoundPSpace():
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 5)
C = CompoundDistribution(PoissonDistribution(r))
assert _test_args(CompoundPSpace('C', C))
@SKIP("abstract class")
def test_sympy__stats__drv__SingleDiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDomain():
pass
def test_sympy__stats__rv__RandomDomain():
from sympy.stats.rv import RandomDomain
from sympy.sets.sets import FiniteSet
assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__SingleDomain():
from sympy.stats.rv import SingleDomain
from sympy.sets.sets import FiniteSet
assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__ConditionalDomain():
from sympy.stats.rv import ConditionalDomain, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2))
assert _test_args(ConditionalDomain(D, x > 1))
def test_sympy__stats__rv__MatrixDomain():
from sympy.stats.rv import MatrixDomain
from sympy.matrices import MatrixSet
from sympy import S
assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals)))
def test_sympy__stats__rv__PSpace():
from sympy.stats.rv import PSpace, RandomDomain
from sympy import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6))
assert _test_args(PSpace(D, die))
@SKIP("abstract Class")
def test_sympy__stats__rv__SinglePSpace():
pass
def test_sympy__stats__rv__RandomSymbol():
from sympy.stats.rv import RandomSymbol
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
assert _test_args(RandomSymbol(x, A))
@SKIP("abstract Class")
def test_sympy__stats__rv__ProductPSpace():
pass
def test_sympy__stats__rv__IndependentProductPSpace():
from sympy.stats.rv import IndependentProductPSpace
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
B = SingleContinuousPSpace(y, nd)
assert _test_args(IndependentProductPSpace(A, B))
def test_sympy__stats__rv__ProductDomain():
from sympy.stats.rv import ProductDomain, SingleDomain
D = SingleDomain(x, Interval(-oo, oo))
E = SingleDomain(y, Interval(0, oo))
assert _test_args(ProductDomain(D, E))
def test_sympy__stats__symbolic_probability__Probability():
from sympy.stats.symbolic_probability import Probability
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Probability(X > 0))
def test_sympy__stats__symbolic_probability__Expectation():
from sympy.stats.symbolic_probability import Expectation
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Expectation(X > 0))
def test_sympy__stats__symbolic_probability__Covariance():
from sympy.stats.symbolic_probability import Covariance
from sympy.stats import Normal
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 3)
assert _test_args(Covariance(X, Y))
def test_sympy__stats__symbolic_probability__Variance():
from sympy.stats.symbolic_probability import Variance
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Variance(X))
def test_sympy__stats__symbolic_probability__Moment():
from sympy.stats.symbolic_probability import Moment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Moment(X, 3, 2, X > 3))
def test_sympy__stats__symbolic_probability__CentralMoment():
from sympy.stats.symbolic_probability import CentralMoment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(CentralMoment(X, 2, X > 1))
def test_sympy__stats__frv_types__DiscreteUniformDistribution():
from sympy.stats.frv_types import DiscreteUniformDistribution
from sympy.core.containers import Tuple
assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6)))))
def test_sympy__stats__frv_types__DieDistribution():
assert _test_args(die)
def test_sympy__stats__frv_types__BernoulliDistribution():
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(BernoulliDistribution(S.Half, 0, 1))
def test_sympy__stats__frv_types__BinomialDistribution():
from sympy.stats.frv_types import BinomialDistribution
assert _test_args(BinomialDistribution(5, S.Half, 1, 0))
def test_sympy__stats__frv_types__BetaBinomialDistribution():
from sympy.stats.frv_types import BetaBinomialDistribution
assert _test_args(BetaBinomialDistribution(5, 1, 1))
def test_sympy__stats__frv_types__HypergeometricDistribution():
from sympy.stats.frv_types import HypergeometricDistribution
assert _test_args(HypergeometricDistribution(10, 5, 3))
def test_sympy__stats__frv_types__RademacherDistribution():
from sympy.stats.frv_types import RademacherDistribution
assert _test_args(RademacherDistribution())
def test_sympy__stats__frv_types__IdealSolitonDistribution():
from sympy.stats.frv_types import IdealSolitonDistribution
assert _test_args(IdealSolitonDistribution(10))
def test_sympy__stats__frv_types__RobustSolitonDistribution():
from sympy.stats.frv_types import RobustSolitonDistribution
assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1))
def test_sympy__stats__frv__FiniteDomain():
from sympy.stats.frv import FiniteDomain
assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2
def test_sympy__stats__frv__SingleFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain
assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2
def test_sympy__stats__frv__ProductFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
yd = SingleFiniteDomain(y, {1, 2})
assert _test_args(ProductFiniteDomain(xd, yd))
def test_sympy__stats__frv__ConditionalFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(ConditionalFiniteDomain(xd, x > 1))
def test_sympy__stats__frv__FinitePSpace():
from sympy.stats.frv import FinitePSpace, SingleFiniteDomain
xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
def test_sympy__stats__frv__SingleFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace
from sympy import Symbol
assert _test_args(SingleFinitePSpace(Symbol('x'), die))
def test_sympy__stats__frv__ProductFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace
from sympy import Symbol
xp = SingleFinitePSpace(Symbol('x'), die)
yp = SingleFinitePSpace(Symbol('y'), die)
assert _test_args(ProductFinitePSpace(xp, yp))
@SKIP("abstract class")
def test_sympy__stats__frv__SingleFiniteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__ContinuousDistribution():
pass
def test_sympy__stats__frv_types__FiniteDistributionHandmade():
from sympy.stats.frv_types import FiniteDistributionHandmade
from sympy import Dict
assert _test_args(FiniteDistributionHandmade(Dict({1: 1})))
def test_sympy__stats__crv_types__ContinuousDistributionHandmade():
from sympy.stats.crv_types import ContinuousDistributionHandmade
from sympy import Interval, Lambda
from sympy.abc import x
assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x),
Interval(0, 1)))
def test_sympy__stats__drv_types__DiscreteDistributionHandmade():
from sympy.stats.drv_types import DiscreteDistributionHandmade
from sympy import Lambda, FiniteSet
from sympy.abc import x
assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)),
FiniteSet(*range(10))))
def test_sympy__stats__rv__Density():
from sympy.stats.rv import Density
from sympy.stats.crv_types import Normal
assert _test_args(Density(Normal('x', 0, 1)))
def test_sympy__stats__crv_types__ArcsinDistribution():
from sympy.stats.crv_types import ArcsinDistribution
assert _test_args(ArcsinDistribution(0, 1))
def test_sympy__stats__crv_types__BeniniDistribution():
from sympy.stats.crv_types import BeniniDistribution
assert _test_args(BeniniDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaDistribution():
from sympy.stats.crv_types import BetaDistribution
assert _test_args(BetaDistribution(1, 1))
def test_sympy__stats__crv_types__BetaNoncentralDistribution():
from sympy.stats.crv_types import BetaNoncentralDistribution
assert _test_args(BetaNoncentralDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaPrimeDistribution():
from sympy.stats.crv_types import BetaPrimeDistribution
assert _test_args(BetaPrimeDistribution(1, 1))
def test_sympy__stats__crv_types__BoundedParetoDistribution():
from sympy.stats.crv_types import BoundedParetoDistribution
assert _test_args(BoundedParetoDistribution(1, 1, 2))
def test_sympy__stats__crv_types__CauchyDistribution():
from sympy.stats.crv_types import CauchyDistribution
assert _test_args(CauchyDistribution(0, 1))
def test_sympy__stats__crv_types__ChiDistribution():
from sympy.stats.crv_types import ChiDistribution
assert _test_args(ChiDistribution(1))
def test_sympy__stats__crv_types__ChiNoncentralDistribution():
from sympy.stats.crv_types import ChiNoncentralDistribution
assert _test_args(ChiNoncentralDistribution(1,1))
def test_sympy__stats__crv_types__ChiSquaredDistribution():
from sympy.stats.crv_types import ChiSquaredDistribution
assert _test_args(ChiSquaredDistribution(1))
def test_sympy__stats__crv_types__DagumDistribution():
from sympy.stats.crv_types import DagumDistribution
assert _test_args(DagumDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExGaussianDistribution():
from sympy.stats.crv_types import ExGaussianDistribution
assert _test_args(ExGaussianDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExponentialDistribution():
from sympy.stats.crv_types import ExponentialDistribution
assert _test_args(ExponentialDistribution(1))
def test_sympy__stats__crv_types__ExponentialPowerDistribution():
from sympy.stats.crv_types import ExponentialPowerDistribution
assert _test_args(ExponentialPowerDistribution(0, 1, 1))
def test_sympy__stats__crv_types__FDistributionDistribution():
from sympy.stats.crv_types import FDistributionDistribution
assert _test_args(FDistributionDistribution(1, 1))
def test_sympy__stats__crv_types__FisherZDistribution():
from sympy.stats.crv_types import FisherZDistribution
assert _test_args(FisherZDistribution(1, 1))
def test_sympy__stats__crv_types__FrechetDistribution():
from sympy.stats.crv_types import FrechetDistribution
assert _test_args(FrechetDistribution(1, 1, 1))
def test_sympy__stats__crv_types__GammaInverseDistribution():
from sympy.stats.crv_types import GammaInverseDistribution
assert _test_args(GammaInverseDistribution(1, 1))
def test_sympy__stats__crv_types__GammaDistribution():
from sympy.stats.crv_types import GammaDistribution
assert _test_args(GammaDistribution(1, 1))
def test_sympy__stats__crv_types__GumbelDistribution():
from sympy.stats.crv_types import GumbelDistribution
assert _test_args(GumbelDistribution(1, 1, False))
def test_sympy__stats__crv_types__GompertzDistribution():
from sympy.stats.crv_types import GompertzDistribution
assert _test_args(GompertzDistribution(1, 1))
def test_sympy__stats__crv_types__KumaraswamyDistribution():
from sympy.stats.crv_types import KumaraswamyDistribution
assert _test_args(KumaraswamyDistribution(1, 1))
def test_sympy__stats__crv_types__LaplaceDistribution():
from sympy.stats.crv_types import LaplaceDistribution
assert _test_args(LaplaceDistribution(0, 1))
def test_sympy__stats__crv_types__LevyDistribution():
from sympy.stats.crv_types import LevyDistribution
assert _test_args(LevyDistribution(0, 1))
def test_sympy__stats__crv_types__LogisticDistribution():
from sympy.stats.crv_types import LogisticDistribution
assert _test_args(LogisticDistribution(0, 1))
def test_sympy__stats__crv_types__LogLogisticDistribution():
from sympy.stats.crv_types import LogLogisticDistribution
assert _test_args(LogLogisticDistribution(1, 1))
def test_sympy__stats__crv_types__LogitNormalDistribution():
from sympy.stats.crv_types import LogitNormalDistribution
assert _test_args(LogitNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LomaxDistribution():
from sympy.stats.crv_types import LomaxDistribution
assert _test_args(LomaxDistribution(1, 2))
def test_sympy__stats__crv_types__MaxwellDistribution():
from sympy.stats.crv_types import MaxwellDistribution
assert _test_args(MaxwellDistribution(1))
def test_sympy__stats__crv_types__MoyalDistribution():
from sympy.stats.crv_types import MoyalDistribution
assert _test_args(MoyalDistribution(1,2))
def test_sympy__stats__crv_types__NakagamiDistribution():
from sympy.stats.crv_types import NakagamiDistribution
assert _test_args(NakagamiDistribution(1, 1))
def test_sympy__stats__crv_types__NormalDistribution():
from sympy.stats.crv_types import NormalDistribution
assert _test_args(NormalDistribution(0, 1))
def test_sympy__stats__crv_types__GaussianInverseDistribution():
from sympy.stats.crv_types import GaussianInverseDistribution
assert _test_args(GaussianInverseDistribution(1, 1))
def test_sympy__stats__crv_types__ParetoDistribution():
from sympy.stats.crv_types import ParetoDistribution
assert _test_args(ParetoDistribution(1, 1))
def test_sympy__stats__crv_types__PowerFunctionDistribution():
from sympy.stats.crv_types import PowerFunctionDistribution
assert _test_args(PowerFunctionDistribution(2,0,1))
def test_sympy__stats__crv_types__QuadraticUDistribution():
from sympy.stats.crv_types import QuadraticUDistribution
assert _test_args(QuadraticUDistribution(1, 2))
def test_sympy__stats__crv_types__RaisedCosineDistribution():
from sympy.stats.crv_types import RaisedCosineDistribution
assert _test_args(RaisedCosineDistribution(1, 1))
def test_sympy__stats__crv_types__RayleighDistribution():
from sympy.stats.crv_types import RayleighDistribution
assert _test_args(RayleighDistribution(1))
def test_sympy__stats__crv_types__ReciprocalDistribution():
from sympy.stats.crv_types import ReciprocalDistribution
assert _test_args(ReciprocalDistribution(5, 30))
def test_sympy__stats__crv_types__ShiftedGompertzDistribution():
from sympy.stats.crv_types import ShiftedGompertzDistribution
assert _test_args(ShiftedGompertzDistribution(1, 1))
def test_sympy__stats__crv_types__StudentTDistribution():
from sympy.stats.crv_types import StudentTDistribution
assert _test_args(StudentTDistribution(1))
def test_sympy__stats__crv_types__TrapezoidalDistribution():
from sympy.stats.crv_types import TrapezoidalDistribution
assert _test_args(TrapezoidalDistribution(1, 2, 3, 4))
def test_sympy__stats__crv_types__TriangularDistribution():
from sympy.stats.crv_types import TriangularDistribution
assert _test_args(TriangularDistribution(-1, 0, 1))
def test_sympy__stats__crv_types__UniformDistribution():
from sympy.stats.crv_types import UniformDistribution
assert _test_args(UniformDistribution(0, 1))
def test_sympy__stats__crv_types__UniformSumDistribution():
from sympy.stats.crv_types import UniformSumDistribution
assert _test_args(UniformSumDistribution(1))
def test_sympy__stats__crv_types__VonMisesDistribution():
from sympy.stats.crv_types import VonMisesDistribution
assert _test_args(VonMisesDistribution(1, 1))
def test_sympy__stats__crv_types__WeibullDistribution():
from sympy.stats.crv_types import WeibullDistribution
assert _test_args(WeibullDistribution(1, 1))
def test_sympy__stats__crv_types__WignerSemicircleDistribution():
from sympy.stats.crv_types import WignerSemicircleDistribution
assert _test_args(WignerSemicircleDistribution(1))
def test_sympy__stats__drv_types__GeometricDistribution():
from sympy.stats.drv_types import GeometricDistribution
assert _test_args(GeometricDistribution(.5))
def test_sympy__stats__drv_types__HermiteDistribution():
from sympy.stats.drv_types import HermiteDistribution
assert _test_args(HermiteDistribution(1, 2))
def test_sympy__stats__drv_types__LogarithmicDistribution():
from sympy.stats.drv_types import LogarithmicDistribution
assert _test_args(LogarithmicDistribution(.5))
def test_sympy__stats__drv_types__NegativeBinomialDistribution():
from sympy.stats.drv_types import NegativeBinomialDistribution
assert _test_args(NegativeBinomialDistribution(.5, .5))
def test_sympy__stats__drv_types__PoissonDistribution():
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(PoissonDistribution(1))
def test_sympy__stats__drv_types__SkellamDistribution():
from sympy.stats.drv_types import SkellamDistribution
assert _test_args(SkellamDistribution(1, 1))
def test_sympy__stats__drv_types__YuleSimonDistribution():
from sympy.stats.drv_types import YuleSimonDistribution
assert _test_args(YuleSimonDistribution(.5))
def test_sympy__stats__drv_types__ZetaDistribution():
from sympy.stats.drv_types import ZetaDistribution
assert _test_args(ZetaDistribution(1.5))
def test_sympy__stats__joint_rv__JointDistribution():
from sympy.stats.joint_rv import JointDistribution
assert _test_args(JointDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution():
from sympy.stats.joint_rv_types import MultivariateNormalDistribution
assert _test_args(
MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution():
from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution
assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateTDistribution():
from sympy.stats.joint_rv_types import MultivariateTDistribution
assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1))
def test_sympy__stats__joint_rv_types__NormalGammaDistribution():
from sympy.stats.joint_rv_types import NormalGammaDistribution
assert _test_args(NormalGammaDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution():
from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution
v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4])
assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu))
def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution():
from sympy.stats.joint_rv_types import MultivariateBetaDistribution
assert _test_args(MultivariateBetaDistribution([1, 2, 3]))
def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution():
from sympy.stats.joint_rv_types import MultivariateEwensDistribution
assert _test_args(MultivariateEwensDistribution(5, 1))
def test_sympy__stats__joint_rv_types__MultinomialDistribution():
from sympy.stats.joint_rv_types import MultinomialDistribution
assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution():
from sympy.stats.joint_rv_types import NegativeMultinomialDistribution
assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__rv__RandomIndexedSymbol():
from sympy.stats.rv import RandomIndexedSymbol, pspace
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
X = DiscreteMarkovChain("X")
assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0])))
def test_sympy__stats__rv__RandomMatrixSymbol():
from sympy.stats.rv import RandomMatrixSymbol
from sympy.stats.random_matrix import RandomMatrixPSpace
pspace = RandomMatrixPSpace('P')
assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace))
def test_sympy__stats__stochastic_process__StochasticPSpace():
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.stochastic_process_types import StochasticProcess
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0)))
def test_sympy__stats__stochastic_process_types__StochasticProcess():
from sympy.stats.stochastic_process_types import StochasticProcess
assert _test_args(StochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__MarkovProcess():
from sympy.stats.stochastic_process_types import MarkovProcess
assert _test_args(MarkovProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess():
from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess
assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess():
from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess
assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__TransitionMatrixOf():
from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain
from sympy import MatrixSymbol
DMC = DiscreteMarkovChain("Y")
assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf():
from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain
from sympy import MatrixSymbol
DMC = ContinuousMarkovChain("Y")
assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf():
from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain
DMC = DiscreteMarkovChain("Y")
assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2]))
def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain():
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
from sympy import MatrixSymbol
assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain():
from sympy.stats.stochastic_process_types import ContinuousMarkovChain
from sympy import MatrixSymbol
assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__BernoulliProcess():
from sympy.stats.stochastic_process_types import BernoulliProcess
assert _test_args(BernoulliProcess("B", 0.5, 1, 0))
def test_sympy__stats__stochastic_process_types__CountingProcess():
from sympy.stats.stochastic_process_types import CountingProcess
assert _test_args(CountingProcess("C"))
def test_sympy__stats__stochastic_process_types__PoissonProcess():
from sympy.stats.stochastic_process_types import PoissonProcess
assert _test_args(PoissonProcess("X", 2))
def test_sympy__stats__stochastic_process_types__WienerProcess():
from sympy.stats.stochastic_process_types import WienerProcess
assert _test_args(WienerProcess("X"))
def test_sympy__stats__stochastic_process_types__GammaProcess():
from sympy.stats.stochastic_process_types import GammaProcess
assert _test_args(GammaProcess("X", 1, 2))
def test_sympy__stats__random_matrix__RandomMatrixPSpace():
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
model = RandomMatrixEnsembleModel('R', 3)
assert _test_args(RandomMatrixPSpace('P', model=model))
def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel():
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
assert _test_args(RandomMatrixEnsembleModel('R', 3))
def test_sympy__stats__random_matrix_models__GaussianEnsembleModel():
from sympy.stats.random_matrix_models import GaussianEnsembleModel
assert _test_args(GaussianEnsembleModel('G', 3))
def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel
assert _test_args(GaussianUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel
assert _test_args(GaussianOrthogonalEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel
assert _test_args(GaussianSymplecticEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularEnsembleModel():
from sympy.stats.random_matrix_models import CircularEnsembleModel
assert _test_args(CircularEnsembleModel('C', 3))
def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel
assert _test_args(CircularUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel
assert _test_args(CircularOrthogonalEnsembleModel('O', 3))
def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel
assert _test_args(CircularSymplecticEnsembleModel('S', 3))
def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix():
from sympy.stats import ExpectationMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1)))
def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix():
from sympy.stats import VarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1)))
def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix():
from sympy.stats import CrossCovarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1),
RandomMatrixSymbol('X', 3, 1)))
def test_sympy__stats__matrix_distributions__MatrixPSpace():
from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace
from sympy import Matrix
M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))
assert _test_args(MatrixPSpace('M', M, 2, 2))
def test_sympy__stats__matrix_distributions__MatrixDistribution():
from sympy.stats.matrix_distributions import MatrixDistribution
from sympy import Matrix
assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixGammaDistribution():
from sympy.stats.matrix_distributions import MatrixGammaDistribution
from sympy import Matrix
assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__WishartDistribution():
from sympy.stats.matrix_distributions import WishartDistribution
from sympy import Matrix
assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixNormalDistribution():
from sympy.stats.matrix_distributions import MatrixNormalDistribution
from sympy import MatrixSymbol
L = MatrixSymbol('L', 1, 2)
S1 = MatrixSymbol('S1', 1, 1)
S2 = MatrixSymbol('S2', 2, 2)
assert _test_args(MatrixNormalDistribution(L, S1, S2))
def test_sympy__utilities__matchpy_connector__WildDot():
from sympy.utilities.matchpy_connector import WildDot
assert _test_args(WildDot("w_"))
def test_sympy__utilities__matchpy_connector__WildPlus():
from sympy.utilities.matchpy_connector import WildPlus
assert _test_args(WildPlus("w__"))
def test_sympy__utilities__matchpy_connector__WildStar():
from sympy.utilities.matchpy_connector import WildStar
assert _test_args(WildStar("w___"))
def test_sympy__core__symbol__Str():
from sympy.core.symbol import Str
assert _test_args(Str('t'))
def test_sympy__core__symbol__Dummy():
from sympy.core.symbol import Dummy
assert _test_args(Dummy('t'))
def test_sympy__core__symbol__Symbol():
from sympy.core.symbol import Symbol
assert _test_args(Symbol('t'))
def test_sympy__core__symbol__Wild():
from sympy.core.symbol import Wild
assert _test_args(Wild('x', exclude=[x]))
@SKIP("abstract class")
def test_sympy__functions__combinatorial__factorials__CombinatorialFunction():
pass
def test_sympy__functions__combinatorial__factorials__FallingFactorial():
from sympy.functions.combinatorial.factorials import FallingFactorial
assert _test_args(FallingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__MultiFactorial():
from sympy.functions.combinatorial.factorials import MultiFactorial
assert _test_args(MultiFactorial(x))
def test_sympy__functions__combinatorial__factorials__RisingFactorial():
from sympy.functions.combinatorial.factorials import RisingFactorial
assert _test_args(RisingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__binomial():
from sympy.functions.combinatorial.factorials import binomial
assert _test_args(binomial(2, x))
def test_sympy__functions__combinatorial__factorials__subfactorial():
from sympy.functions.combinatorial.factorials import subfactorial
assert _test_args(subfactorial(1))
def test_sympy__functions__combinatorial__factorials__factorial():
from sympy.functions.combinatorial.factorials import factorial
assert _test_args(factorial(x))
def test_sympy__functions__combinatorial__factorials__factorial2():
from sympy.functions.combinatorial.factorials import factorial2
assert _test_args(factorial2(x))
def test_sympy__functions__combinatorial__numbers__bell():
from sympy.functions.combinatorial.numbers import bell
assert _test_args(bell(x, y))
def test_sympy__functions__combinatorial__numbers__bernoulli():
from sympy.functions.combinatorial.numbers import bernoulli
assert _test_args(bernoulli(x))
def test_sympy__functions__combinatorial__numbers__catalan():
from sympy.functions.combinatorial.numbers import catalan
assert _test_args(catalan(x))
def test_sympy__functions__combinatorial__numbers__genocchi():
from sympy.functions.combinatorial.numbers import genocchi
assert _test_args(genocchi(x))
def test_sympy__functions__combinatorial__numbers__euler():
from sympy.functions.combinatorial.numbers import euler
assert _test_args(euler(x))
def test_sympy__functions__combinatorial__numbers__carmichael():
from sympy.functions.combinatorial.numbers import carmichael
assert _test_args(carmichael(x))
def test_sympy__functions__combinatorial__numbers__fibonacci():
from sympy.functions.combinatorial.numbers import fibonacci
assert _test_args(fibonacci(x))
def test_sympy__functions__combinatorial__numbers__tribonacci():
from sympy.functions.combinatorial.numbers import tribonacci
assert _test_args(tribonacci(x))
def test_sympy__functions__combinatorial__numbers__harmonic():
from sympy.functions.combinatorial.numbers import harmonic
assert _test_args(harmonic(x, 2))
def test_sympy__functions__combinatorial__numbers__lucas():
from sympy.functions.combinatorial.numbers import lucas
assert _test_args(lucas(x))
def test_sympy__functions__combinatorial__numbers__partition():
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.numbers import partition
assert _test_args(partition(Symbol('a', integer=True)))
def test_sympy__functions__elementary__complexes__Abs():
from sympy.functions.elementary.complexes import Abs
assert _test_args(Abs(x))
def test_sympy__functions__elementary__complexes__adjoint():
from sympy.functions.elementary.complexes import adjoint
assert _test_args(adjoint(x))
def test_sympy__functions__elementary__complexes__arg():
from sympy.functions.elementary.complexes import arg
assert _test_args(arg(x))
def test_sympy__functions__elementary__complexes__conjugate():
from sympy.functions.elementary.complexes import conjugate
assert _test_args(conjugate(x))
def test_sympy__functions__elementary__complexes__im():
from sympy.functions.elementary.complexes import im
assert _test_args(im(x))
def test_sympy__functions__elementary__complexes__re():
from sympy.functions.elementary.complexes import re
assert _test_args(re(x))
def test_sympy__functions__elementary__complexes__sign():
from sympy.functions.elementary.complexes import sign
assert _test_args(sign(x))
def test_sympy__functions__elementary__complexes__polar_lift():
from sympy.functions.elementary.complexes import polar_lift
assert _test_args(polar_lift(x))
def test_sympy__functions__elementary__complexes__periodic_argument():
from sympy.functions.elementary.complexes import periodic_argument
assert _test_args(periodic_argument(x, y))
def test_sympy__functions__elementary__complexes__principal_branch():
from sympy.functions.elementary.complexes import principal_branch
assert _test_args(principal_branch(x, y))
def test_sympy__functions__elementary__complexes__transpose():
from sympy.functions.elementary.complexes import transpose
assert _test_args(transpose(x))
def test_sympy__functions__elementary__exponential__LambertW():
from sympy.functions.elementary.exponential import LambertW
assert _test_args(LambertW(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__exponential__ExpBase():
pass
def test_sympy__functions__elementary__exponential__exp():
from sympy.functions.elementary.exponential import exp
assert _test_args(exp(2))
def test_sympy__functions__elementary__exponential__exp_polar():
from sympy.functions.elementary.exponential import exp_polar
assert _test_args(exp_polar(2))
def test_sympy__functions__elementary__exponential__log():
from sympy.functions.elementary.exponential import log
assert _test_args(log(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction():
pass
def test_sympy__functions__elementary__hyperbolic__acosh():
from sympy.functions.elementary.hyperbolic import acosh
assert _test_args(acosh(2))
def test_sympy__functions__elementary__hyperbolic__acoth():
from sympy.functions.elementary.hyperbolic import acoth
assert _test_args(acoth(2))
def test_sympy__functions__elementary__hyperbolic__asinh():
from sympy.functions.elementary.hyperbolic import asinh
assert _test_args(asinh(2))
def test_sympy__functions__elementary__hyperbolic__atanh():
from sympy.functions.elementary.hyperbolic import atanh
assert _test_args(atanh(2))
def test_sympy__functions__elementary__hyperbolic__asech():
from sympy.functions.elementary.hyperbolic import asech
assert _test_args(asech(2))
def test_sympy__functions__elementary__hyperbolic__acsch():
from sympy.functions.elementary.hyperbolic import acsch
assert _test_args(acsch(2))
def test_sympy__functions__elementary__hyperbolic__cosh():
from sympy.functions.elementary.hyperbolic import cosh
assert _test_args(cosh(2))
def test_sympy__functions__elementary__hyperbolic__coth():
from sympy.functions.elementary.hyperbolic import coth
assert _test_args(coth(2))
def test_sympy__functions__elementary__hyperbolic__csch():
from sympy.functions.elementary.hyperbolic import csch
assert _test_args(csch(2))
def test_sympy__functions__elementary__hyperbolic__sech():
from sympy.functions.elementary.hyperbolic import sech
assert _test_args(sech(2))
def test_sympy__functions__elementary__hyperbolic__sinh():
from sympy.functions.elementary.hyperbolic import sinh
assert _test_args(sinh(2))
def test_sympy__functions__elementary__hyperbolic__tanh():
from sympy.functions.elementary.hyperbolic import tanh
assert _test_args(tanh(2))
@SKIP("does this work at all?")
def test_sympy__functions__elementary__integers__RoundFunction():
from sympy.functions.elementary.integers import RoundFunction
assert _test_args(RoundFunction())
def test_sympy__functions__elementary__integers__ceiling():
from sympy.functions.elementary.integers import ceiling
assert _test_args(ceiling(x))
def test_sympy__functions__elementary__integers__floor():
from sympy.functions.elementary.integers import floor
assert _test_args(floor(x))
def test_sympy__functions__elementary__integers__frac():
from sympy.functions.elementary.integers import frac
assert _test_args(frac(x))
def test_sympy__functions__elementary__miscellaneous__IdentityFunction():
from sympy.functions.elementary.miscellaneous import IdentityFunction
assert _test_args(IdentityFunction())
def test_sympy__functions__elementary__miscellaneous__Max():
from sympy.functions.elementary.miscellaneous import Max
assert _test_args(Max(x, 2))
def test_sympy__functions__elementary__miscellaneous__Min():
from sympy.functions.elementary.miscellaneous import Min
assert _test_args(Min(x, 2))
@SKIP("abstract class")
def test_sympy__functions__elementary__miscellaneous__MinMaxBase():
pass
def test_sympy__functions__elementary__piecewise__ExprCondPair():
from sympy.functions.elementary.piecewise import ExprCondPair
assert _test_args(ExprCondPair(1, True))
def test_sympy__functions__elementary__piecewise__Piecewise():
from sympy.functions.elementary.piecewise import Piecewise
assert _test_args(Piecewise((1, x >= 0), (0, True)))
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__TrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction():
pass
def test_sympy__functions__elementary__trigonometric__acos():
from sympy.functions.elementary.trigonometric import acos
assert _test_args(acos(2))
def test_sympy__functions__elementary__trigonometric__acot():
from sympy.functions.elementary.trigonometric import acot
assert _test_args(acot(2))
def test_sympy__functions__elementary__trigonometric__asin():
from sympy.functions.elementary.trigonometric import asin
assert _test_args(asin(2))
def test_sympy__functions__elementary__trigonometric__asec():
from sympy.functions.elementary.trigonometric import asec
assert _test_args(asec(2))
def test_sympy__functions__elementary__trigonometric__acsc():
from sympy.functions.elementary.trigonometric import acsc
assert _test_args(acsc(2))
def test_sympy__functions__elementary__trigonometric__atan():
from sympy.functions.elementary.trigonometric import atan
assert _test_args(atan(2))
def test_sympy__functions__elementary__trigonometric__atan2():
from sympy.functions.elementary.trigonometric import atan2
assert _test_args(atan2(2, 3))
def test_sympy__functions__elementary__trigonometric__cos():
from sympy.functions.elementary.trigonometric import cos
assert _test_args(cos(2))
def test_sympy__functions__elementary__trigonometric__csc():
from sympy.functions.elementary.trigonometric import csc
assert _test_args(csc(2))
def test_sympy__functions__elementary__trigonometric__cot():
from sympy.functions.elementary.trigonometric import cot
assert _test_args(cot(2))
def test_sympy__functions__elementary__trigonometric__sin():
assert _test_args(sin(2))
def test_sympy__functions__elementary__trigonometric__sinc():
from sympy.functions.elementary.trigonometric import sinc
assert _test_args(sinc(2))
def test_sympy__functions__elementary__trigonometric__sec():
from sympy.functions.elementary.trigonometric import sec
assert _test_args(sec(2))
def test_sympy__functions__elementary__trigonometric__tan():
from sympy.functions.elementary.trigonometric import tan
assert _test_args(tan(2))
@SKIP("abstract class")
def test_sympy__functions__special__bessel__BesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalBesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalHankelBase():
pass
def test_sympy__functions__special__bessel__besseli():
from sympy.functions.special.bessel import besseli
assert _test_args(besseli(x, 1))
def test_sympy__functions__special__bessel__besselj():
from sympy.functions.special.bessel import besselj
assert _test_args(besselj(x, 1))
def test_sympy__functions__special__bessel__besselk():
from sympy.functions.special.bessel import besselk
assert _test_args(besselk(x, 1))
def test_sympy__functions__special__bessel__bessely():
from sympy.functions.special.bessel import bessely
assert _test_args(bessely(x, 1))
def test_sympy__functions__special__bessel__hankel1():
from sympy.functions.special.bessel import hankel1
assert _test_args(hankel1(x, 1))
def test_sympy__functions__special__bessel__hankel2():
from sympy.functions.special.bessel import hankel2
assert _test_args(hankel2(x, 1))
def test_sympy__functions__special__bessel__jn():
from sympy.functions.special.bessel import jn
assert _test_args(jn(0, x))
def test_sympy__functions__special__bessel__yn():
from sympy.functions.special.bessel import yn
assert _test_args(yn(0, x))
def test_sympy__functions__special__bessel__hn1():
from sympy.functions.special.bessel import hn1
assert _test_args(hn1(0, x))
def test_sympy__functions__special__bessel__hn2():
from sympy.functions.special.bessel import hn2
assert _test_args(hn2(0, x))
def test_sympy__functions__special__bessel__AiryBase():
pass
def test_sympy__functions__special__bessel__airyai():
from sympy.functions.special.bessel import airyai
assert _test_args(airyai(2))
def test_sympy__functions__special__bessel__airybi():
from sympy.functions.special.bessel import airybi
assert _test_args(airybi(2))
def test_sympy__functions__special__bessel__airyaiprime():
from sympy.functions.special.bessel import airyaiprime
assert _test_args(airyaiprime(2))
def test_sympy__functions__special__bessel__airybiprime():
from sympy.functions.special.bessel import airybiprime
assert _test_args(airybiprime(2))
def test_sympy__functions__special__bessel__marcumq():
from sympy.functions.special.bessel import marcumq
assert _test_args(marcumq(x, y, z))
def test_sympy__functions__special__elliptic_integrals__elliptic_k():
from sympy.functions.special.elliptic_integrals import elliptic_k as K
assert _test_args(K(x))
def test_sympy__functions__special__elliptic_integrals__elliptic_f():
from sympy.functions.special.elliptic_integrals import elliptic_f as F
assert _test_args(F(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_e():
from sympy.functions.special.elliptic_integrals import elliptic_e as E
assert _test_args(E(x))
assert _test_args(E(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_pi():
from sympy.functions.special.elliptic_integrals import elliptic_pi as P
assert _test_args(P(x, y))
assert _test_args(P(x, y, z))
def test_sympy__functions__special__delta_functions__DiracDelta():
from sympy.functions.special.delta_functions import DiracDelta
assert _test_args(DiracDelta(x, 1))
def test_sympy__functions__special__singularity_functions__SingularityFunction():
from sympy.functions.special.singularity_functions import SingularityFunction
assert _test_args(SingularityFunction(x, y, z))
def test_sympy__functions__special__delta_functions__Heaviside():
from sympy.functions.special.delta_functions import Heaviside
assert _test_args(Heaviside(x))
def test_sympy__functions__special__error_functions__erf():
from sympy.functions.special.error_functions import erf
assert _test_args(erf(2))
def test_sympy__functions__special__error_functions__erfc():
from sympy.functions.special.error_functions import erfc
assert _test_args(erfc(2))
def test_sympy__functions__special__error_functions__erfi():
from sympy.functions.special.error_functions import erfi
assert _test_args(erfi(2))
def test_sympy__functions__special__error_functions__erf2():
from sympy.functions.special.error_functions import erf2
assert _test_args(erf2(2, 3))
def test_sympy__functions__special__error_functions__erfinv():
from sympy.functions.special.error_functions import erfinv
assert _test_args(erfinv(2))
def test_sympy__functions__special__error_functions__erfcinv():
from sympy.functions.special.error_functions import erfcinv
assert _test_args(erfcinv(2))
def test_sympy__functions__special__error_functions__erf2inv():
from sympy.functions.special.error_functions import erf2inv
assert _test_args(erf2inv(2, 3))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__FresnelIntegral():
pass
def test_sympy__functions__special__error_functions__fresnels():
from sympy.functions.special.error_functions import fresnels
assert _test_args(fresnels(2))
def test_sympy__functions__special__error_functions__fresnelc():
from sympy.functions.special.error_functions import fresnelc
assert _test_args(fresnelc(2))
def test_sympy__functions__special__error_functions__erfs():
from sympy.functions.special.error_functions import _erfs
assert _test_args(_erfs(2))
def test_sympy__functions__special__error_functions__Ei():
from sympy.functions.special.error_functions import Ei
assert _test_args(Ei(2))
def test_sympy__functions__special__error_functions__li():
from sympy.functions.special.error_functions import li
assert _test_args(li(2))
def test_sympy__functions__special__error_functions__Li():
from sympy.functions.special.error_functions import Li
assert _test_args(Li(2))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__TrigonometricIntegral():
pass
def test_sympy__functions__special__error_functions__Si():
from sympy.functions.special.error_functions import Si
assert _test_args(Si(2))
def test_sympy__functions__special__error_functions__Ci():
from sympy.functions.special.error_functions import Ci
assert _test_args(Ci(2))
def test_sympy__functions__special__error_functions__Shi():
from sympy.functions.special.error_functions import Shi
assert _test_args(Shi(2))
def test_sympy__functions__special__error_functions__Chi():
from sympy.functions.special.error_functions import Chi
assert _test_args(Chi(2))
def test_sympy__functions__special__error_functions__expint():
from sympy.functions.special.error_functions import expint
assert _test_args(expint(y, x))
def test_sympy__functions__special__gamma_functions__gamma():
from sympy.functions.special.gamma_functions import gamma
assert _test_args(gamma(x))
def test_sympy__functions__special__gamma_functions__loggamma():
from sympy.functions.special.gamma_functions import loggamma
assert _test_args(loggamma(2))
def test_sympy__functions__special__gamma_functions__lowergamma():
from sympy.functions.special.gamma_functions import lowergamma
assert _test_args(lowergamma(x, 2))
def test_sympy__functions__special__gamma_functions__polygamma():
from sympy.functions.special.gamma_functions import polygamma
assert _test_args(polygamma(x, 2))
def test_sympy__functions__special__gamma_functions__digamma():
from sympy.functions.special.gamma_functions import digamma
assert _test_args(digamma(x))
def test_sympy__functions__special__gamma_functions__trigamma():
from sympy.functions.special.gamma_functions import trigamma
assert _test_args(trigamma(x))
def test_sympy__functions__special__gamma_functions__uppergamma():
from sympy.functions.special.gamma_functions import uppergamma
assert _test_args(uppergamma(x, 2))
def test_sympy__functions__special__gamma_functions__multigamma():
from sympy.functions.special.gamma_functions import multigamma
assert _test_args(multigamma(x, 1))
def test_sympy__functions__special__beta_functions__beta():
from sympy.functions.special.beta_functions import beta
assert _test_args(beta(x, x))
def test_sympy__functions__special__mathieu_functions__MathieuBase():
pass
def test_sympy__functions__special__mathieu_functions__mathieus():
from sympy.functions.special.mathieu_functions import mathieus
assert _test_args(mathieus(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieuc():
from sympy.functions.special.mathieu_functions import mathieuc
assert _test_args(mathieuc(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieusprime():
from sympy.functions.special.mathieu_functions import mathieusprime
assert _test_args(mathieusprime(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieucprime():
from sympy.functions.special.mathieu_functions import mathieucprime
assert _test_args(mathieucprime(1, 1, 1))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleParametersBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleArg():
pass
def test_sympy__functions__special__hyper__hyper():
from sympy.functions.special.hyper import hyper
assert _test_args(hyper([1, 2, 3], [4, 5], x))
def test_sympy__functions__special__hyper__meijerg():
from sympy.functions.special.hyper import meijerg
assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__HyperRep():
pass
def test_sympy__functions__special__hyper__HyperRep_power1():
from sympy.functions.special.hyper import HyperRep_power1
assert _test_args(HyperRep_power1(x, y))
def test_sympy__functions__special__hyper__HyperRep_power2():
from sympy.functions.special.hyper import HyperRep_power2
assert _test_args(HyperRep_power2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log1():
from sympy.functions.special.hyper import HyperRep_log1
assert _test_args(HyperRep_log1(x))
def test_sympy__functions__special__hyper__HyperRep_atanh():
from sympy.functions.special.hyper import HyperRep_atanh
assert _test_args(HyperRep_atanh(x))
def test_sympy__functions__special__hyper__HyperRep_asin1():
from sympy.functions.special.hyper import HyperRep_asin1
assert _test_args(HyperRep_asin1(x))
def test_sympy__functions__special__hyper__HyperRep_asin2():
from sympy.functions.special.hyper import HyperRep_asin2
assert _test_args(HyperRep_asin2(x))
def test_sympy__functions__special__hyper__HyperRep_sqrts1():
from sympy.functions.special.hyper import HyperRep_sqrts1
assert _test_args(HyperRep_sqrts1(x, y))
def test_sympy__functions__special__hyper__HyperRep_sqrts2():
from sympy.functions.special.hyper import HyperRep_sqrts2
assert _test_args(HyperRep_sqrts2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log2():
from sympy.functions.special.hyper import HyperRep_log2
assert _test_args(HyperRep_log2(x))
def test_sympy__functions__special__hyper__HyperRep_cosasin():
from sympy.functions.special.hyper import HyperRep_cosasin
assert _test_args(HyperRep_cosasin(x, y))
def test_sympy__functions__special__hyper__HyperRep_sinasin():
from sympy.functions.special.hyper import HyperRep_sinasin
assert _test_args(HyperRep_sinasin(x, y))
def test_sympy__functions__special__hyper__appellf1():
from sympy.functions.special.hyper import appellf1
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
assert _test_args(appellf1(a, b1, b2, c, x, y))
@SKIP("abstract class")
def test_sympy__functions__special__polynomials__OrthogonalPolynomial():
pass
def test_sympy__functions__special__polynomials__jacobi():
from sympy.functions.special.polynomials import jacobi
assert _test_args(jacobi(x, 2, 2, 2))
def test_sympy__functions__special__polynomials__gegenbauer():
from sympy.functions.special.polynomials import gegenbauer
assert _test_args(gegenbauer(x, 2, 2))
def test_sympy__functions__special__polynomials__chebyshevt():
from sympy.functions.special.polynomials import chebyshevt
assert _test_args(chebyshevt(x, 2))
def test_sympy__functions__special__polynomials__chebyshevt_root():
from sympy.functions.special.polynomials import chebyshevt_root
assert _test_args(chebyshevt_root(3, 2))
def test_sympy__functions__special__polynomials__chebyshevu():
from sympy.functions.special.polynomials import chebyshevu
assert _test_args(chebyshevu(x, 2))
def test_sympy__functions__special__polynomials__chebyshevu_root():
from sympy.functions.special.polynomials import chebyshevu_root
assert _test_args(chebyshevu_root(3, 2))
def test_sympy__functions__special__polynomials__hermite():
from sympy.functions.special.polynomials import hermite
assert _test_args(hermite(x, 2))
def test_sympy__functions__special__polynomials__legendre():
from sympy.functions.special.polynomials import legendre
assert _test_args(legendre(x, 2))
def test_sympy__functions__special__polynomials__assoc_legendre():
from sympy.functions.special.polynomials import assoc_legendre
assert _test_args(assoc_legendre(x, 0, y))
def test_sympy__functions__special__polynomials__laguerre():
from sympy.functions.special.polynomials import laguerre
assert _test_args(laguerre(x, 2))
def test_sympy__functions__special__polynomials__assoc_laguerre():
from sympy.functions.special.polynomials import assoc_laguerre
assert _test_args(assoc_laguerre(x, 0, y))
def test_sympy__functions__special__spherical_harmonics__Ynm():
from sympy.functions.special.spherical_harmonics import Ynm
assert _test_args(Ynm(1, 1, x, y))
def test_sympy__functions__special__spherical_harmonics__Znm():
from sympy.functions.special.spherical_harmonics import Znm
assert _test_args(Znm(1, 1, x, y))
def test_sympy__functions__special__tensor_functions__LeviCivita():
from sympy.functions.special.tensor_functions import LeviCivita
assert _test_args(LeviCivita(x, y, 2))
def test_sympy__functions__special__tensor_functions__KroneckerDelta():
from sympy.functions.special.tensor_functions import KroneckerDelta
assert _test_args(KroneckerDelta(x, y))
def test_sympy__functions__special__zeta_functions__dirichlet_eta():
from sympy.functions.special.zeta_functions import dirichlet_eta
assert _test_args(dirichlet_eta(x))
def test_sympy__functions__special__zeta_functions__zeta():
from sympy.functions.special.zeta_functions import zeta
assert _test_args(zeta(101))
def test_sympy__functions__special__zeta_functions__lerchphi():
from sympy.functions.special.zeta_functions import lerchphi
assert _test_args(lerchphi(x, y, z))
def test_sympy__functions__special__zeta_functions__polylog():
from sympy.functions.special.zeta_functions import polylog
assert _test_args(polylog(x, y))
def test_sympy__functions__special__zeta_functions__stieltjes():
from sympy.functions.special.zeta_functions import stieltjes
assert _test_args(stieltjes(x, y))
def test_sympy__integrals__integrals__Integral():
from sympy.integrals.integrals import Integral
assert _test_args(Integral(2, (x, 0, 1)))
def test_sympy__integrals__risch__NonElementaryIntegral():
from sympy.integrals.risch import NonElementaryIntegral
assert _test_args(NonElementaryIntegral(exp(-x**2), x))
@SKIP("abstract class")
def test_sympy__integrals__transforms__IntegralTransform():
pass
def test_sympy__integrals__transforms__MellinTransform():
from sympy.integrals.transforms import MellinTransform
assert _test_args(MellinTransform(2, x, y))
def test_sympy__integrals__transforms__InverseMellinTransform():
from sympy.integrals.transforms import InverseMellinTransform
assert _test_args(InverseMellinTransform(2, x, y, 0, 1))
def test_sympy__integrals__transforms__LaplaceTransform():
from sympy.integrals.transforms import LaplaceTransform
assert _test_args(LaplaceTransform(2, x, y))
def test_sympy__integrals__transforms__InverseLaplaceTransform():
from sympy.integrals.transforms import InverseLaplaceTransform
assert _test_args(InverseLaplaceTransform(2, x, y, 0))
@SKIP("abstract class")
def test_sympy__integrals__transforms__FourierTypeTransform():
pass
def test_sympy__integrals__transforms__InverseFourierTransform():
from sympy.integrals.transforms import InverseFourierTransform
assert _test_args(InverseFourierTransform(2, x, y))
def test_sympy__integrals__transforms__FourierTransform():
from sympy.integrals.transforms import FourierTransform
assert _test_args(FourierTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__SineCosineTypeTransform():
pass
def test_sympy__integrals__transforms__InverseSineTransform():
from sympy.integrals.transforms import InverseSineTransform
assert _test_args(InverseSineTransform(2, x, y))
def test_sympy__integrals__transforms__SineTransform():
from sympy.integrals.transforms import SineTransform
assert _test_args(SineTransform(2, x, y))
def test_sympy__integrals__transforms__InverseCosineTransform():
from sympy.integrals.transforms import InverseCosineTransform
assert _test_args(InverseCosineTransform(2, x, y))
def test_sympy__integrals__transforms__CosineTransform():
from sympy.integrals.transforms import CosineTransform
assert _test_args(CosineTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__HankelTypeTransform():
pass
def test_sympy__integrals__transforms__InverseHankelTransform():
from sympy.integrals.transforms import InverseHankelTransform
assert _test_args(InverseHankelTransform(2, x, y, 0))
def test_sympy__integrals__transforms__HankelTransform():
from sympy.integrals.transforms import HankelTransform
assert _test_args(HankelTransform(2, x, y, 0))
@XFAIL
def test_sympy__liealgebras__cartan_type__CartanType_generator():
from sympy.liealgebras.cartan_type import CartanType_generator
assert _test_args(CartanType_generator("A2"))
@XFAIL
def test_sympy__liealgebras__cartan_type__Standard_Cartan():
from sympy.liealgebras.cartan_type import Standard_Cartan
assert _test_args(Standard_Cartan("A", 2))
@XFAIL
def test_sympy__liealgebras__weyl_group__WeylGroup():
from sympy.liealgebras.weyl_group import WeylGroup
assert _test_args(WeylGroup("B4"))
@XFAIL
def test_sympy__liealgebras__root_system__RootSystem():
from sympy.liealgebras.root_system import RootSystem
assert _test_args(RootSystem("A2"))
@XFAIL
def test_sympy__liealgebras__type_a__TypeA():
from sympy.liealgebras.type_a import TypeA
assert _test_args(TypeA(2))
@XFAIL
def test_sympy__liealgebras__type_b__TypeB():
from sympy.liealgebras.type_b import TypeB
assert _test_args(TypeB(4))
@XFAIL
def test_sympy__liealgebras__type_c__TypeC():
from sympy.liealgebras.type_c import TypeC
assert _test_args(TypeC(4))
@XFAIL
def test_sympy__liealgebras__type_d__TypeD():
from sympy.liealgebras.type_d import TypeD
assert _test_args(TypeD(4))
@XFAIL
def test_sympy__liealgebras__type_e__TypeE():
from sympy.liealgebras.type_e import TypeE
assert _test_args(TypeE(6))
@XFAIL
def test_sympy__liealgebras__type_f__TypeF():
from sympy.liealgebras.type_f import TypeF
assert _test_args(TypeF(4))
@XFAIL
def test_sympy__liealgebras__type_g__TypeG():
from sympy.liealgebras.type_g import TypeG
assert _test_args(TypeG(2))
def test_sympy__logic__boolalg__And():
from sympy.logic.boolalg import And
assert _test_args(And(x, y, 1))
@SKIP("abstract class")
def test_sympy__logic__boolalg__Boolean():
pass
def test_sympy__logic__boolalg__BooleanFunction():
from sympy.logic.boolalg import BooleanFunction
assert _test_args(BooleanFunction(1, 2, 3))
@SKIP("abstract class")
def test_sympy__logic__boolalg__BooleanAtom():
pass
def test_sympy__logic__boolalg__BooleanTrue():
from sympy.logic.boolalg import true
assert _test_args(true)
def test_sympy__logic__boolalg__BooleanFalse():
from sympy.logic.boolalg import false
assert _test_args(false)
def test_sympy__logic__boolalg__Equivalent():
from sympy.logic.boolalg import Equivalent
assert _test_args(Equivalent(x, 2))
def test_sympy__logic__boolalg__ITE():
from sympy.logic.boolalg import ITE
assert _test_args(ITE(x, y, 1))
def test_sympy__logic__boolalg__Implies():
from sympy.logic.boolalg import Implies
assert _test_args(Implies(x, y))
def test_sympy__logic__boolalg__Nand():
from sympy.logic.boolalg import Nand
assert _test_args(Nand(x, y, 1))
def test_sympy__logic__boolalg__Nor():
from sympy.logic.boolalg import Nor
assert _test_args(Nor(x, y))
def test_sympy__logic__boolalg__Not():
from sympy.logic.boolalg import Not
assert _test_args(Not(x))
def test_sympy__logic__boolalg__Or():
from sympy.logic.boolalg import Or
assert _test_args(Or(x, y))
def test_sympy__logic__boolalg__Xor():
from sympy.logic.boolalg import Xor
assert _test_args(Xor(x, y, 2))
def test_sympy__logic__boolalg__Xnor():
from sympy.logic.boolalg import Xnor
assert _test_args(Xnor(x, y, 2))
def test_sympy__matrices__matrices__DeferredVector():
from sympy.matrices.matrices import DeferredVector
assert _test_args(DeferredVector("X"))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixBase():
pass
def test_sympy__matrices__immutable__ImmutableDenseMatrix():
from sympy.matrices.immutable import ImmutableDenseMatrix
m = ImmutableDenseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__immutable__ImmutableSparseMatrix():
from sympy.matrices.immutable import ImmutableSparseMatrix
m = ImmutableSparseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, {(0, 0): 1})
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__expressions__slice__MatrixSlice():
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 4, 4)
assert _test_args(MatrixSlice(X, (0, 2), (0, 2)))
def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction():
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol("X", x, x)
func = Lambda(x, x**2)
assert _test_args(ElementwiseApplyFunction(func, X))
def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix():
from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
assert _test_args(BlockDiagMatrix(X, Y))
def test_sympy__matrices__expressions__blockmatrix__BlockMatrix():
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
Z = MatrixSymbol('Z', x, y)
O = ZeroMatrix(y, x)
assert _test_args(BlockMatrix([[X, Z], [O, Y]]))
def test_sympy__matrices__expressions__inverse__Inverse():
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Inverse(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__matadd__MatAdd():
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(MatAdd(X, Y))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixExpr():
pass
def test_sympy__matrices__expressions__matexpr__MatrixElement():
from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement
from sympy import S
assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3)))
def test_sympy__matrices__expressions__matexpr__MatrixSymbol():
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(MatrixSymbol('A', 3, 5))
def test_sympy__matrices__expressions__special__OneMatrix():
from sympy.matrices.expressions.special import OneMatrix
assert _test_args(OneMatrix(3, 5))
def test_sympy__matrices__expressions__special__ZeroMatrix():
from sympy.matrices.expressions.special import ZeroMatrix
assert _test_args(ZeroMatrix(3, 5))
def test_sympy__matrices__expressions__special__GenericZeroMatrix():
from sympy.matrices.expressions.special import GenericZeroMatrix
assert _test_args(GenericZeroMatrix())
def test_sympy__matrices__expressions__special__Identity():
from sympy.matrices.expressions.special import Identity
assert _test_args(Identity(3))
def test_sympy__matrices__expressions__special__GenericIdentity():
from sympy.matrices.expressions.special import GenericIdentity
assert _test_args(GenericIdentity())
def test_sympy__matrices__expressions__sets__MatrixSet():
from sympy.matrices.expressions.sets import MatrixSet
from sympy import S
assert _test_args(MatrixSet(2, 2, S.Reals))
def test_sympy__matrices__expressions__matmul__MatMul():
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', y, x)
assert _test_args(MatMul(X, Y))
def test_sympy__matrices__expressions__dotproduct__DotProduct():
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, 1)
Y = MatrixSymbol('Y', x, 1)
assert _test_args(DotProduct(X, Y))
def test_sympy__matrices__expressions__diagonal__DiagonalMatrix():
from sympy.matrices.expressions.diagonal import DiagonalMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagonalMatrix(x))
def test_sympy__matrices__expressions__diagonal__DiagonalOf():
from sympy.matrices.expressions.diagonal import DiagonalOf
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('x', 10, 10)
assert _test_args(DiagonalOf(X))
def test_sympy__matrices__expressions__diagonal__DiagMatrix():
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagMatrix(x))
def test_sympy__matrices__expressions__hadamard__HadamardProduct():
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(HadamardProduct(X, Y))
def test_sympy__matrices__expressions__hadamard__HadamardPower():
from sympy.matrices.expressions.hadamard import HadamardPower
from sympy.matrices.expressions import MatrixSymbol
from sympy import Symbol
X = MatrixSymbol('X', x, y)
n = Symbol("n")
assert _test_args(HadamardPower(X, n))
def test_sympy__matrices__expressions__kronecker__KroneckerProduct():
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(KroneckerProduct(X, Y))
def test_sympy__matrices__expressions__matpow__MatPow():
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
assert _test_args(MatPow(X, 2))
def test_sympy__matrices__expressions__transpose__Transpose():
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Transpose(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__adjoint__Adjoint():
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Adjoint(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__trace__Trace():
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Trace(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Determinant():
from sympy.matrices.expressions.determinant import Determinant
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Determinant(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Permanent():
from sympy.matrices.expressions.determinant import Permanent
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Permanent(MatrixSymbol('A', 3, 4)))
def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix():
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy import symbols
i, j = symbols('i,j')
assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) ))
def test_sympy__matrices__expressions__fourier__DFT():
from sympy.matrices.expressions.fourier import DFT
from sympy import S
assert _test_args(DFT(S(2)))
def test_sympy__matrices__expressions__fourier__IDFT():
from sympy.matrices.expressions.fourier import IDFT
from sympy import S
assert _test_args(IDFT(S(2)))
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 10, 10)
def test_sympy__matrices__expressions__factorizations__LofLU():
from sympy.matrices.expressions.factorizations import LofLU
assert _test_args(LofLU(X))
def test_sympy__matrices__expressions__factorizations__UofLU():
from sympy.matrices.expressions.factorizations import UofLU
assert _test_args(UofLU(X))
def test_sympy__matrices__expressions__factorizations__QofQR():
from sympy.matrices.expressions.factorizations import QofQR
assert _test_args(QofQR(X))
def test_sympy__matrices__expressions__factorizations__RofQR():
from sympy.matrices.expressions.factorizations import RofQR
assert _test_args(RofQR(X))
def test_sympy__matrices__expressions__factorizations__LofCholesky():
from sympy.matrices.expressions.factorizations import LofCholesky
assert _test_args(LofCholesky(X))
def test_sympy__matrices__expressions__factorizations__UofCholesky():
from sympy.matrices.expressions.factorizations import UofCholesky
assert _test_args(UofCholesky(X))
def test_sympy__matrices__expressions__factorizations__EigenVectors():
from sympy.matrices.expressions.factorizations import EigenVectors
assert _test_args(EigenVectors(X))
def test_sympy__matrices__expressions__factorizations__EigenValues():
from sympy.matrices.expressions.factorizations import EigenValues
assert _test_args(EigenValues(X))
def test_sympy__matrices__expressions__factorizations__UofSVD():
from sympy.matrices.expressions.factorizations import UofSVD
assert _test_args(UofSVD(X))
def test_sympy__matrices__expressions__factorizations__VofSVD():
from sympy.matrices.expressions.factorizations import VofSVD
assert _test_args(VofSVD(X))
def test_sympy__matrices__expressions__factorizations__SofSVD():
from sympy.matrices.expressions.factorizations import SofSVD
assert _test_args(SofSVD(X))
@SKIP("abstract class")
def test_sympy__matrices__expressions__factorizations__Factorization():
pass
def test_sympy__matrices__expressions__permutation__PermutationMatrix():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.permutation import PermutationMatrix
assert _test_args(PermutationMatrix(Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__permutation__MatrixPermute():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.permutation import MatrixPermute
A = MatrixSymbol('A', 3, 3)
assert _test_args(MatrixPermute(A, Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__companion__CompanionMatrix():
from sympy.core.symbol import Symbol
from sympy.matrices.expressions.companion import CompanionMatrix
from sympy.polys.polytools import Poly
x = Symbol('x')
p = Poly([1, 2, 3], x)
assert _test_args(CompanionMatrix(p))
def test_sympy__physics__vector__frame__CoordinateSym():
from sympy.physics.vector import CoordinateSym
from sympy.physics.vector import ReferenceFrame
assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))
def test_sympy__physics__paulialgebra__Pauli():
from sympy.physics.paulialgebra import Pauli
assert _test_args(Pauli(1))
def test_sympy__physics__quantum__anticommutator__AntiCommutator():
from sympy.physics.quantum.anticommutator import AntiCommutator
assert _test_args(AntiCommutator(x, y))
def test_sympy__physics__quantum__cartesian__PositionBra3D():
from sympy.physics.quantum.cartesian import PositionBra3D
assert _test_args(PositionBra3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionKet3D():
from sympy.physics.quantum.cartesian import PositionKet3D
assert _test_args(PositionKet3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionState3D():
from sympy.physics.quantum.cartesian import PositionState3D
assert _test_args(PositionState3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PxBra():
from sympy.physics.quantum.cartesian import PxBra
assert _test_args(PxBra(x, y, z))
def test_sympy__physics__quantum__cartesian__PxKet():
from sympy.physics.quantum.cartesian import PxKet
assert _test_args(PxKet(x, y, z))
def test_sympy__physics__quantum__cartesian__PxOp():
from sympy.physics.quantum.cartesian import PxOp
assert _test_args(PxOp(x, y, z))
def test_sympy__physics__quantum__cartesian__XBra():
from sympy.physics.quantum.cartesian import XBra
assert _test_args(XBra(x))
def test_sympy__physics__quantum__cartesian__XKet():
from sympy.physics.quantum.cartesian import XKet
assert _test_args(XKet(x))
def test_sympy__physics__quantum__cartesian__XOp():
from sympy.physics.quantum.cartesian import XOp
assert _test_args(XOp(x))
def test_sympy__physics__quantum__cartesian__YOp():
from sympy.physics.quantum.cartesian import YOp
assert _test_args(YOp(x))
def test_sympy__physics__quantum__cartesian__ZOp():
from sympy.physics.quantum.cartesian import ZOp
assert _test_args(ZOp(x))
def test_sympy__physics__quantum__cg__CG():
from sympy.physics.quantum.cg import CG
from sympy import S
assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1))
def test_sympy__physics__quantum__cg__Wigner3j():
from sympy.physics.quantum.cg import Wigner3j
assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0))
def test_sympy__physics__quantum__cg__Wigner6j():
from sympy.physics.quantum.cg import Wigner6j
assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2))
def test_sympy__physics__quantum__cg__Wigner9j():
from sympy.physics.quantum.cg import Wigner9j
assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0))
def test_sympy__physics__quantum__circuitplot__Mz():
from sympy.physics.quantum.circuitplot import Mz
assert _test_args(Mz(0))
def test_sympy__physics__quantum__circuitplot__Mx():
from sympy.physics.quantum.circuitplot import Mx
assert _test_args(Mx(0))
def test_sympy__physics__quantum__commutator__Commutator():
from sympy.physics.quantum.commutator import Commutator
A, B = symbols('A,B', commutative=False)
assert _test_args(Commutator(A, B))
def test_sympy__physics__quantum__constants__HBar():
from sympy.physics.quantum.constants import HBar
assert _test_args(HBar())
def test_sympy__physics__quantum__dagger__Dagger():
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Ket
assert _test_args(Dagger(Dagger(Ket('psi'))))
def test_sympy__physics__quantum__gate__CGate():
from sympy.physics.quantum.gate import CGate, Gate
assert _test_args(CGate((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CGateS():
from sympy.physics.quantum.gate import CGateS, Gate
assert _test_args(CGateS((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CNotGate():
from sympy.physics.quantum.gate import CNotGate
assert _test_args(CNotGate(0, 1))
def test_sympy__physics__quantum__gate__Gate():
from sympy.physics.quantum.gate import Gate
assert _test_args(Gate(0))
def test_sympy__physics__quantum__gate__HadamardGate():
from sympy.physics.quantum.gate import HadamardGate
assert _test_args(HadamardGate(0))
def test_sympy__physics__quantum__gate__IdentityGate():
from sympy.physics.quantum.gate import IdentityGate
assert _test_args(IdentityGate(0))
def test_sympy__physics__quantum__gate__OneQubitGate():
from sympy.physics.quantum.gate import OneQubitGate
assert _test_args(OneQubitGate(0))
def test_sympy__physics__quantum__gate__PhaseGate():
from sympy.physics.quantum.gate import PhaseGate
assert _test_args(PhaseGate(0))
def test_sympy__physics__quantum__gate__SwapGate():
from sympy.physics.quantum.gate import SwapGate
assert _test_args(SwapGate(0, 1))
def test_sympy__physics__quantum__gate__TGate():
from sympy.physics.quantum.gate import TGate
assert _test_args(TGate(0))
def test_sympy__physics__quantum__gate__TwoQubitGate():
from sympy.physics.quantum.gate import TwoQubitGate
assert _test_args(TwoQubitGate(0))
def test_sympy__physics__quantum__gate__UGate():
from sympy.physics.quantum.gate import UGate
from sympy.matrices.immutable import ImmutableDenseMatrix
from sympy import Integer, Tuple
assert _test_args(
UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]])))
def test_sympy__physics__quantum__gate__XGate():
from sympy.physics.quantum.gate import XGate
assert _test_args(XGate(0))
def test_sympy__physics__quantum__gate__YGate():
from sympy.physics.quantum.gate import YGate
assert _test_args(YGate(0))
def test_sympy__physics__quantum__gate__ZGate():
from sympy.physics.quantum.gate import ZGate
assert _test_args(ZGate(0))
@SKIP("TODO: sympy.physics")
def test_sympy__physics__quantum__grover__OracleGate():
from sympy.physics.quantum.grover import OracleGate
assert _test_args(OracleGate())
def test_sympy__physics__quantum__grover__WGate():
from sympy.physics.quantum.grover import WGate
assert _test_args(WGate(1))
def test_sympy__physics__quantum__hilbert__ComplexSpace():
from sympy.physics.quantum.hilbert import ComplexSpace
assert _test_args(ComplexSpace(x))
def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace():
from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(DirectSumHilbertSpace(c, f))
def test_sympy__physics__quantum__hilbert__FockSpace():
from sympy.physics.quantum.hilbert import FockSpace
assert _test_args(FockSpace())
def test_sympy__physics__quantum__hilbert__HilbertSpace():
from sympy.physics.quantum.hilbert import HilbertSpace
assert _test_args(HilbertSpace())
def test_sympy__physics__quantum__hilbert__L2():
from sympy.physics.quantum.hilbert import L2
from sympy import oo, Interval
assert _test_args(L2(Interval(0, oo)))
def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace():
from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace
f = FockSpace()
assert _test_args(TensorPowerHilbertSpace(f, 2))
def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace():
from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(TensorProductHilbertSpace(f, c))
def test_sympy__physics__quantum__innerproduct__InnerProduct():
from sympy.physics.quantum import Bra, Ket, InnerProduct
b = Bra('b')
k = Ket('k')
assert _test_args(InnerProduct(b, k))
def test_sympy__physics__quantum__operator__DifferentialOperator():
from sympy.physics.quantum.operator import DifferentialOperator
from sympy import Derivative, Function
f = Function('f')
assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x)))
def test_sympy__physics__quantum__operator__HermitianOperator():
from sympy.physics.quantum.operator import HermitianOperator
assert _test_args(HermitianOperator('H'))
def test_sympy__physics__quantum__operator__IdentityOperator():
from sympy.physics.quantum.operator import IdentityOperator
assert _test_args(IdentityOperator(5))
def test_sympy__physics__quantum__operator__Operator():
from sympy.physics.quantum.operator import Operator
assert _test_args(Operator('A'))
def test_sympy__physics__quantum__operator__OuterProduct():
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum import Ket, Bra
b = Bra('b')
k = Ket('k')
assert _test_args(OuterProduct(k, b))
def test_sympy__physics__quantum__operator__UnitaryOperator():
from sympy.physics.quantum.operator import UnitaryOperator
assert _test_args(UnitaryOperator('U'))
def test_sympy__physics__quantum__piab__PIABBra():
from sympy.physics.quantum.piab import PIABBra
assert _test_args(PIABBra('B'))
def test_sympy__physics__quantum__boson__BosonOp():
from sympy.physics.quantum.boson import BosonOp
assert _test_args(BosonOp('a'))
assert _test_args(BosonOp('a', False))
def test_sympy__physics__quantum__boson__BosonFockKet():
from sympy.physics.quantum.boson import BosonFockKet
assert _test_args(BosonFockKet(1))
def test_sympy__physics__quantum__boson__BosonFockBra():
from sympy.physics.quantum.boson import BosonFockBra
assert _test_args(BosonFockBra(1))
def test_sympy__physics__quantum__boson__BosonCoherentKet():
from sympy.physics.quantum.boson import BosonCoherentKet
assert _test_args(BosonCoherentKet(1))
def test_sympy__physics__quantum__boson__BosonCoherentBra():
from sympy.physics.quantum.boson import BosonCoherentBra
assert _test_args(BosonCoherentBra(1))
def test_sympy__physics__quantum__fermion__FermionOp():
from sympy.physics.quantum.fermion import FermionOp
assert _test_args(FermionOp('c'))
assert _test_args(FermionOp('c', False))
def test_sympy__physics__quantum__fermion__FermionFockKet():
from sympy.physics.quantum.fermion import FermionFockKet
assert _test_args(FermionFockKet(1))
def test_sympy__physics__quantum__fermion__FermionFockBra():
from sympy.physics.quantum.fermion import FermionFockBra
assert _test_args(FermionFockBra(1))
def test_sympy__physics__quantum__pauli__SigmaOpBase():
from sympy.physics.quantum.pauli import SigmaOpBase
assert _test_args(SigmaOpBase())
def test_sympy__physics__quantum__pauli__SigmaX():
from sympy.physics.quantum.pauli import SigmaX
assert _test_args(SigmaX())
def test_sympy__physics__quantum__pauli__SigmaY():
from sympy.physics.quantum.pauli import SigmaY
assert _test_args(SigmaY())
def test_sympy__physics__quantum__pauli__SigmaZ():
from sympy.physics.quantum.pauli import SigmaZ
assert _test_args(SigmaZ())
def test_sympy__physics__quantum__pauli__SigmaMinus():
from sympy.physics.quantum.pauli import SigmaMinus
assert _test_args(SigmaMinus())
def test_sympy__physics__quantum__pauli__SigmaPlus():
from sympy.physics.quantum.pauli import SigmaPlus
assert _test_args(SigmaPlus())
def test_sympy__physics__quantum__pauli__SigmaZKet():
from sympy.physics.quantum.pauli import SigmaZKet
assert _test_args(SigmaZKet(0))
def test_sympy__physics__quantum__pauli__SigmaZBra():
from sympy.physics.quantum.pauli import SigmaZBra
assert _test_args(SigmaZBra(0))
def test_sympy__physics__quantum__piab__PIABHamiltonian():
from sympy.physics.quantum.piab import PIABHamiltonian
assert _test_args(PIABHamiltonian('P'))
def test_sympy__physics__quantum__piab__PIABKet():
from sympy.physics.quantum.piab import PIABKet
assert _test_args(PIABKet('K'))
def test_sympy__physics__quantum__qexpr__QExpr():
from sympy.physics.quantum.qexpr import QExpr
assert _test_args(QExpr(0))
def test_sympy__physics__quantum__qft__Fourier():
from sympy.physics.quantum.qft import Fourier
assert _test_args(Fourier(0, 1))
def test_sympy__physics__quantum__qft__IQFT():
from sympy.physics.quantum.qft import IQFT
assert _test_args(IQFT(0, 1))
def test_sympy__physics__quantum__qft__QFT():
from sympy.physics.quantum.qft import QFT
assert _test_args(QFT(0, 1))
def test_sympy__physics__quantum__qft__RkGate():
from sympy.physics.quantum.qft import RkGate
assert _test_args(RkGate(0, 1))
def test_sympy__physics__quantum__qubit__IntQubit():
from sympy.physics.quantum.qubit import IntQubit
assert _test_args(IntQubit(0))
def test_sympy__physics__quantum__qubit__IntQubitBra():
from sympy.physics.quantum.qubit import IntQubitBra
assert _test_args(IntQubitBra(0))
def test_sympy__physics__quantum__qubit__IntQubitState():
from sympy.physics.quantum.qubit import IntQubitState, QubitState
assert _test_args(IntQubitState(QubitState(0, 1)))
def test_sympy__physics__quantum__qubit__Qubit():
from sympy.physics.quantum.qubit import Qubit
assert _test_args(Qubit(0, 0, 0))
def test_sympy__physics__quantum__qubit__QubitBra():
from sympy.physics.quantum.qubit import QubitBra
assert _test_args(QubitBra('1', 0))
def test_sympy__physics__quantum__qubit__QubitState():
from sympy.physics.quantum.qubit import QubitState
assert _test_args(QubitState(0, 1))
def test_sympy__physics__quantum__density__Density():
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.state import Ket
assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5]))
@SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented")
def test_sympy__physics__quantum__shor__CMod():
from sympy.physics.quantum.shor import CMod
assert _test_args(CMod())
def test_sympy__physics__quantum__spin__CoupledSpinState():
from sympy.physics.quantum.spin import CoupledSpinState
assert _test_args(CoupledSpinState(1, 0, (1, 1)))
assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half)))
assert _test_args(CoupledSpinState(
1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) ))
j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x')
assert CoupledSpinState(
j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3))
assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \
CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) )
def test_sympy__physics__quantum__spin__J2Op():
from sympy.physics.quantum.spin import J2Op
assert _test_args(J2Op('J'))
def test_sympy__physics__quantum__spin__JminusOp():
from sympy.physics.quantum.spin import JminusOp
assert _test_args(JminusOp('J'))
def test_sympy__physics__quantum__spin__JplusOp():
from sympy.physics.quantum.spin import JplusOp
assert _test_args(JplusOp('J'))
def test_sympy__physics__quantum__spin__JxBra():
from sympy.physics.quantum.spin import JxBra
assert _test_args(JxBra(1, 0))
def test_sympy__physics__quantum__spin__JxBraCoupled():
from sympy.physics.quantum.spin import JxBraCoupled
assert _test_args(JxBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxKet():
from sympy.physics.quantum.spin import JxKet
assert _test_args(JxKet(1, 0))
def test_sympy__physics__quantum__spin__JxKetCoupled():
from sympy.physics.quantum.spin import JxKetCoupled
assert _test_args(JxKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxOp():
from sympy.physics.quantum.spin import JxOp
assert _test_args(JxOp('J'))
def test_sympy__physics__quantum__spin__JyBra():
from sympy.physics.quantum.spin import JyBra
assert _test_args(JyBra(1, 0))
def test_sympy__physics__quantum__spin__JyBraCoupled():
from sympy.physics.quantum.spin import JyBraCoupled
assert _test_args(JyBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyKet():
from sympy.physics.quantum.spin import JyKet
assert _test_args(JyKet(1, 0))
def test_sympy__physics__quantum__spin__JyKetCoupled():
from sympy.physics.quantum.spin import JyKetCoupled
assert _test_args(JyKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyOp():
from sympy.physics.quantum.spin import JyOp
assert _test_args(JyOp('J'))
def test_sympy__physics__quantum__spin__JzBra():
from sympy.physics.quantum.spin import JzBra
assert _test_args(JzBra(1, 0))
def test_sympy__physics__quantum__spin__JzBraCoupled():
from sympy.physics.quantum.spin import JzBraCoupled
assert _test_args(JzBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzKet():
from sympy.physics.quantum.spin import JzKet
assert _test_args(JzKet(1, 0))
def test_sympy__physics__quantum__spin__JzKetCoupled():
from sympy.physics.quantum.spin import JzKetCoupled
assert _test_args(JzKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzOp():
from sympy.physics.quantum.spin import JzOp
assert _test_args(JzOp('J'))
def test_sympy__physics__quantum__spin__Rotation():
from sympy.physics.quantum.spin import Rotation
assert _test_args(Rotation(pi, 0, pi/2))
def test_sympy__physics__quantum__spin__SpinState():
from sympy.physics.quantum.spin import SpinState
assert _test_args(SpinState(1, 0))
def test_sympy__physics__quantum__spin__WignerD():
from sympy.physics.quantum.spin import WignerD
assert _test_args(WignerD(0, 1, 2, 3, 4, 5))
def test_sympy__physics__quantum__state__Bra():
from sympy.physics.quantum.state import Bra
assert _test_args(Bra(0))
def test_sympy__physics__quantum__state__BraBase():
from sympy.physics.quantum.state import BraBase
assert _test_args(BraBase(0))
def test_sympy__physics__quantum__state__Ket():
from sympy.physics.quantum.state import Ket
assert _test_args(Ket(0))
def test_sympy__physics__quantum__state__KetBase():
from sympy.physics.quantum.state import KetBase
assert _test_args(KetBase(0))
def test_sympy__physics__quantum__state__State():
from sympy.physics.quantum.state import State
assert _test_args(State(0))
def test_sympy__physics__quantum__state__StateBase():
from sympy.physics.quantum.state import StateBase
assert _test_args(StateBase(0))
def test_sympy__physics__quantum__state__OrthogonalBra():
from sympy.physics.quantum.state import OrthogonalBra
assert _test_args(OrthogonalBra(0))
def test_sympy__physics__quantum__state__OrthogonalKet():
from sympy.physics.quantum.state import OrthogonalKet
assert _test_args(OrthogonalKet(0))
def test_sympy__physics__quantum__state__OrthogonalState():
from sympy.physics.quantum.state import OrthogonalState
assert _test_args(OrthogonalState(0))
def test_sympy__physics__quantum__state__TimeDepBra():
from sympy.physics.quantum.state import TimeDepBra
assert _test_args(TimeDepBra('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepKet():
from sympy.physics.quantum.state import TimeDepKet
assert _test_args(TimeDepKet('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepState():
from sympy.physics.quantum.state import TimeDepState
assert _test_args(TimeDepState('psi', 't'))
def test_sympy__physics__quantum__state__Wavefunction():
from sympy.physics.quantum.state import Wavefunction
from sympy.functions import sin
from sympy import Piecewise
n = 1
L = 1
g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
assert _test_args(Wavefunction(g, x))
def test_sympy__physics__quantum__tensorproduct__TensorProduct():
from sympy.physics.quantum.tensorproduct import TensorProduct
assert _test_args(TensorProduct(x, y))
def test_sympy__physics__quantum__identitysearch__GateIdentity():
from sympy.physics.quantum.gate import X
from sympy.physics.quantum.identitysearch import GateIdentity
assert _test_args(GateIdentity(X(0), X(0)))
def test_sympy__physics__quantum__sho1d__SHOOp():
from sympy.physics.quantum.sho1d import SHOOp
assert _test_args(SHOOp('a'))
def test_sympy__physics__quantum__sho1d__RaisingOp():
from sympy.physics.quantum.sho1d import RaisingOp
assert _test_args(RaisingOp('a'))
def test_sympy__physics__quantum__sho1d__LoweringOp():
from sympy.physics.quantum.sho1d import LoweringOp
assert _test_args(LoweringOp('a'))
def test_sympy__physics__quantum__sho1d__NumberOp():
from sympy.physics.quantum.sho1d import NumberOp
assert _test_args(NumberOp('N'))
def test_sympy__physics__quantum__sho1d__Hamiltonian():
from sympy.physics.quantum.sho1d import Hamiltonian
assert _test_args(Hamiltonian('H'))
def test_sympy__physics__quantum__sho1d__SHOState():
from sympy.physics.quantum.sho1d import SHOState
assert _test_args(SHOState(0))
def test_sympy__physics__quantum__sho1d__SHOKet():
from sympy.physics.quantum.sho1d import SHOKet
assert _test_args(SHOKet(0))
def test_sympy__physics__quantum__sho1d__SHOBra():
from sympy.physics.quantum.sho1d import SHOBra
assert _test_args(SHOBra(0))
def test_sympy__physics__secondquant__AnnihilateBoson():
from sympy.physics.secondquant import AnnihilateBoson
assert _test_args(AnnihilateBoson(0))
def test_sympy__physics__secondquant__AnnihilateFermion():
from sympy.physics.secondquant import AnnihilateFermion
assert _test_args(AnnihilateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Annihilator():
pass
def test_sympy__physics__secondquant__AntiSymmetricTensor():
from sympy.physics.secondquant import AntiSymmetricTensor
i, j = symbols('i j', below_fermi=True)
a, b = symbols('a b', above_fermi=True)
assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j)))
def test_sympy__physics__secondquant__BosonState():
from sympy.physics.secondquant import BosonState
assert _test_args(BosonState((0, 1)))
@SKIP("abstract class")
def test_sympy__physics__secondquant__BosonicOperator():
pass
def test_sympy__physics__secondquant__Commutator():
from sympy.physics.secondquant import Commutator
assert _test_args(Commutator(x, y))
def test_sympy__physics__secondquant__CreateBoson():
from sympy.physics.secondquant import CreateBoson
assert _test_args(CreateBoson(0))
def test_sympy__physics__secondquant__CreateFermion():
from sympy.physics.secondquant import CreateFermion
assert _test_args(CreateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Creator():
pass
def test_sympy__physics__secondquant__Dagger():
from sympy.physics.secondquant import Dagger
from sympy import I
assert _test_args(Dagger(2*I))
def test_sympy__physics__secondquant__FermionState():
from sympy.physics.secondquant import FermionState
assert _test_args(FermionState((0, 1)))
def test_sympy__physics__secondquant__FermionicOperator():
from sympy.physics.secondquant import FermionicOperator
assert _test_args(FermionicOperator(0))
def test_sympy__physics__secondquant__FockState():
from sympy.physics.secondquant import FockState
assert _test_args(FockState((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonBra():
from sympy.physics.secondquant import FockStateBosonBra
assert _test_args(FockStateBosonBra((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonKet():
from sympy.physics.secondquant import FockStateBosonKet
assert _test_args(FockStateBosonKet((0, 1)))
def test_sympy__physics__secondquant__FockStateBra():
from sympy.physics.secondquant import FockStateBra
assert _test_args(FockStateBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionBra():
from sympy.physics.secondquant import FockStateFermionBra
assert _test_args(FockStateFermionBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionKet():
from sympy.physics.secondquant import FockStateFermionKet
assert _test_args(FockStateFermionKet((0, 1)))
def test_sympy__physics__secondquant__FockStateKet():
from sympy.physics.secondquant import FockStateKet
assert _test_args(FockStateKet((0, 1)))
def test_sympy__physics__secondquant__InnerProduct():
from sympy.physics.secondquant import InnerProduct
from sympy.physics.secondquant import FockStateKet, FockStateBra
assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1))))
def test_sympy__physics__secondquant__NO():
from sympy.physics.secondquant import NO, F, Fd
assert _test_args(NO(Fd(x)*F(y)))
def test_sympy__physics__secondquant__PermutationOperator():
from sympy.physics.secondquant import PermutationOperator
assert _test_args(PermutationOperator(0, 1))
def test_sympy__physics__secondquant__SqOperator():
from sympy.physics.secondquant import SqOperator
assert _test_args(SqOperator(0))
def test_sympy__physics__secondquant__TensorSymbol():
from sympy.physics.secondquant import TensorSymbol
assert _test_args(TensorSymbol(x))
def test_sympy__physics__control__lti__TransferFunction():
from sympy.physics.control.lti import TransferFunction
assert _test_args(TransferFunction(2, 3, x))
def test_sympy__physics__control__lti__Series():
from sympy.physics.control import Series, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Series(tf1, tf2))
def test_sympy__physics__control__lti__Parallel():
from sympy.physics.control import Parallel, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Parallel(tf1, tf2))
def test_sympy__physics__control__lti__Feedback():
from sympy.physics.control import TransferFunction, Feedback
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Feedback(tf1, tf2))
def test_sympy__physics__units__dimensions__Dimension():
from sympy.physics.units.dimensions import Dimension
assert _test_args(Dimension("length", "L"))
def test_sympy__physics__units__dimensions__DimensionSystem():
from sympy.physics.units.dimensions import DimensionSystem
from sympy.physics.units.definitions.dimension_definitions import length, time, velocity
assert _test_args(DimensionSystem((length, time), (velocity,)))
def test_sympy__physics__units__quantities__Quantity():
from sympy.physics.units.quantities import Quantity
assert _test_args(Quantity("dam"))
def test_sympy__physics__units__prefixes__Prefix():
from sympy.physics.units.prefixes import Prefix
assert _test_args(Prefix('kilo', 'k', 3))
def test_sympy__core__numbers__AlgebraicNumber():
from sympy.core.numbers import AlgebraicNumber
assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3]))
def test_sympy__polys__polytools__GroebnerBasis():
from sympy.polys.polytools import GroebnerBasis
assert _test_args(GroebnerBasis([x, y, z], x, y, z))
def test_sympy__polys__polytools__Poly():
from sympy.polys.polytools import Poly
assert _test_args(Poly(2, x, y))
def test_sympy__polys__polytools__PurePoly():
from sympy.polys.polytools import PurePoly
assert _test_args(PurePoly(2, x, y))
@SKIP('abstract class')
def test_sympy__polys__rootoftools__RootOf():
pass
def test_sympy__polys__rootoftools__ComplexRootOf():
from sympy.polys.rootoftools import ComplexRootOf
assert _test_args(ComplexRootOf(x**3 + x + 1, 0))
def test_sympy__polys__rootoftools__RootSum():
from sympy.polys.rootoftools import RootSum
assert _test_args(RootSum(x**3 + x + 1, sin))
def test_sympy__series__limits__Limit():
from sympy.series.limits import Limit
assert _test_args(Limit(x, x, 0, dir='-'))
def test_sympy__series__order__Order():
from sympy.series.order import Order
assert _test_args(Order(1, x, y))
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqBase():
pass
def test_sympy__series__sequences__EmptySequence():
# Need to imort the instance from series not the class from
# series.sequence
from sympy.series import EmptySequence
assert _test_args(EmptySequence)
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqExpr():
pass
def test_sympy__series__sequences__SeqPer():
from sympy.series.sequences import SeqPer
assert _test_args(SeqPer((1, 2, 3), (0, 10)))
def test_sympy__series__sequences__SeqFormula():
from sympy.series.sequences import SeqFormula
assert _test_args(SeqFormula(x**2, (0, 10)))
def test_sympy__series__sequences__RecursiveSeq():
from sympy.series.sequences import RecursiveSeq
y = Function("y")
n = symbols("n")
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1)))
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n))
def test_sympy__series__sequences__SeqExprOp():
from sympy.series.sequences import SeqExprOp, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqExprOp(s1, s2))
def test_sympy__series__sequences__SeqAdd():
from sympy.series.sequences import SeqAdd, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqAdd(s1, s2))
def test_sympy__series__sequences__SeqMul():
from sympy.series.sequences import SeqMul, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqMul(s1, s2))
@SKIP('Abstract Class')
def test_sympy__series__series_class__SeriesBase():
pass
def test_sympy__series__fourier__FourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(x, (x, -pi, pi)))
def test_sympy__series__fourier__FiniteFourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(sin(pi*x), (x, -1, 1)))
def test_sympy__series__formal__FormalPowerSeries():
from sympy.series.formal import fps
assert _test_args(fps(log(1 + x), x))
def test_sympy__series__formal__Coeff():
from sympy.series.formal import fps
assert _test_args(fps(x**2 + x + 1, x))
@SKIP('Abstract Class')
def test_sympy__series__formal__FiniteFormalPowerSeries():
pass
def test_sympy__series__formal__FormalPowerSeriesProduct():
from sympy.series.formal import fps
f1, f2 = fps(sin(x)), fps(exp(x))
assert _test_args(f1.product(f2, x))
def test_sympy__series__formal__FormalPowerSeriesCompose():
from sympy.series.formal import fps
f1, f2 = fps(exp(x)), fps(sin(x))
assert _test_args(f1.compose(f2, x))
def test_sympy__series__formal__FormalPowerSeriesInverse():
from sympy.series.formal import fps
f1 = fps(exp(x))
assert _test_args(f1.inverse(x))
def test_sympy__simplify__hyperexpand__Hyper_Function():
from sympy.simplify.hyperexpand import Hyper_Function
assert _test_args(Hyper_Function([2], [1]))
def test_sympy__simplify__hyperexpand__G_Function():
from sympy.simplify.hyperexpand import G_Function
assert _test_args(G_Function([2], [1], [], []))
@SKIP("abstract class")
def test_sympy__tensor__array__ndim_array__ImmutableNDimArray():
pass
def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray():
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(densarr)
def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray():
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(sparr)
def test_sympy__tensor__array__array_comprehension__ArrayComprehension():
from sympy.tensor.array.array_comprehension import ArrayComprehension
arrcom = ArrayComprehension(x, (x, 1, 5))
assert _test_args(arrcom)
def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap():
from sympy.tensor.array.array_comprehension import ArrayComprehensionMap
arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5))
assert _test_args(arrcomma)
def test_sympy__tensor__array__arrayop__Flatten():
from sympy.tensor.array.arrayop import Flatten
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
fla = Flatten(ImmutableDenseNDimArray(range(24)).reshape(2, 3, 4))
assert _test_args(fla)
def test_sympy__tensor__array__array_derivatives__ArrayDerivative():
from sympy.tensor.array.array_derivatives import ArrayDerivative
A = MatrixSymbol("A", 2, 2)
arrder = ArrayDerivative(A, A, evaluate=False)
assert _test_args(arrder)
def test_sympy__tensor__functions__TensorProduct():
from sympy.tensor.functions import TensorProduct
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
tp = TensorProduct(A, B)
assert _test_args(tp)
def test_sympy__tensor__indexed__Idx():
from sympy.tensor.indexed import Idx
assert _test_args(Idx('test'))
assert _test_args(Idx(1, (0, 10)))
def test_sympy__tensor__indexed__Indexed():
from sympy.tensor.indexed import Indexed, Idx
assert _test_args(Indexed('A', Idx('i'), Idx('j')))
def test_sympy__tensor__indexed__IndexedBase():
from sympy.tensor.indexed import IndexedBase
assert _test_args(IndexedBase('A', shape=(x, y)))
assert _test_args(IndexedBase('A', 1))
assert _test_args(IndexedBase('A')[0, 1])
def test_sympy__tensor__tensor__TensorIndexType():
from sympy.tensor.tensor import TensorIndexType
assert _test_args(TensorIndexType('Lorentz'))
@SKIP("deprecated class")
def test_sympy__tensor__tensor__TensorType():
pass
def test_sympy__tensor__tensor__TensorSymmetry():
from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs
assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2)))
def test_sympy__tensor__tensor__TensorHead():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
sym = TensorSymmetry(get_symmetric_group_sgs(1))
assert _test_args(TensorHead('p', [Lorentz], sym, 0))
def test_sympy__tensor__tensor__TensorIndex():
from sympy.tensor.tensor import TensorIndexType, TensorIndex
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
assert _test_args(TensorIndex('i', Lorentz))
@SKIP("abstract class")
def test_sympy__tensor__tensor__TensExpr():
pass
def test_sympy__tensor__tensor__TensAdd():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p,q', [Lorentz], sym)
t1 = p(a)
t2 = q(a)
assert _test_args(TensAdd(t1, t2))
def test_sympy__tensor__tensor__Tensor():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p = TensorHead('p', [Lorentz], sym)
assert _test_args(p(a))
def test_sympy__tensor__tensor__TensMul():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p, q', [Lorentz], sym)
assert _test_args(3*p(a)*q(b))
def test_sympy__tensor__tensor__TensorElement():
from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement
L = TensorIndexType("L")
A = TensorHead("A", [L, L])
telem = TensorElement(A(x, y), {x: 1})
assert _test_args(telem)
def test_sympy__tensor__toperators__PartialDerivative():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
from sympy.tensor.toperators import PartialDerivative
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
A = TensorHead("A", [Lorentz])
assert _test_args(PartialDerivative(A(a), A(b)))
def test_as_coeff_add():
assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add()
def test_sympy__geometry__curve__Curve():
from sympy.geometry.curve import Curve
assert _test_args(Curve((x, 1), (x, 0, 1)))
def test_sympy__geometry__point__Point():
from sympy.geometry.point import Point
assert _test_args(Point(0, 1))
def test_sympy__geometry__point__Point2D():
from sympy.geometry.point import Point2D
assert _test_args(Point2D(0, 1))
def test_sympy__geometry__point__Point3D():
from sympy.geometry.point import Point3D
assert _test_args(Point3D(0, 1, 2))
def test_sympy__geometry__ellipse__Ellipse():
from sympy.geometry.ellipse import Ellipse
assert _test_args(Ellipse((0, 1), 2, 3))
def test_sympy__geometry__ellipse__Circle():
from sympy.geometry.ellipse import Circle
assert _test_args(Circle((0, 1), 2))
def test_sympy__geometry__parabola__Parabola():
from sympy.geometry.parabola import Parabola
from sympy.geometry.line import Line
assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3))))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity():
pass
def test_sympy__geometry__line__Line():
from sympy.geometry.line import Line
assert _test_args(Line((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray():
from sympy.geometry.line import Ray
assert _test_args(Ray((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment():
from sympy.geometry.line import Segment
assert _test_args(Segment((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity2D():
pass
def test_sympy__geometry__line__Line2D():
from sympy.geometry.line import Line2D
assert _test_args(Line2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray2D():
from sympy.geometry.line import Ray2D
assert _test_args(Ray2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment2D():
from sympy.geometry.line import Segment2D
assert _test_args(Segment2D((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity3D():
pass
def test_sympy__geometry__line__Line3D():
from sympy.geometry.line import Line3D
assert _test_args(Line3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Segment3D():
from sympy.geometry.line import Segment3D
assert _test_args(Segment3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Ray3D():
from sympy.geometry.line import Ray3D
assert _test_args(Ray3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__plane__Plane():
from sympy.geometry.plane import Plane
assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3)))
def test_sympy__geometry__polygon__Polygon():
from sympy.geometry.polygon import Polygon
assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7)))
def test_sympy__geometry__polygon__RegularPolygon():
from sympy.geometry.polygon import RegularPolygon
assert _test_args(RegularPolygon((0, 1), 2, 3, 4))
def test_sympy__geometry__polygon__Triangle():
from sympy.geometry.polygon import Triangle
assert _test_args(Triangle((0, 1), (2, 3), (4, 5)))
def test_sympy__geometry__entity__GeometryEntity():
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2]))
@SKIP("abstract class")
def test_sympy__geometry__entity__GeometrySet():
pass
def test_sympy__diffgeom__diffgeom__Manifold():
from sympy.diffgeom import Manifold
assert _test_args(Manifold('name', 3))
def test_sympy__diffgeom__diffgeom__Patch():
from sympy.diffgeom import Manifold, Patch
assert _test_args(Patch('name', Manifold('name', 3)))
def test_sympy__diffgeom__diffgeom__CoordSystem():
from sympy.diffgeom import Manifold, Patch, CoordSystem
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3))))
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]))
def test_sympy__diffgeom__diffgeom__CoordinateSymbol():
from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol
assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0))
def test_sympy__diffgeom__diffgeom__Point():
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
assert _test_args(Point(
CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y]))
def test_sympy__diffgeom__diffgeom__BaseScalarField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseScalarField(cs, 0))
def test_sympy__diffgeom__diffgeom__BaseVectorField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseVectorField(cs, 0))
def test_sympy__diffgeom__diffgeom__Differential():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(Differential(BaseScalarField(cs, 0)))
def test_sympy__diffgeom__diffgeom__Commutator():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
v1 = BaseVectorField(cs1, 0)
assert _test_args(Commutator(v, v1))
def test_sympy__diffgeom__diffgeom__TensorProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
assert _test_args(TensorProduct(d, d))
def test_sympy__diffgeom__diffgeom__WedgeProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
d1 = Differential(BaseScalarField(cs, 1))
assert _test_args(WedgeProduct(d, d1))
def test_sympy__diffgeom__diffgeom__LieDerivative():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
v = BaseVectorField(cs, 0)
assert _test_args(LieDerivative(v, d))
@XFAIL
def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3))
def test_sympy__diffgeom__diffgeom__CovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
_test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3))
def test_sympy__categories__baseclasses__Class():
from sympy.categories.baseclasses import Class
assert _test_args(Class())
def test_sympy__categories__baseclasses__Object():
from sympy.categories import Object
assert _test_args(Object("A"))
@XFAIL
def test_sympy__categories__baseclasses__Morphism():
from sympy.categories import Object, Morphism
assert _test_args(Morphism(Object("A"), Object("B")))
def test_sympy__categories__baseclasses__IdentityMorphism():
from sympy.categories import Object, IdentityMorphism
assert _test_args(IdentityMorphism(Object("A")))
def test_sympy__categories__baseclasses__NamedMorphism():
from sympy.categories import Object, NamedMorphism
assert _test_args(NamedMorphism(Object("A"), Object("B"), "f"))
def test_sympy__categories__baseclasses__CompositeMorphism():
from sympy.categories import Object, NamedMorphism, CompositeMorphism
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
assert _test_args(CompositeMorphism(f, g))
def test_sympy__categories__baseclasses__Diagram():
from sympy.categories import Object, NamedMorphism, Diagram
A = Object("A")
B = Object("B")
f = NamedMorphism(A, B, "f")
d = Diagram([f])
assert _test_args(d)
def test_sympy__categories__baseclasses__Category():
from sympy.categories import Object, NamedMorphism, Diagram, Category
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d1 = Diagram([f, g])
d2 = Diagram([f])
K = Category("K", commutative_diagrams=[d1, d2])
assert _test_args(K)
def test_sympy__ntheory__factor___totient():
from sympy.ntheory.factor_ import totient
k = symbols('k', integer=True)
t = totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___reduced_totient():
from sympy.ntheory.factor_ import reduced_totient
k = symbols('k', integer=True)
t = reduced_totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___divisor_sigma():
from sympy.ntheory.factor_ import divisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = divisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___udivisor_sigma():
from sympy.ntheory.factor_ import udivisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = udivisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___primenu():
from sympy.ntheory.factor_ import primenu
n = symbols('n', integer=True)
t = primenu(n)
assert _test_args(t)
def test_sympy__ntheory__factor___primeomega():
from sympy.ntheory.factor_ import primeomega
n = symbols('n', integer=True)
t = primeomega(n)
assert _test_args(t)
def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
def test_sympy__ntheory__generate__primepi():
from sympy.ntheory import primepi
n = symbols('n')
t = primepi(n)
assert _test_args(t)
def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
def test_sympy__physics__optics__gaussopt__BeamParameter():
from sympy.physics.optics import BeamParameter
assert _test_args(BeamParameter(530e-9, 1, w=1e-3))
def test_sympy__physics__optics__medium__Medium():
from sympy.physics.optics import Medium
assert _test_args(Medium('m'))
def test_sympy__codegen__array_utils__CodegenArrayContraction():
from sympy.codegen.array_utils import CodegenArrayContraction
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayContraction(A, (0, 1)))
def test_sympy__codegen__array_utils__CodegenArrayDiagonal():
from sympy.codegen.array_utils import CodegenArrayDiagonal
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayDiagonal(A, (0, 1)))
def test_sympy__codegen__array_utils__CodegenArrayTensorProduct():
from sympy.codegen.array_utils import CodegenArrayTensorProduct
from sympy import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(CodegenArrayTensorProduct(A, B))
def test_sympy__codegen__array_utils__CodegenArrayElementwiseAdd():
from sympy.codegen.array_utils import CodegenArrayElementwiseAdd
from sympy import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(CodegenArrayElementwiseAdd(A, B))
def test_sympy__codegen__array_utils__CodegenArrayPermuteDims():
from sympy.codegen.array_utils import CodegenArrayPermuteDims
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayPermuteDims(A, (1, 0)))
def test_sympy__codegen__ast__Assignment():
from sympy.codegen.ast import Assignment
assert _test_args(Assignment(x, y))
def test_sympy__codegen__cfunctions__expm1():
from sympy.codegen.cfunctions import expm1
assert _test_args(expm1(x))
def test_sympy__codegen__cfunctions__log1p():
from sympy.codegen.cfunctions import log1p
assert _test_args(log1p(x))
def test_sympy__codegen__cfunctions__exp2():
from sympy.codegen.cfunctions import exp2
assert _test_args(exp2(x))
def test_sympy__codegen__cfunctions__log2():
from sympy.codegen.cfunctions import log2
assert _test_args(log2(x))
def test_sympy__codegen__cfunctions__fma():
from sympy.codegen.cfunctions import fma
assert _test_args(fma(x, y, z))
def test_sympy__codegen__cfunctions__log10():
from sympy.codegen.cfunctions import log10
assert _test_args(log10(x))
def test_sympy__codegen__cfunctions__Sqrt():
from sympy.codegen.cfunctions import Sqrt
assert _test_args(Sqrt(x))
def test_sympy__codegen__cfunctions__Cbrt():
from sympy.codegen.cfunctions import Cbrt
assert _test_args(Cbrt(x))
def test_sympy__codegen__cfunctions__hypot():
from sympy.codegen.cfunctions import hypot
assert _test_args(hypot(x, y))
def test_sympy__codegen__fnodes__FFunction():
from sympy.codegen.fnodes import FFunction
assert _test_args(FFunction('f'))
def test_sympy__codegen__fnodes__F95Function():
from sympy.codegen.fnodes import F95Function
assert _test_args(F95Function('f'))
def test_sympy__codegen__fnodes__isign():
from sympy.codegen.fnodes import isign
assert _test_args(isign(1, x))
def test_sympy__codegen__fnodes__dsign():
from sympy.codegen.fnodes import dsign
assert _test_args(dsign(1, x))
def test_sympy__codegen__fnodes__cmplx():
from sympy.codegen.fnodes import cmplx
assert _test_args(cmplx(x, y))
def test_sympy__codegen__fnodes__kind():
from sympy.codegen.fnodes import kind
assert _test_args(kind(x))
def test_sympy__codegen__fnodes__merge():
from sympy.codegen.fnodes import merge
assert _test_args(merge(1, 2, Eq(x, 0)))
def test_sympy__codegen__fnodes___literal():
from sympy.codegen.fnodes import _literal
assert _test_args(_literal(1))
def test_sympy__codegen__fnodes__literal_sp():
from sympy.codegen.fnodes import literal_sp
assert _test_args(literal_sp(1))
def test_sympy__codegen__fnodes__literal_dp():
from sympy.codegen.fnodes import literal_dp
assert _test_args(literal_dp(1))
def test_sympy__codegen__matrix_nodes__MatrixSolve():
from sympy.matrices import MatrixSymbol
from sympy.codegen.matrix_nodes import MatrixSolve
A = MatrixSymbol('A', 3, 3)
v = MatrixSymbol('x', 3, 1)
assert _test_args(MatrixSolve(A, v))
def test_sympy__vector__coordsysrect__CoordSys3D():
from sympy.vector.coordsysrect import CoordSys3D
assert _test_args(CoordSys3D('C'))
def test_sympy__vector__point__Point():
from sympy.vector.point import Point
assert _test_args(Point('P'))
def test_sympy__vector__basisdependent__BasisDependent():
#from sympy.vector.basisdependent import BasisDependent
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentMul():
#from sympy.vector.basisdependent import BasisDependentMul
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentAdd():
#from sympy.vector.basisdependent import BasisDependentAdd
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentZero():
#from sympy.vector.basisdependent import BasisDependentZero
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__vector__BaseVector():
from sympy.vector.vector import BaseVector
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseVector(0, C, ' ', ' '))
def test_sympy__vector__vector__VectorAdd():
from sympy.vector.vector import VectorAdd, VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a, b, c, x, y, z
v1 = a*C.i + b*C.j + c*C.k
v2 = x*C.i + y*C.j + z*C.k
assert _test_args(VectorAdd(v1, v2))
assert _test_args(VectorMul(x, v1))
def test_sympy__vector__vector__VectorMul():
from sympy.vector.vector import VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a
assert _test_args(VectorMul(a, C.i))
def test_sympy__vector__vector__VectorZero():
from sympy.vector.vector import VectorZero
assert _test_args(VectorZero())
def test_sympy__vector__vector__Vector():
#from sympy.vector.vector import Vector
#Vector is never to be initialized using args
pass
def test_sympy__vector__vector__Cross():
from sympy.vector.vector import Cross
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Cross(C.i, C.j))
def test_sympy__vector__vector__Dot():
from sympy.vector.vector import Dot
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Dot(C.i, C.j))
def test_sympy__vector__dyadic__Dyadic():
#from sympy.vector.dyadic import Dyadic
#Dyadic is never to be initialized using args
pass
def test_sympy__vector__dyadic__BaseDyadic():
from sympy.vector.dyadic import BaseDyadic
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseDyadic(C.i, C.j))
def test_sympy__vector__dyadic__DyadicMul():
from sympy.vector.dyadic import BaseDyadic, DyadicMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicAdd():
from sympy.vector.dyadic import BaseDyadic, DyadicAdd
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i),
BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicZero():
from sympy.vector.dyadic import DyadicZero
assert _test_args(DyadicZero())
def test_sympy__vector__deloperator__Del():
from sympy.vector.deloperator import Del
assert _test_args(Del())
def test_sympy__vector__implicitregion__ImplicitRegion():
from sympy.vector.implicitregion import ImplicitRegion
from sympy.abc import x, y
assert _test_args(ImplicitRegion((x, y), y**3 - 4*x))
def test_sympy__vector__integrals__ParametricIntegral():
from sympy.vector.integrals import ParametricIntegral
from sympy.vector.parametricregion import ParametricRegion
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\
ParametricRegion((x, y), (x, 1, 3), (y, -2, 2))))
def test_sympy__vector__operators__Curl():
from sympy.vector.operators import Curl
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Curl(C.i))
def test_sympy__vector__operators__Laplacian():
from sympy.vector.operators import Laplacian
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Laplacian(C.i))
def test_sympy__vector__operators__Divergence():
from sympy.vector.operators import Divergence
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Divergence(C.i))
def test_sympy__vector__operators__Gradient():
from sympy.vector.operators import Gradient
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Gradient(C.x))
def test_sympy__vector__orienters__Orienter():
#from sympy.vector.orienters import Orienter
#Not to be initialized
pass
def test_sympy__vector__orienters__ThreeAngleOrienter():
#from sympy.vector.orienters import ThreeAngleOrienter
#Not to be initialized
pass
def test_sympy__vector__orienters__AxisOrienter():
from sympy.vector.orienters import AxisOrienter
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(AxisOrienter(x, C.i))
def test_sympy__vector__orienters__BodyOrienter():
from sympy.vector.orienters import BodyOrienter
assert _test_args(BodyOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__SpaceOrienter():
from sympy.vector.orienters import SpaceOrienter
assert _test_args(SpaceOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__QuaternionOrienter():
from sympy.vector.orienters import QuaternionOrienter
a, b, c, d = symbols('a b c d')
assert _test_args(QuaternionOrienter(a, b, c, d))
def test_sympy__vector__parametricregion__ParametricRegion():
from sympy.abc import t
from sympy.vector.parametricregion import ParametricRegion
assert _test_args(ParametricRegion((t, t**3), (t, 0, 2)))
def test_sympy__vector__scalar__BaseScalar():
from sympy.vector.scalar import BaseScalar
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseScalar(0, C, ' ', ' '))
def test_sympy__physics__wigner__Wigner3j():
from sympy.physics.wigner import Wigner3j
assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0))
def test_sympy__integrals__rubi__symbol__matchpyWC():
from sympy.integrals.rubi.symbol import matchpyWC
assert _test_args(matchpyWC(1, True, 'a'))
def test_sympy__integrals__rubi__utility_function__rubi_unevaluated_expr():
from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr
a = symbols('a')
assert _test_args(rubi_unevaluated_expr(a))
def test_sympy__integrals__rubi__utility_function__rubi_exp():
from sympy.integrals.rubi.utility_function import rubi_exp
assert _test_args(rubi_exp(5))
def test_sympy__integrals__rubi__utility_function__rubi_log():
from sympy.integrals.rubi.utility_function import rubi_log
assert _test_args(rubi_log(5))
def test_sympy__integrals__rubi__utility_function__Int():
from sympy.integrals.rubi.utility_function import Int
assert _test_args(Int(5, x))
def test_sympy__integrals__rubi__utility_function__Util_Coefficient():
from sympy.integrals.rubi.utility_function import Util_Coefficient
a, x = symbols('a x')
assert _test_args(Util_Coefficient(a, x))
def test_sympy__integrals__rubi__utility_function__Gamma():
from sympy.integrals.rubi.utility_function import Gamma
assert _test_args(Gamma(5))
def test_sympy__integrals__rubi__utility_function__Util_Part():
from sympy.integrals.rubi.utility_function import Util_Part
a, b = symbols('a b')
assert _test_args(Util_Part(a + b, 0))
def test_sympy__integrals__rubi__utility_function__PolyGamma():
from sympy.integrals.rubi.utility_function import PolyGamma
assert _test_args(PolyGamma(1, 1))
def test_sympy__integrals__rubi__utility_function__ProductLog():
from sympy.integrals.rubi.utility_function import ProductLog
assert _test_args(ProductLog(1))
def test_sympy__combinatorics__schur_number__SchurNumber():
from sympy.combinatorics.schur_number import SchurNumber
assert _test_args(SchurNumber(1))
def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup():
from sympy.combinatorics.perm_groups import SymmetricPermutationGroup
assert _test_args(SymmetricPermutationGroup(5))
def test_sympy__combinatorics__perm_groups__Coset():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup, Coset
a = Permutation(1, 2)
b = Permutation(0, 1)
G = PermutationGroup([a, b])
assert _test_args(Coset(a, G))
|
11c16cce29e09325101b982ef5d7e12dec98ed8ab8dfde529261ced31b649de7 | from sympy.core.basic import Basic
from sympy.core.numbers import Rational
from sympy.core.singleton import S, Singleton
def test_Singleton():
global instantiated
instantiated = 0
class MySingleton(Basic, metaclass=Singleton):
def __new__(cls):
global instantiated
instantiated += 1
return Basic.__new__(cls)
assert instantiated == 0
MySingleton() # force instantiation
assert instantiated == 1
assert MySingleton() is not Basic()
assert MySingleton() is MySingleton()
assert S.MySingleton is MySingleton()
assert instantiated == 1
class MySingleton_sub(MySingleton):
pass
assert instantiated == 1
MySingleton_sub()
assert instantiated == 2
assert MySingleton_sub() is not MySingleton()
assert MySingleton_sub() is MySingleton_sub()
def test_singleton_redefinition():
class TestSingleton(Basic, metaclass=Singleton):
pass
assert TestSingleton() is S.TestSingleton
class TestSingleton(Basic, metaclass=Singleton):
pass
assert TestSingleton() is S.TestSingleton
def test_names_in_namespace():
# Every singleton name should be accessible from the 'from sympy import *'
# namespace in addition to the S object. However, it does not need to be
# by the same name (e.g., oo instead of S.Infinity).
# As a general rule, things should only be added to the singleton registry
# if they are used often enough that code can benefit either from the
# performance benefit of being able to use 'is' (this only matters in very
# tight loops), or from the memory savings of having exactly one instance
# (this matters for the numbers singletons, but very little else). The
# singleton registry is already a bit overpopulated, and things cannot be
# removed from it without breaking backwards compatibility. So if you got
# here by adding something new to the singletons, ask yourself if it
# really needs to be singletonized. Note that SymPy classes compare to one
# another just fine, so Class() == Class() will give True even if each
# Class() returns a new instance. Having unique instances is only
# necessary for the above noted performance gains. It should not be needed
# for any behavioral purposes.
# If you determine that something really should be a singleton, it must be
# accessible to sympify() without using 'S' (hence this test). Also, its
# str printer should print a form that does not use S. This is because
# sympify() disables attribute lookups by default for safety purposes.
d = {}
exec('from sympy import *', d)
for name in dir(S) + list(S._classes_to_install):
if name.startswith('_'):
continue
if name == 'register':
continue
if isinstance(getattr(S, name), Rational):
continue
if getattr(S, name).__module__.startswith('sympy.physics'):
continue
if name in ['MySingleton', 'MySingleton_sub', 'TestSingleton']:
# From the tests above
continue
if name == 'NegativeInfinity':
# Accessible by -oo
continue
# Use is here to ensure it is the exact same object
assert any(getattr(S, name) is i for i in d.values()), name
|
3a83348a4fcd5318a2038c8bfbb1c6c64cfbceda4b2d5ae2f9a82586b9822f5a | """This tests sympy/core/basic.py with (ideally) no reference to subclasses
of Basic or Atom."""
import collections
from sympy.core.basic import (Basic, Atom, preorder_traversal, as_Basic,
_atomic, _aresame)
from sympy.core.singleton import S
from sympy.core.symbol import symbols, Symbol, Dummy
from sympy.core.sympify import SympifyError
from sympy.core.function import Function, Lambda
from sympy.core.compatibility import default_sort_key
from sympy import sin, Q, cos, gamma, Tuple, Integral, Sum
from sympy.functions.elementary.exponential import exp
from sympy.testing.pytest import raises
from sympy.core import I, pi
b1 = Basic()
b2 = Basic(b1)
b3 = Basic(b2)
b21 = Basic(b2, b1)
def test__aresame():
assert not _aresame(Basic([]), Basic())
assert not _aresame(Basic([]), Basic(()))
assert not _aresame(Basic(2), Basic(2.))
def test_structure():
assert b21.args == (b2, b1)
assert b21.func(*b21.args) == b21
assert bool(b1)
def test_immutable():
assert not hasattr(b1, '__dict__')
with raises(AttributeError):
b1.x = 1
def test_equality():
instances = [b1, b2, b3, b21, Basic(b1, b1, b1), Basic]
for i, b_i in enumerate(instances):
for j, b_j in enumerate(instances):
assert (b_i == b_j) == (i == j)
assert (b_i != b_j) == (i != j)
assert Basic() != []
assert not(Basic() == [])
assert Basic() != 0
assert not(Basic() == 0)
class Foo:
"""
Class that is unaware of Basic, and relies on both classes returning
the NotImplemented singleton for equivalence to evaluate to False.
"""
b = Basic()
foo = Foo()
assert b != foo
assert foo != b
assert not b == foo
assert not foo == b
class Bar:
"""
Class that considers itself equal to any instance of Basic, and relies
on Basic returning the NotImplemented singleton in order to achieve
a symmetric equivalence relation.
"""
def __eq__(self, other):
if isinstance(other, Basic):
return True
return NotImplemented
def __ne__(self, other):
return not self == other
bar = Bar()
assert b == bar
assert bar == b
assert not b != bar
assert not bar != b
def test_matches_basic():
instances = [Basic(b1, b1, b2), Basic(b1, b2, b1), Basic(b2, b1, b1),
Basic(b1, b2), Basic(b2, b1), b2, b1]
for i, b_i in enumerate(instances):
for j, b_j in enumerate(instances):
if i == j:
assert b_i.matches(b_j) == {}
else:
assert b_i.matches(b_j) is None
assert b1.match(b1) == {}
def test_has():
assert b21.has(b1)
assert b21.has(b3, b1)
assert b21.has(Basic)
assert not b1.has(b21, b3)
assert not b21.has()
raises(SympifyError, lambda: Symbol("x").has("x"))
def test_subs():
assert b21.subs(b2, b1) == Basic(b1, b1)
assert b21.subs(b2, b21) == Basic(b21, b1)
assert b3.subs(b2, b1) == b2
assert b21.subs([(b2, b1), (b1, b2)]) == Basic(b2, b2)
assert b21.subs({b1: b2, b2: b1}) == Basic(b2, b2)
assert b21.subs(collections.ChainMap({b1: b2}, {b2: b1})) == Basic(b2, b2)
assert b21.subs(collections.OrderedDict([(b2, b1), (b1, b2)])) == Basic(b2, b2)
raises(ValueError, lambda: b21.subs('bad arg'))
raises(ValueError, lambda: b21.subs(b1, b2, b3))
# dict(b1=foo) creates a string 'b1' but leaves foo unchanged; subs
# will convert the first to a symbol but will raise an error if foo
# cannot be sympified; sympification is strict if foo is not string
raises(ValueError, lambda: b21.subs(b1='bad arg'))
assert Symbol("text").subs({"text": b1}) == b1
assert Symbol("s").subs({"s": 1}) == 1
def test_subs_with_unicode_symbols():
expr = Symbol('var1')
replaced = expr.subs('var1', 'x')
assert replaced.name == 'x'
replaced = expr.subs('var1', 'x')
assert replaced.name == 'x'
def test_atoms():
assert b21.atoms() == {Basic()}
def test_free_symbols_empty():
assert b21.free_symbols == set()
def test_doit():
assert b21.doit() == b21
assert b21.doit(deep=False) == b21
def test_S():
assert repr(S) == 'S'
def test_xreplace():
assert b21.xreplace({b2: b1}) == Basic(b1, b1)
assert b21.xreplace({b2: b21}) == Basic(b21, b1)
assert b3.xreplace({b2: b1}) == b2
assert Basic(b1, b2).xreplace({b1: b2, b2: b1}) == Basic(b2, b1)
assert Atom(b1).xreplace({b1: b2}) == Atom(b1)
assert Atom(b1).xreplace({Atom(b1): b2}) == b2
raises(TypeError, lambda: b1.xreplace())
raises(TypeError, lambda: b1.xreplace([b1, b2]))
for f in (exp, Function('f')):
assert f.xreplace({}) == f
assert f.xreplace({}, hack2=True) == f
assert f.xreplace({f: b1}) == b1
assert f.xreplace({f: b1}, hack2=True) == b1
def test_preorder_traversal():
expr = Basic(b21, b3)
assert list(
preorder_traversal(expr)) == [expr, b21, b2, b1, b1, b3, b2, b1]
assert list(preorder_traversal(('abc', ('d', 'ef')))) == [
('abc', ('d', 'ef')), 'abc', ('d', 'ef'), 'd', 'ef']
result = []
pt = preorder_traversal(expr)
for i in pt:
result.append(i)
if i == b2:
pt.skip()
assert result == [expr, b21, b2, b1, b3, b2]
w, x, y, z = symbols('w:z')
expr = z + w*(x + y)
assert list(preorder_traversal([expr], keys=default_sort_key)) == \
[[w*(x + y) + z], w*(x + y) + z, z, w*(x + y), w, x + y, x, y]
assert list(preorder_traversal((x + y)*z, keys=True)) == \
[z*(x + y), z, x + y, x, y]
def test_sorted_args():
x = symbols('x')
assert b21._sorted_args == b21.args
raises(AttributeError, lambda: x._sorted_args)
def test_call():
x, y = symbols('x y')
# See the long history of this in issues 5026 and 5105.
raises(TypeError, lambda: sin(x)({ x : 1, sin(x) : 2}))
raises(TypeError, lambda: sin(x)(1))
# No effect as there are no callables
assert sin(x).rcall(1) == sin(x)
assert (1 + sin(x)).rcall(1) == 1 + sin(x)
# Effect in the pressence of callables
l = Lambda(x, 2*x)
assert (l + x).rcall(y) == 2*y + x
assert (x**l).rcall(2) == x**4
# TODO UndefinedFunction does not subclass Expr
#f = Function('f')
#assert (2*f)(x) == 2*f(x)
assert (Q.real & Q.positive).rcall(x) == Q.real(x) & Q.positive(x)
def test_rewrite():
x, y, z = symbols('x y z')
a, b = symbols('a b')
f1 = sin(x) + cos(x)
assert f1.rewrite(cos,exp) == exp(I*x)/2 + sin(x) + exp(-I*x)/2
assert f1.rewrite([cos],sin) == sin(x) + sin(x + pi/2, evaluate=False)
f2 = sin(x) + cos(y)/gamma(z)
assert f2.rewrite(sin,exp) == -I*(exp(I*x) - exp(-I*x))/2 + cos(y)/gamma(z)
assert f1.rewrite() == f1
def test_literal_evalf_is_number_is_zero_is_comparable():
from sympy.integrals.integrals import Integral
from sympy.core.symbol import symbols
from sympy.core.function import Function
from sympy.functions.elementary.trigonometric import cos, sin
x = symbols('x')
f = Function('f')
# issue 5033
assert f.is_number is False
# issue 6646
assert f(1).is_number is False
i = Integral(0, (x, x, x))
# expressions that are symbolically 0 can be difficult to prove
# so in case there is some easy way to know if something is 0
# it should appear in the is_zero property for that object;
# if is_zero is true evalf should always be able to compute that
# zero
assert i.n() == 0
assert i.is_zero
assert i.is_number is False
assert i.evalf(2, strict=False) == 0
# issue 10268
n = sin(1)**2 + cos(1)**2 - 1
assert n.is_comparable is False
assert n.n(2).is_comparable is False
assert n.n(2).n(2).is_comparable
def test_as_Basic():
assert as_Basic(1) is S.One
assert as_Basic(()) == Tuple()
raises(TypeError, lambda: as_Basic([]))
def test_atomic():
g, h = map(Function, 'gh')
x = symbols('x')
assert _atomic(g(x + h(x))) == {g(x + h(x))}
assert _atomic(g(x + h(x)), recursive=True) == {h(x), x, g(x + h(x))}
assert _atomic(1) == set()
assert _atomic(Basic(1,2)) == {Basic(1, 2)}
def test_as_dummy():
u, v, x, y, z, _0, _1 = symbols('u v x y z _0 _1')
assert Lambda(x, x + 1).as_dummy() == Lambda(_0, _0 + 1)
assert Lambda(x, x + _0).as_dummy() == Lambda(_1, _0 + _1)
eq = (1 + Sum(x, (x, 1, x)))
ans = 1 + Sum(_0, (_0, 1, x))
once = eq.as_dummy()
assert once == ans
twice = once.as_dummy()
assert twice == ans
assert Integral(x + _0, (x, x + 1), (_0, 1, 2)
).as_dummy() == Integral(_0 + _1, (_0, x + 1), (_1, 1, 2))
for T in (Symbol, Dummy):
d = T('x', real=True)
D = d.as_dummy()
assert D != d and D.func == Dummy and D.is_real is None
assert Dummy().as_dummy().is_commutative
assert Dummy(commutative=False).as_dummy().is_commutative is False
def test_canonical_variables():
x, i0, i1 = symbols('x _:2')
assert Integral(x, (x, x + 1)).canonical_variables == {x: i0}
assert Integral(x, (x, x + 1), (i0, 1, 2)).canonical_variables == {
x: i0, i0: i1}
assert Integral(x, (x, x + i0)).canonical_variables == {x: i1}
def test_replace_exceptions():
from sympy import Wild
x, y = symbols('x y')
e = (x**2 + x*y)
raises(TypeError, lambda: e.replace(sin, 2))
b = Wild('b')
c = Wild('c')
raises(TypeError, lambda: e.replace(b*c, c.is_real))
raises(TypeError, lambda: e.replace(b.is_real, 1))
raises(TypeError, lambda: e.replace(lambda d: d.is_Number, 1))
|
8f020e6ce3585e3c620d062488ebb036342179becfd731b2bf67462a5facdac6 | from sympy import (Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda,
Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval, Add, Mul,
Pow, Or, true, false, Abs, pi, Range, Xor)
from sympy.abc import x, y
from sympy.core.sympify import (sympify, _sympify, SympifyError, kernS,
CantSympify)
from sympy.core.decorators import _sympifyit
from sympy.external import import_module
from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.geometry import Point, Line
from sympy.functions.combinatorial.factorials import factorial, factorial2
from sympy.abc import _clash, _clash1, _clash2
from sympy.core.compatibility import HAS_GMPY
from sympy.sets import FiniteSet, EmptySet
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
import mpmath
from collections import defaultdict, OrderedDict
from mpmath.rational import mpq
numpy = import_module('numpy')
def test_issue_3538():
v = sympify("exp(x)")
assert v == exp(x)
assert type(v) == type(exp(x))
assert str(type(v)) == str(type(exp(x)))
def test_sympify1():
assert sympify("x") == Symbol("x")
assert sympify(" x") == Symbol("x")
assert sympify(" x ") == Symbol("x")
# issue 4877
n1 = S.Half
assert sympify('--.5') == n1
assert sympify('-1/2') == -n1
assert sympify('-+--.5') == -n1
assert sympify('-.[3]') == Rational(-1, 3)
assert sympify('.[3]') == Rational(1, 3)
assert sympify('+.[3]') == Rational(1, 3)
assert sympify('+0.[3]*10**-2') == Rational(1, 300)
assert sympify('.[052631578947368421]') == Rational(1, 19)
assert sympify('.0[526315789473684210]') == Rational(1, 19)
assert sympify('.034[56]') == Rational(1711, 49500)
# options to make reals into rationals
assert sympify('1.22[345]', rational=True) == \
1 + Rational(22, 100) + Rational(345, 99900)
assert sympify('2/2.6', rational=True) == Rational(10, 13)
assert sympify('2.6/2', rational=True) == Rational(13, 10)
assert sympify('2.6e2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e+2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000)
assert sympify('2.1+3/4', rational=True) == \
Rational(21, 10) + Rational(3, 4)
assert sympify('2.234456', rational=True) == Rational(279307, 125000)
assert sympify('2.234456e23', rational=True) == 223445600000000000000000
assert sympify('2.234456e-23', rational=True) == \
Rational(279307, 12500000000000000000000000000)
assert sympify('-2.234456e-23', rational=True) == \
Rational(-279307, 12500000000000000000000000000)
assert sympify('12345678901/17', rational=True) == \
Rational(12345678901, 17)
assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x
# make sure longs in fractions work
assert sympify('222222222222/11111111111') == \
Rational(222222222222, 11111111111)
# ... even if they come from repetend notation
assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967)
# ... or from high precision reals
assert sympify('.1234567890123456', rational=True) == \
Rational(19290123283179, 156250000000000)
def test_sympify_Fraction():
try:
import fractions
except ImportError:
pass
else:
value = sympify(fractions.Fraction(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
def test_sympify_gmpy():
if HAS_GMPY:
if HAS_GMPY == 2:
import gmpy2 as gmpy
elif HAS_GMPY == 1:
import gmpy
value = sympify(gmpy.mpz(1000001))
assert value == Integer(1000001) and type(value) is Integer
value = sympify(gmpy.mpq(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
@conserve_mpmath_dps
def test_sympify_mpmath():
value = sympify(mpmath.mpf(1.0))
assert value == Float(1.0) and type(value) is Float
mpmath.mp.dps = 12
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) == False
mpmath.mp.dps = 6
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) == False
assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I
assert sympify(mpq(1, 2)) == S.Half
def test_sympify2():
class A:
def _sympy_(self):
return Symbol("x")**3
a = A()
assert _sympify(a) == x**3
assert sympify(a) == x**3
assert a == x**3
def test_sympify3():
assert sympify("x**3") == x**3
assert sympify("x^3") == x**3
assert sympify("1/2") == Integer(1)/2
raises(SympifyError, lambda: _sympify('x**3'))
raises(SympifyError, lambda: _sympify('1/2'))
def test_sympify_keywords():
raises(SympifyError, lambda: sympify('if'))
raises(SympifyError, lambda: sympify('for'))
raises(SympifyError, lambda: sympify('while'))
raises(SympifyError, lambda: sympify('lambda'))
def test_sympify_float():
assert sympify("1e-64") != 0
assert sympify("1e-20000") != 0
def test_sympify_bool():
assert sympify(True) is true
assert sympify(False) is false
def test_sympyify_iterables():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(['.3', '.2'], rational=True) == ans
assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
@XFAIL
def test_issue_16772():
# because there is a converter for tuple, the
# args are only sympified without the flags being passed
# along; list, on the other hand, is not converted
# with a converter so its args are traversed later
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
def test_issue_16859():
class no(float, CantSympify):
pass
raises(SympifyError, lambda: sympify(no(1.2)))
def test_sympify4():
class A:
def _sympy_(self):
return Symbol("x")
a = A()
assert _sympify(a)**3 == x**3
assert sympify(a)**3 == x**3
assert a == x
def test_sympify_text():
assert sympify('some') == Symbol('some')
assert sympify('core') == Symbol('core')
assert sympify('True') is True
assert sympify('False') is False
assert sympify('Poly') == Poly
assert sympify('sin') == sin
def test_sympify_function():
assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1)
assert sympify('sin(pi/2)*cos(pi)') == -Integer(1)
def test_sympify_poly():
p = Poly(x**2 + x + 1, x)
assert _sympify(p) is p
assert sympify(p) is p
def test_sympify_factorial():
assert sympify('x!') == factorial(x)
assert sympify('(x+1)!') == factorial(x + 1)
assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2
assert sympify('y*x!') == y*factorial(x)
assert sympify('x!!') == factorial2(x)
assert sympify('(x+1)!!') == factorial2(x + 1)
assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2
assert sympify('y*x!!') == y*factorial2(x)
assert sympify('factorial2(x)!') == factorial(factorial2(x))
raises(SympifyError, lambda: sympify("+!!"))
raises(SympifyError, lambda: sympify(")!!"))
raises(SympifyError, lambda: sympify("!"))
raises(SympifyError, lambda: sympify("(!)"))
raises(SympifyError, lambda: sympify("x!!!"))
def test_sage():
# how to effectivelly test for the _sage_() method without having SAGE
# installed?
assert hasattr(x, "_sage_")
assert hasattr(Integer(3), "_sage_")
assert hasattr(sin(x), "_sage_")
assert hasattr(cos(x), "_sage_")
assert hasattr(x**2, "_sage_")
assert hasattr(x + y, "_sage_")
assert hasattr(exp(x), "_sage_")
assert hasattr(log(x), "_sage_")
def test_issue_3595():
assert sympify("a_") == Symbol("a_")
assert sympify("_a") == Symbol("_a")
def test_lambda():
x = Symbol('x')
assert sympify('lambda: 1') == Lambda((), 1)
assert sympify('lambda x: x') == Lambda(x, x)
assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
assert sympify('lambda x, y: 2*x+y') == Lambda((x, y), 2*x + y)
def test_lambda_raises():
raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error
raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error
raises(SympifyError, lambda: sympify("lambda x = 1: x")) # Keyword argument error
with raises(SympifyError):
_sympify('lambda: 1')
def test_sympify_raises():
raises(SympifyError, lambda: sympify("fx)"))
class A:
def __str__(self):
return 'x'
with warns_deprecated_sympy():
assert sympify(A()) == Symbol('x')
def test__sympify():
x = Symbol('x')
f = Function('f')
# positive _sympify
assert _sympify(x) is x
assert _sympify(1) == Integer(1)
assert _sympify(0.5) == Float("0.5")
assert _sympify(1 + 1j) == 1.0 + I*1.0
# Function f is not Basic and can't sympify to Basic. We allow it to pass
# with sympify but not with _sympify.
# https://github.com/sympy/sympy/issues/20124
assert sympify(f) is f
raises(SympifyError, lambda: _sympify(f))
class A:
def _sympy_(self):
return Integer(5)
a = A()
assert _sympify(a) == Integer(5)
# negative _sympify
raises(SympifyError, lambda: _sympify('1'))
raises(SympifyError, lambda: _sympify([1, 2, 3]))
def test_sympifyit():
x = Symbol('x')
y = Symbol('y')
@_sympifyit('b', NotImplemented)
def add(a, b):
return a + b
assert add(x, 1) == x + 1
assert add(x, 0.5) == x + Float('0.5')
assert add(x, y) == x + y
assert add(x, '1') == NotImplemented
@_sympifyit('b')
def add_raises(a, b):
return a + b
assert add_raises(x, 1) == x + 1
assert add_raises(x, 0.5) == x + Float('0.5')
assert add_raises(x, y) == x + y
raises(SympifyError, lambda: add_raises(x, '1'))
def test_int_float():
class F1_1:
def __float__(self):
return 1.1
class F1_1b:
"""
This class is still a float, even though it also implements __int__().
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
class F1_1c:
"""
This class is still a float, because it implements _sympy_()
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
def _sympy_(self):
return Float(1.1)
class I5:
def __int__(self):
return 5
class I5b:
"""
This class implements both __int__() and __float__(), so it will be
treated as Float in SymPy. One could change this behavior, by using
float(a) == int(a), but deciding that integer-valued floats represent
exact numbers is arbitrary and often not correct, so we do not do it.
If, in the future, we decide to do it anyway, the tests for I5b need to
be changed.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
class I5c:
"""
This class implements both __int__() and __float__(), but also
a _sympy_() method, so it will be Integer.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
def _sympy_(self):
return Integer(5)
i5 = I5()
i5b = I5b()
i5c = I5c()
f1_1 = F1_1()
f1_1b = F1_1b()
f1_1c = F1_1c()
assert sympify(i5) == 5
assert isinstance(sympify(i5), Integer)
assert sympify(i5b) == 5
assert isinstance(sympify(i5b), Float)
assert sympify(i5c) == 5
assert isinstance(sympify(i5c), Integer)
assert abs(sympify(f1_1) - 1.1) < 1e-5
assert abs(sympify(f1_1b) - 1.1) < 1e-5
assert abs(sympify(f1_1c) - 1.1) < 1e-5
assert _sympify(i5) == 5
assert isinstance(_sympify(i5), Integer)
assert _sympify(i5b) == 5
assert isinstance(_sympify(i5b), Float)
assert _sympify(i5c) == 5
assert isinstance(_sympify(i5c), Integer)
assert abs(_sympify(f1_1) - 1.1) < 1e-5
assert abs(_sympify(f1_1b) - 1.1) < 1e-5
assert abs(_sympify(f1_1c) - 1.1) < 1e-5
def test_evaluate_false():
cases = {
'2 + 3': Add(2, 3, evaluate=False),
'2**2 / 3': Mul(Pow(2, 2, evaluate=False), Pow(3, -1, evaluate=False), evaluate=False),
'2 + 3 * 5': Add(2, Mul(3, 5, evaluate=False), evaluate=False),
'2 - 3 * 5': Add(2, Mul(-1, Mul(3, 5,evaluate=False), evaluate=False), evaluate=False),
'1 / 3': Mul(1, Pow(3, -1, evaluate=False), evaluate=False),
'True | False': Or(True, False, evaluate=False),
'1 + 2 + 3 + 5*3 + integrate(x)': Add(1, 2, 3, Mul(5, 3, evaluate=False), x**2/2, evaluate=False),
'2 * 4 * 6 + 8': Add(Mul(2, 4, 6, evaluate=False), 8, evaluate=False),
'2 - 8 / 4': Add(2, Mul(-1, Mul(8, Pow(4, -1, evaluate=False), evaluate=False), evaluate=False), evaluate=False),
'2 - 2**2': Add(2, Mul(-1, Pow(2, 2, evaluate=False), evaluate=False), evaluate=False),
}
for case, result in cases.items():
assert sympify(case, evaluate=False) == result
def test_issue_4133():
a = sympify('Integer(4)')
assert a == Integer(4)
assert a.is_Integer
def test_issue_3982():
a = [3, 2.0]
assert sympify(a) == [Integer(3), Float(2.0)]
assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0))
assert sympify(set(a)) == FiniteSet(Integer(3), Float(2.0))
def test_S_sympify():
assert S(1)/2 == sympify(1)/2
assert (-2)**(S(1)/2) == sqrt(2)*I
def test_issue_4788():
assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0))
def test_issue_4798_None():
assert S(None) is None
def test_issue_3218():
assert sympify("x+\ny") == x + y
def test_issue_4988_builtins():
C = Symbol('C')
vars = {'C': C}
exp1 = sympify('C')
assert exp1 == C # Make sure it did not get mixed up with sympy.C
exp2 = sympify('C', vars)
assert exp2 == C # Make sure it did not get mixed up with sympy.C
def test_geometry():
p = sympify(Point(0, 1))
assert p == Point(0, 1) and isinstance(p, Point)
L = sympify(Line(p, (1, 0)))
assert L == Line((0, 1), (1, 0)) and isinstance(L, Line)
def test_kernS():
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'
# when 1497 is fixed, this no longer should pass: the expression
# should be unchanged
assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1
# sympification should not allow the constant to enter a Mul
# or else the structure can change dramatically
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace(
'x', '_kern')
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
# issue 6687
assert (kernS('Interval(-1,-2 - 4*(-3))')
== Interval(-1, Add(-2, Mul(12, 1, evaluate=False), evaluate=False)))
assert kernS('_kern') == Symbol('_kern')
assert kernS('E**-(x)') == exp(-x)
e = 2*(x + y)*y
assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)]
assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \
-y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2
# issue 15132
assert kernS('(1 - x)/(1 - x*(1-y))') == kernS('(1-x)/(1-(1-y)*x)')
assert kernS('(1-2**-(4+1)*(1-y)*x)') == (1 - x*(1 - y)/32)
assert kernS('(1-2**(4+1)*(1-y)*x)') == (1 - 32*x*(1 - y))
assert kernS('(1-2.*(1-y)*x)') == 1 - 2.*x*(1 - y)
one = kernS('x - (x - 1)')
assert one != 1 and one.expand() == 1
assert kernS("(2*x)/(x-1)") == 2*x/(x-1)
def test_issue_6540_6552():
assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)]
assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (S.Half,)]
assert S('[[[2*(1)]]]') == [[[2]]]
assert S('Matrix([2*(1)])') == Matrix([2])
def test_issue_6046():
assert str(S("Q & C", locals=_clash1)) == 'C & Q'
assert str(S('pi(x)', locals=_clash2)) == 'pi(x)'
assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
locals = {}
exec("from sympy.abc import Q, C", locals)
assert str(S('C&Q', locals)) == 'C & Q'
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = sympify(s)
assert Abs(sin(p)) < 1e-127
def test_issue_10295():
if not numpy:
skip("numpy not installed.")
A = numpy.array([[1, 3, -1],
[0, 1, 7]])
sA = S(A)
assert sA.shape == (2, 3)
for (ri, ci), val in numpy.ndenumerate(A):
assert sA[ri, ci] == val
B = numpy.array([-7, x, 3*y**2])
sB = S(B)
assert sB.shape == (3,)
assert B[0] == sB[0] == -7
assert B[1] == sB[1] == x
assert B[2] == sB[2] == 3*y**2
C = numpy.arange(0, 24)
C.resize(2,3,4)
sC = S(C)
assert sC[0, 0, 0].is_integer
assert sC[0, 0, 0] == 0
a1 = numpy.array([1, 2, 3])
a2 = numpy.array([i for i in range(24)])
a2.resize(2, 4, 3)
assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3])
assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3))
def test_Range():
# Only works in Python 3 where range returns a range type
assert sympify(range(10)) == Range(10)
assert _sympify(range(10)) == Range(10)
def test_sympify_set():
n = Symbol('n')
assert sympify({n}) == FiniteSet(n)
assert sympify(set()) == EmptySet
def test_sympify_numpy():
if not numpy:
skip('numpy not installed. Abort numpy tests.')
np = numpy
def equal(x, y):
return x == y and type(x) == type(y)
assert sympify(np.bool_(1)) is S(True)
try:
assert equal(
sympify(np.int_(1234567891234567891)), S(1234567891234567891))
assert equal(
sympify(np.intp(1234567891234567891)), S(1234567891234567891))
except OverflowError:
# May fail on 32-bit systems: Python int too large to convert to C long
pass
assert equal(sympify(np.intc(1234567891)), S(1234567891))
assert equal(sympify(np.int8(-123)), S(-123))
assert equal(sympify(np.int16(-12345)), S(-12345))
assert equal(sympify(np.int32(-1234567891)), S(-1234567891))
assert equal(
sympify(np.int64(-1234567891234567891)), S(-1234567891234567891))
assert equal(sympify(np.uint8(123)), S(123))
assert equal(sympify(np.uint16(12345)), S(12345))
assert equal(sympify(np.uint32(1234567891)), S(1234567891))
assert equal(
sympify(np.uint64(1234567891234567891)), S(1234567891234567891))
assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24))
assert equal(sympify(np.float64(1.1234567891234)),
Float(1.1234567891234, precision=53))
assert equal(sympify(np.longdouble(1.123456789)),
Float(1.123456789, precision=80))
assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0*I))
assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0*I))
assert equal(sympify(np.longcomplex(1 + 2j)), S(1.0 + 2.0*I))
#float96 does not exist on all platforms
if hasattr(np, 'float96'):
assert equal(sympify(np.float96(1.123456789)),
Float(1.123456789, precision=80))
#float128 does not exist on all platforms
if hasattr(np, 'float128'):
assert equal(sympify(np.float128(1.123456789123)),
Float(1.123456789123, precision=80))
@XFAIL
def test_sympify_rational_numbers_set():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify({'.3', '.2'}, rational=True) == FiniteSet(*ans)
def test_issue_13924():
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.array([1]))
assert isinstance(a, ImmutableDenseNDimArray)
assert a[0] == 1
def test_numpy_sympify_args():
# Issue 15098. Make sure sympify args work with numpy types (like numpy.str_)
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.str_('a'))
assert type(a) is Symbol
assert a == Symbol('a')
class CustomSymbol(Symbol):
pass
a = sympify(numpy.str_('a'), {"Symbol": CustomSymbol})
assert isinstance(a, CustomSymbol)
a = sympify(numpy.str_('x^y'))
assert a == x**y
a = sympify(numpy.str_('x^y'), convert_xor=False)
assert a == Xor(x, y)
raises(SympifyError, lambda: sympify(numpy.str_('x'), strict=True))
a = sympify(numpy.str_('1.1'))
assert isinstance(a, Float)
assert a == 1.1
a = sympify(numpy.str_('1.1'), rational=True)
assert isinstance(a, Rational)
assert a == Rational(11, 10)
a = sympify(numpy.str_('x + x'))
assert isinstance(a, Mul)
assert a == 2*x
a = sympify(numpy.str_('x + x'), evaluate=False)
assert isinstance(a, Add)
assert a == Add(x, x, evaluate=False)
def test_issue_5939():
a = Symbol('a')
b = Symbol('b')
assert sympify('''a+\nb''') == a + b
def test_issue_16759():
d = sympify({.5: 1})
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(OrderedDict({.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(defaultdict(int, {.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
def test_issue_17811():
a = Function('a')
assert sympify('a(x)*5', evaluate=False) == Mul(a(x), 5, evaluate=False)
def test_issue_14706():
if not numpy:
skip("numpy not installed.")
z1 = numpy.zeros((1, 1), dtype=numpy.float)
z2 = numpy.zeros((2, 2), dtype=numpy.float)
z3 = numpy.zeros((), dtype=numpy.float)
y1 = numpy.ones((1, 1), dtype=numpy.float)
y2 = numpy.ones((2, 2), dtype=numpy.float)
y3 = numpy.ones((), dtype=numpy.float)
assert numpy.all(x + z1 == numpy.full((1, 1), x))
assert numpy.all(x + z2 == numpy.full((2, 2), x))
assert numpy.all(z1 + x == numpy.full((1, 1), x))
assert numpy.all(z2 + x == numpy.full((2, 2), x))
for z in [z3,
numpy.int(0),
numpy.float(0),
numpy.complex(0)]:
assert x + z == x
assert z + x == x
assert isinstance(x + z, Symbol)
assert isinstance(z + x, Symbol)
# If these tests fail, then it means that numpy has finally
# fixed the issue of scalar conversion for rank>0 arrays
# which is mentioned in numpy/numpy#10404. In that case,
# some changes have to be made in sympify.py.
# Note: For future reference, for anyone who takes up this
# issue when numpy has finally fixed their side of the problem,
# the changes for this temporary fix were introduced in PR 18651
assert numpy.all(x + y1 == numpy.full((1, 1), x + 1.0))
assert numpy.all(x + y2 == numpy.full((2, 2), x + 1.0))
assert numpy.all(y1 + x == numpy.full((1, 1), x + 1.0))
assert numpy.all(y2 + x == numpy.full((2, 2), x + 1.0))
for y_ in [y3,
numpy.int(1),
numpy.float(1),
numpy.complex(1)]:
assert x + y_ == y_ + x
assert isinstance(x + y_, Add)
assert isinstance(y_ + x, Add)
assert x + numpy.array(x) == 2 * x
assert x + numpy.array([x]) == numpy.array([2*x], dtype=object)
assert sympify(numpy.array([1])) == ImmutableDenseNDimArray([1], 1)
assert sympify(numpy.array([[[1]]])) == ImmutableDenseNDimArray([1], (1, 1, 1))
assert sympify(z1) == ImmutableDenseNDimArray([0], (1, 1))
assert sympify(z2) == ImmutableDenseNDimArray([0, 0, 0, 0], (2, 2))
assert sympify(z3) == ImmutableDenseNDimArray([0], ())
assert sympify(z3, strict=True) == 0.0
raises(SympifyError, lambda: sympify(numpy.array([1]), strict=True))
raises(SympifyError, lambda: sympify(z1, strict=True))
raises(SympifyError, lambda: sympify(z2, strict=True))
|
0d23d17cbbd22d69090cd7816468b93195b9f350d6dbf8f45dd1607cdcb2d289 | from sympy import (Basic, Symbol, sin, cos, atan, exp, sqrt, Rational,
Float, re, pi, sympify, Add, Mul, Pow, Mod, I, log, S, Max, symbols,
oo, zoo, Integer, sign, im, nan, Dummy, factorial, comp, floor, Poly,
FiniteSet
)
from sympy.core.parameters import distribute
from sympy.core.expr import unchanged
from sympy.utilities.iterables import cartes
from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy
from sympy.testing.randtest import verify_numerically
a, c, x, y, z = symbols('a,c,x,y,z')
b = Symbol("b", positive=True)
def same_and_same_prec(a, b):
# stricter matching for Floats
return a == b and a._prec == b._prec
def test_bug1():
assert re(x) != x
x.series(x, 0, 1)
assert re(x) != x
def test_Symbol():
e = a*b
assert e == a*b
assert a*b*b == a*b**2
assert a*b*b + c == c + a*b**2
assert a*b*b - c == -c + a*b**2
x = Symbol('x', complex=True, real=False)
assert x.is_imaginary is None # could be I or 1 + I
x = Symbol('x', complex=True, imaginary=False)
assert x.is_real is None # could be 1 or 1 + I
x = Symbol('x', real=True)
assert x.is_complex
x = Symbol('x', imaginary=True)
assert x.is_complex
x = Symbol('x', real=False, imaginary=False)
assert x.is_complex is None # might be a non-number
def test_arit0():
p = Rational(5)
e = a*b
assert e == a*b
e = a*b + b*a
assert e == 2*a*b
e = a*b + b*a + a*b + p*b*a
assert e == 8*a*b
e = a*b + b*a + a*b + p*b*a + a
assert e == a + 8*a*b
e = a + a
assert e == 2*a
e = a + b + a
assert e == b + 2*a
e = a + b*b + a + b*b
assert e == 2*a + 2*b**2
e = a + Rational(2) + b*b + a + b*b + p
assert e == 7 + 2*a + 2*b**2
e = (a + b*b + a + b*b)*p
assert e == 5*(2*a + 2*b**2)
e = (a*b*c + c*b*a + b*a*c)*p
assert e == 15*a*b*c
e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c
assert e == Rational(0)
e = Rational(50)*(a - a)
assert e == Rational(0)
e = b*a - b - a*b + b
assert e == Rational(0)
e = a*b + c**p
assert e == a*b + c**5
e = a/b
assert e == a*b**(-1)
e = a*2*2
assert e == 4*a
e = 2 + a*2/2
assert e == 2 + a
e = 2 - a - 2
assert e == -a
e = 2*a*2
assert e == 4*a
e = 2/a/2
assert e == a**(-1)
e = 2**a**2
assert e == 2**(a**2)
e = -(1 + a)
assert e == -1 - a
e = S.Half*(1 + a)
assert e == S.Half + a/2
def test_div():
e = a/b
assert e == a*b**(-1)
e = a/b + c/2
assert e == a*b**(-1) + Rational(1)/2*c
e = (1 - b)/(b - 1)
assert e == (1 + -b)*((-1) + b)**(-1)
def test_pow():
n1 = Rational(1)
n2 = Rational(2)
n5 = Rational(5)
e = a*a
assert e == a**2
e = a*a*a
assert e == a**3
e = a*a*a*a**Rational(6)
assert e == a**9
e = a*a*a*a**Rational(6) - a**Rational(9)
assert e == Rational(0)
e = a**(b - b)
assert e == Rational(1)
e = (a + Rational(1) - a)**b
assert e == Rational(1)
e = (a + b + c)**n2
assert e == (a + b + c)**2
assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2
e = (a + b)**n2
assert e == (a + b)**2
assert e.expand() == 2*a*b + a**2 + b**2
e = (a + b)**(n1/n2)
assert e == sqrt(a + b)
assert e.expand() == sqrt(a + b)
n = n5**(n1/n2)
assert n == sqrt(5)
e = n*a*b - n*b*a
assert e == Rational(0)
e = n*a*b + n*b*a
assert e == 2*a*b*sqrt(5)
assert e.diff(a) == 2*b*sqrt(5)
assert e.diff(a) == 2*b*sqrt(5)
e = a/b**2
assert e == a*b**(-2)
assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half
x = Symbol('x')
y = Symbol('y')
assert ((x*y)**3).expand() == y**3 * x**3
assert ((x*y)**-3).expand() == y**-3 * x**-3
assert (x**5*(3*x)**(3)).expand() == 27 * x**8
assert (x**5*(-3*x)**(3)).expand() == -27 * x**8
assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27)
assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27)
# expand_power_exp
assert (x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \
x**z*x**(y**(x + exp(x + y)))
assert (x**(y**(x + exp(x + y)) + z)).expand() == \
x**z*x**(y**x*y**(exp(x)*exp(y)))
n = Symbol('n', even=False)
k = Symbol('k', even=True)
o = Symbol('o', odd=True)
assert unchanged(Pow, -1, x)
assert unchanged(Pow, -1, n)
assert (-2)**k == 2**k
assert (-1)**k == 1
assert (-1)**o == -1
def test_pow2():
# x**(2*y) is always (x**y)**2 but is only (x**2)**y if
# x.is_positive or y.is_integer
# let x = 1 to see why the following are not true.
assert (-x)**Rational(2, 3) != x**Rational(2, 3)
assert (-x)**Rational(5, 7) != -x**Rational(5, 7)
assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2
assert sqrt(x**2) != x
def test_pow3():
assert sqrt(2)**3 == 2 * sqrt(2)
assert sqrt(2)**3 == sqrt(8)
def test_mod_pow():
for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365),
(3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]:
assert pow(S(s), t, u) == v
assert pow(S(s), S(t), u) == v
assert pow(S(s), t, S(u)) == v
assert pow(S(s), S(t), S(u)) == v
assert pow(S(2), S(10000000000), S(3)) == 1
assert pow(x, y, z) == x**y%z
raises(TypeError, lambda: pow(S(4), "13", 497))
raises(TypeError, lambda: pow(S(4), 13, "497"))
def test_pow_E():
assert 2**(y/log(2)) == S.Exp1**y
assert 2**(y/log(2)/3) == S.Exp1**(y/3)
assert 3**(1/log(-3)) != S.Exp1
assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1
assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1
assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9
assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9
# every time tests are run they will affirm with a different random
# value that this identity holds
while 1:
b = x._random()
r, i = b.as_real_imag()
if i:
break
assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1)
def test_pow_issue_3516():
assert 4**Rational(1, 4) == sqrt(2)
def test_pow_im():
for m in (-2, -1, 2):
for d in (3, 4, 5):
b = m*I
for i in range(1, 4*d + 1):
e = Rational(i, d)
assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0
e = Rational(7, 3)
assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha
im = symbols('im', imaginary=True)
assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e
args = [I, I, I, I, 2]
e = Rational(1, 3)
ans = 2**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args = [I, I, I, 2]
e = Rational(1, 3)
ans = 2**e*(-I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-3)
ans = (6*I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-1)
ans = (-6*I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args = [I, I, 2]
e = Rational(1, 3)
ans = (-2)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-3)
ans = (6)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-1)
ans = (-6)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I
assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I
def test_real_mul():
assert Float(0) * pi * x == 0
assert set((Float(1) * pi * x).args) == {Float(1), pi, x}
def test_ncmul():
A = Symbol("A", commutative=False)
B = Symbol("B", commutative=False)
C = Symbol("C", commutative=False)
assert A*B != B*A
assert A*B*C != C*B*A
assert A*b*B*3*C == 3*b*A*B*C
assert A*b*B*3*C != 3*b*B*A*C
assert A*b*B*3*C == 3*A*B*C*b
assert A + B == B + A
assert (A + B)*C != C*(A + B)
assert C*(A + B)*C != C*C*(A + B)
assert A*A == A**2
assert (A + B)*(A + B) == (A + B)**2
assert A**-1 * A == 1
assert A/A == 1
assert A/(A**2) == 1/A
assert A/(1 + A) == A/(1 + A)
assert set((A + B + 2*(A + B)).args) == \
{A, B, 2*(A + B)}
def test_mul_add_identity():
m = Mul(1, 2)
assert isinstance(m, Rational) and m.p == 2 and m.q == 1
m = Mul(1, 2, evaluate=False)
assert isinstance(m, Mul) and m.args == (1, 2)
m = Mul(0, 1)
assert m is S.Zero
m = Mul(0, 1, evaluate=False)
assert isinstance(m, Mul) and m.args == (0, 1)
m = Add(0, 1)
assert m is S.One
m = Add(0, 1, evaluate=False)
assert isinstance(m, Add) and m.args == (0, 1)
def test_ncpow():
x = Symbol('x', commutative=False)
y = Symbol('y', commutative=False)
z = Symbol('z', commutative=False)
a = Symbol('a')
b = Symbol('b')
c = Symbol('c')
assert (x**2)*(y**2) != (y**2)*(x**2)
assert (x**-2)*y != y*(x**2)
assert 2**x*2**y != 2**(x + y)
assert 2**x*2**y*2**z != 2**(x + y + z)
assert 2**x*2**(2*x) == 2**(3*x)
assert 2**x*2**(2*x)*2**x == 2**(4*x)
assert exp(x)*exp(y) != exp(y)*exp(x)
assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z)
assert exp(x)*exp(y)*exp(z) != exp(x + y + z)
assert x**a*x**b != x**(a + b)
assert x**a*x**b*x**c != x**(a + b + c)
assert x**3*x**4 == x**7
assert x**3*x**4*x**2 == x**9
assert x**a*x**(4*a) == x**(5*a)
assert x**a*x**(4*a)*x**a == x**(6*a)
def test_powerbug():
x = Symbol("x")
assert x**1 != (-x)**1
assert x**2 == (-x)**2
assert x**3 != (-x)**3
assert x**4 == (-x)**4
assert x**5 != (-x)**5
assert x**6 == (-x)**6
assert x**128 == (-x)**128
assert x**129 != (-x)**129
assert (2*x)**2 == (-2*x)**2
def test_Mul_doesnt_expand_exp():
x = Symbol('x')
y = Symbol('y')
assert unchanged(Mul, exp(x), exp(y))
assert unchanged(Mul, 2**x, 2**y)
assert x**2*x**3 == x**5
assert 2**x*3**x == 6**x
assert x**(y)*x**(2*y) == x**(3*y)
assert sqrt(2)*sqrt(2) == 2
assert 2**x*2**(2*x) == 2**(3*x)
assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4)
assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1)
def test_Mul_is_integer():
k = Symbol('k', integer=True)
n = Symbol('n', integer=True)
nr = Symbol('nr', rational=False)
nz = Symbol('nz', integer=True, zero=False)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
i2 = Symbol('2', prime=True, even=True)
assert (k/3).is_integer is None
assert (nz/3).is_integer is None
assert (nr/3).is_integer is False
assert (x*k*n).is_integer is None
assert (e/2).is_integer is True
assert (e**2/2).is_integer is True
assert (2/k).is_integer is None
assert (2/k**2).is_integer is None
assert ((-1)**k*n).is_integer is True
assert (3*k*e/2).is_integer is True
assert (2*k*e/3).is_integer is None
assert (e/o).is_integer is None
assert (o/e).is_integer is False
assert (o/i2).is_integer is False
assert Mul(k, 1/k, evaluate=False).is_integer is None
assert Mul(2., S.Half, evaluate=False).is_integer is None
assert (2*sqrt(k)).is_integer is None
assert (2*k**n).is_integer is None
s = 2**2**2**Pow(2, 1000, evaluate=False)
m = Mul(s, s, evaluate=False)
assert m.is_integer
# broken in 1.6 and before, see #20161
xq = Symbol('xq', rational=True)
yq = Symbol('yq', rational=True)
assert (xq*yq).is_integer is None
e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False)
assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation
def test_Add_Mul_is_integer():
x = Symbol('x')
k = Symbol('k', integer=True)
n = Symbol('n', integer=True)
nk = Symbol('nk', integer=False)
nr = Symbol('nr', rational=False)
nz = Symbol('nz', integer=True, zero=False)
assert (-nk).is_integer is None
assert (-nr).is_integer is False
assert (2*k).is_integer is True
assert (-k).is_integer is True
assert (k + nk).is_integer is False
assert (k + n).is_integer is True
assert (k + x).is_integer is None
assert (k + n*x).is_integer is None
assert (k + n/3).is_integer is None
assert (k + nz/3).is_integer is None
assert (k + nr/3).is_integer is False
assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
def test_Add_Mul_is_finite():
x = Symbol('x', extended_real=True, finite=False)
assert sin(x).is_finite is True
assert (x*sin(x)).is_finite is None
assert (x*atan(x)).is_finite is False
assert (1024*sin(x)).is_finite is True
assert (sin(x)*exp(x)).is_finite is None
assert (sin(x)*cos(x)).is_finite is True
assert (x*sin(x)*exp(x)).is_finite is None
assert (sin(x) - 67).is_finite is True
assert (sin(x) + exp(x)).is_finite is not True
assert (1 + x).is_finite is False
assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None
assert (sqrt(2)*(1 + x)).is_finite is False
assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False
def test_Mul_is_even_odd():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
n = Symbol('n', odd=True)
m = Symbol('m', even=True)
assert (2*x).is_even is True
assert (2*x).is_odd is False
assert (3*x).is_even is None
assert (3*x).is_odd is None
assert (k/3).is_integer is None
assert (k/3).is_even is None
assert (k/3).is_odd is None
assert (2*n).is_even is True
assert (2*n).is_odd is False
assert (2*m).is_even is True
assert (2*m).is_odd is False
assert (-n).is_even is False
assert (-n).is_odd is True
assert (k*n).is_even is False
assert (k*n).is_odd is True
assert (k*m).is_even is True
assert (k*m).is_odd is False
assert (k*n*m).is_even is True
assert (k*n*m).is_odd is False
assert (k*m*x).is_even is True
assert (k*m*x).is_odd is False
# issue 6791:
assert (x/2).is_integer is None
assert (k/2).is_integer is False
assert (m/2).is_integer is True
assert (x*y).is_even is None
assert (x*x).is_even is None
assert (x*(x + k)).is_even is True
assert (x*(x + m)).is_even is None
assert (x*y).is_odd is None
assert (x*x).is_odd is None
assert (x*(x + k)).is_odd is False
assert (x*(x + m)).is_odd is None
@XFAIL
def test_evenness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
assert (x*y*(y + k)).is_even is True
assert (y*x*(x + k)).is_even is True
def test_evenness_in_ternary_integer_product_with_even():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
m = Symbol('m', even=True)
assert (x*y*(y + m)).is_even is None
@XFAIL
def test_oddness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
assert (x*y*(y + k)).is_odd is False
assert (y*x*(x + k)).is_odd is False
def test_oddness_in_ternary_integer_product_with_even():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
m = Symbol('m', even=True)
assert (x*y*(y + m)).is_odd is None
def test_Mul_is_rational():
x = Symbol('x')
n = Symbol('n', integer=True)
m = Symbol('m', integer=True, nonzero=True)
assert (n/m).is_rational is True
assert (x/pi).is_rational is None
assert (x/n).is_rational is None
assert (m/pi).is_rational is False
r = Symbol('r', rational=True)
assert (pi*r).is_rational is None
# issue 8008
z = Symbol('z', zero=True)
i = Symbol('i', imaginary=True)
assert (z*i).is_rational is True
bi = Symbol('i', imaginary=True, finite=True)
assert (z*bi).is_zero is True
def test_Add_is_rational():
x = Symbol('x')
n = Symbol('n', rational=True)
m = Symbol('m', rational=True)
assert (n + m).is_rational is True
assert (x + pi).is_rational is None
assert (x + n).is_rational is None
assert (n + pi).is_rational is False
def test_Add_is_even_odd():
x = Symbol('x', integer=True)
k = Symbol('k', odd=True)
n = Symbol('n', odd=True)
m = Symbol('m', even=True)
assert (k + 7).is_even is True
assert (k + 7).is_odd is False
assert (-k + 7).is_even is True
assert (-k + 7).is_odd is False
assert (k - 12).is_even is False
assert (k - 12).is_odd is True
assert (-k - 12).is_even is False
assert (-k - 12).is_odd is True
assert (k + n).is_even is True
assert (k + n).is_odd is False
assert (k + m).is_even is False
assert (k + m).is_odd is True
assert (k + n + m).is_even is True
assert (k + n + m).is_odd is False
assert (k + n + x + m).is_even is None
assert (k + n + x + m).is_odd is None
def test_Mul_is_negative_positive():
x = Symbol('x', real=True)
y = Symbol('y', extended_real=False, complex=True)
z = Symbol('z', zero=True)
e = 2*z
assert e.is_Mul and e.is_positive is False and e.is_negative is False
neg = Symbol('neg', negative=True)
pos = Symbol('pos', positive=True)
nneg = Symbol('nneg', nonnegative=True)
npos = Symbol('npos', nonpositive=True)
assert neg.is_negative is True
assert (-neg).is_negative is False
assert (2*neg).is_negative is True
assert (2*pos)._eval_is_extended_negative() is False
assert (2*pos).is_negative is False
assert pos.is_negative is False
assert (-pos).is_negative is True
assert (2*pos).is_negative is False
assert (pos*neg).is_negative is True
assert (2*pos*neg).is_negative is True
assert (-pos*neg).is_negative is False
assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg
assert nneg.is_negative is False
assert (-nneg).is_negative is None
assert (2*nneg).is_negative is False
assert npos.is_negative is None
assert (-npos).is_negative is False
assert (2*npos).is_negative is None
assert (nneg*npos).is_negative is None
assert (neg*nneg).is_negative is None
assert (neg*npos).is_negative is False
assert (pos*nneg).is_negative is False
assert (pos*npos).is_negative is None
assert (npos*neg*nneg).is_negative is False
assert (npos*pos*nneg).is_negative is None
assert (-npos*neg*nneg).is_negative is None
assert (-npos*pos*nneg).is_negative is False
assert (17*npos*neg*nneg).is_negative is False
assert (17*npos*pos*nneg).is_negative is None
assert (neg*npos*pos*nneg).is_negative is False
assert (x*neg).is_negative is None
assert (nneg*npos*pos*x*neg).is_negative is None
assert neg.is_positive is False
assert (-neg).is_positive is True
assert (2*neg).is_positive is False
assert pos.is_positive is True
assert (-pos).is_positive is False
assert (2*pos).is_positive is True
assert (pos*neg).is_positive is False
assert (2*pos*neg).is_positive is False
assert (-pos*neg).is_positive is True
assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg
assert nneg.is_positive is None
assert (-nneg).is_positive is False
assert (2*nneg).is_positive is None
assert npos.is_positive is False
assert (-npos).is_positive is None
assert (2*npos).is_positive is False
assert (nneg*npos).is_positive is False
assert (neg*nneg).is_positive is False
assert (neg*npos).is_positive is None
assert (pos*nneg).is_positive is None
assert (pos*npos).is_positive is False
assert (npos*neg*nneg).is_positive is None
assert (npos*pos*nneg).is_positive is False
assert (-npos*neg*nneg).is_positive is False
assert (-npos*pos*nneg).is_positive is None
assert (17*npos*neg*nneg).is_positive is None
assert (17*npos*pos*nneg).is_positive is False
assert (neg*npos*pos*nneg).is_positive is None
assert (x*neg).is_positive is None
assert (nneg*npos*pos*x*neg).is_positive is None
def test_Mul_is_negative_positive_2():
a = Symbol('a', nonnegative=True)
b = Symbol('b', nonnegative=True)
c = Symbol('c', nonpositive=True)
d = Symbol('d', nonpositive=True)
assert (a*b).is_nonnegative is True
assert (a*b).is_negative is False
assert (a*b).is_zero is None
assert (a*b).is_positive is None
assert (c*d).is_nonnegative is True
assert (c*d).is_negative is False
assert (c*d).is_zero is None
assert (c*d).is_positive is None
assert (a*c).is_nonpositive is True
assert (a*c).is_positive is False
assert (a*c).is_zero is None
assert (a*c).is_negative is None
def test_Mul_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert k.is_nonpositive is True
assert (-k).is_nonpositive is False
assert (2*k).is_nonpositive is True
assert n.is_nonpositive is False
assert (-n).is_nonpositive is True
assert (2*n).is_nonpositive is False
assert (n*k).is_nonpositive is True
assert (2*n*k).is_nonpositive is True
assert (-n*k).is_nonpositive is False
assert u.is_nonpositive is None
assert (-u).is_nonpositive is True
assert (2*u).is_nonpositive is None
assert v.is_nonpositive is True
assert (-v).is_nonpositive is None
assert (2*v).is_nonpositive is True
assert (u*v).is_nonpositive is True
assert (k*u).is_nonpositive is True
assert (k*v).is_nonpositive is None
assert (n*u).is_nonpositive is None
assert (n*v).is_nonpositive is True
assert (v*k*u).is_nonpositive is None
assert (v*n*u).is_nonpositive is True
assert (-v*k*u).is_nonpositive is True
assert (-v*n*u).is_nonpositive is None
assert (17*v*k*u).is_nonpositive is None
assert (17*v*n*u).is_nonpositive is True
assert (k*v*n*u).is_nonpositive is None
assert (x*k).is_nonpositive is None
assert (u*v*n*x*k).is_nonpositive is None
assert k.is_nonnegative is False
assert (-k).is_nonnegative is True
assert (2*k).is_nonnegative is False
assert n.is_nonnegative is True
assert (-n).is_nonnegative is False
assert (2*n).is_nonnegative is True
assert (n*k).is_nonnegative is False
assert (2*n*k).is_nonnegative is False
assert (-n*k).is_nonnegative is True
assert u.is_nonnegative is True
assert (-u).is_nonnegative is None
assert (2*u).is_nonnegative is True
assert v.is_nonnegative is None
assert (-v).is_nonnegative is True
assert (2*v).is_nonnegative is None
assert (u*v).is_nonnegative is None
assert (k*u).is_nonnegative is None
assert (k*v).is_nonnegative is True
assert (n*u).is_nonnegative is True
assert (n*v).is_nonnegative is None
assert (v*k*u).is_nonnegative is True
assert (v*n*u).is_nonnegative is None
assert (-v*k*u).is_nonnegative is None
assert (-v*n*u).is_nonnegative is True
assert (17*v*k*u).is_nonnegative is True
assert (17*v*n*u).is_nonnegative is None
assert (k*v*n*u).is_nonnegative is True
assert (x*k).is_nonnegative is None
assert (u*v*n*x*k).is_nonnegative is None
def test_Add_is_negative_positive():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert (k - 2).is_negative is True
assert (k + 17).is_negative is None
assert (-k - 5).is_negative is None
assert (-k + 123).is_negative is False
assert (k - n).is_negative is True
assert (k + n).is_negative is None
assert (-k - n).is_negative is None
assert (-k + n).is_negative is False
assert (k - n - 2).is_negative is True
assert (k + n + 17).is_negative is None
assert (-k - n - 5).is_negative is None
assert (-k + n + 123).is_negative is False
assert (-2*k + 123*n + 17).is_negative is False
assert (k + u).is_negative is None
assert (k + v).is_negative is True
assert (n + u).is_negative is False
assert (n + v).is_negative is None
assert (u - v).is_negative is False
assert (u + v).is_negative is None
assert (-u - v).is_negative is None
assert (-u + v).is_negative is None
assert (u - v + n + 2).is_negative is False
assert (u + v + n + 2).is_negative is None
assert (-u - v + n + 2).is_negative is None
assert (-u + v + n + 2).is_negative is None
assert (k + x).is_negative is None
assert (k + x - n).is_negative is None
assert (k - 2).is_positive is False
assert (k + 17).is_positive is None
assert (-k - 5).is_positive is None
assert (-k + 123).is_positive is True
assert (k - n).is_positive is False
assert (k + n).is_positive is None
assert (-k - n).is_positive is None
assert (-k + n).is_positive is True
assert (k - n - 2).is_positive is False
assert (k + n + 17).is_positive is None
assert (-k - n - 5).is_positive is None
assert (-k + n + 123).is_positive is True
assert (-2*k + 123*n + 17).is_positive is True
assert (k + u).is_positive is None
assert (k + v).is_positive is False
assert (n + u).is_positive is True
assert (n + v).is_positive is None
assert (u - v).is_positive is None
assert (u + v).is_positive is None
assert (-u - v).is_positive is None
assert (-u + v).is_positive is False
assert (u - v - n - 2).is_positive is None
assert (u + v - n - 2).is_positive is None
assert (-u - v - n - 2).is_positive is None
assert (-u + v - n - 2).is_positive is False
assert (n + x).is_positive is None
assert (n + x - k).is_positive is None
z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2)
assert z.is_zero
z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert z.is_zero
def test_Add_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert (u - 2).is_nonpositive is None
assert (u + 17).is_nonpositive is False
assert (-u - 5).is_nonpositive is True
assert (-u + 123).is_nonpositive is None
assert (u - v).is_nonpositive is None
assert (u + v).is_nonpositive is None
assert (-u - v).is_nonpositive is None
assert (-u + v).is_nonpositive is True
assert (u - v - 2).is_nonpositive is None
assert (u + v + 17).is_nonpositive is None
assert (-u - v - 5).is_nonpositive is None
assert (-u + v - 123).is_nonpositive is True
assert (-2*u + 123*v - 17).is_nonpositive is True
assert (k + u).is_nonpositive is None
assert (k + v).is_nonpositive is True
assert (n + u).is_nonpositive is False
assert (n + v).is_nonpositive is None
assert (k - n).is_nonpositive is True
assert (k + n).is_nonpositive is None
assert (-k - n).is_nonpositive is None
assert (-k + n).is_nonpositive is False
assert (k - n + u + 2).is_nonpositive is None
assert (k + n + u + 2).is_nonpositive is None
assert (-k - n + u + 2).is_nonpositive is None
assert (-k + n + u + 2).is_nonpositive is False
assert (u + x).is_nonpositive is None
assert (v - x - n).is_nonpositive is None
assert (u - 2).is_nonnegative is None
assert (u + 17).is_nonnegative is True
assert (-u - 5).is_nonnegative is False
assert (-u + 123).is_nonnegative is None
assert (u - v).is_nonnegative is True
assert (u + v).is_nonnegative is None
assert (-u - v).is_nonnegative is None
assert (-u + v).is_nonnegative is None
assert (u - v + 2).is_nonnegative is True
assert (u + v + 17).is_nonnegative is None
assert (-u - v - 5).is_nonnegative is None
assert (-u + v - 123).is_nonnegative is False
assert (2*u - 123*v + 17).is_nonnegative is True
assert (k + u).is_nonnegative is None
assert (k + v).is_nonnegative is False
assert (n + u).is_nonnegative is True
assert (n + v).is_nonnegative is None
assert (k - n).is_nonnegative is False
assert (k + n).is_nonnegative is None
assert (-k - n).is_nonnegative is None
assert (-k + n).is_nonnegative is True
assert (k - n - u - 2).is_nonnegative is False
assert (k + n - u - 2).is_nonnegative is None
assert (-k - n - u - 2).is_nonnegative is None
assert (-k + n - u - 2).is_nonnegative is None
assert (u - x).is_nonnegative is None
assert (v + x + n).is_nonnegative is None
def test_Pow_is_integer():
x = Symbol('x')
k = Symbol('k', integer=True)
n = Symbol('n', integer=True, nonnegative=True)
m = Symbol('m', integer=True, positive=True)
assert (k**2).is_integer is True
assert (k**(-2)).is_integer is None
assert ((m + 1)**(-2)).is_integer is False
assert (m**(-1)).is_integer is None # issue 8580
assert (2**k).is_integer is None
assert (2**(-k)).is_integer is None
assert (2**n).is_integer is True
assert (2**(-n)).is_integer is None
assert (2**m).is_integer is True
assert (2**(-m)).is_integer is False
assert (x**2).is_integer is None
assert (2**x).is_integer is None
assert (k**n).is_integer is True
assert (k**(-n)).is_integer is None
assert (k**x).is_integer is None
assert (x**k).is_integer is None
assert (k**(n*m)).is_integer is True
assert (k**(-n*m)).is_integer is None
assert sqrt(3).is_integer is False
assert sqrt(.3).is_integer is False
assert Pow(3, 2, evaluate=False).is_integer is True
assert Pow(3, 0, evaluate=False).is_integer is True
assert Pow(3, -2, evaluate=False).is_integer is False
assert Pow(S.Half, 3, evaluate=False).is_integer is False
# decided by re-evaluating
assert Pow(3, S.Half, evaluate=False).is_integer is False
assert Pow(3, S.Half, evaluate=False).is_integer is False
assert Pow(4, S.Half, evaluate=False).is_integer is True
assert Pow(S.Half, -2, evaluate=False).is_integer is True
assert ((-1)**k).is_integer
# issue 8641
x = Symbol('x', real=True, integer=False)
assert (x**2).is_integer is None
# issue 10458
x = Symbol('x', positive=True)
assert (1/(x + 1)).is_integer is False
assert (1/(-x - 1)).is_integer is False
def test_Pow_is_real():
x = Symbol('x', real=True)
y = Symbol('y', real=True, positive=True)
assert (x**2).is_real is True
assert (x**3).is_real is True
assert (x**x).is_real is None
assert (y**x).is_real is True
assert (x**Rational(1, 3)).is_real is None
assert (y**Rational(1, 3)).is_real is True
assert sqrt(-1 - sqrt(2)).is_real is False
i = Symbol('i', imaginary=True)
assert (i**i).is_real is None
assert (I**i).is_extended_real is True
assert ((-I)**i).is_extended_real is True
assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not
assert (2**I).is_real is False
assert (2**-I).is_real is False
assert (i**2).is_extended_real is True
assert (i**3).is_extended_real is False
assert (i**x).is_real is None # could be (-I)**(2/3)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
k = Symbol('k', integer=True)
assert (i**e).is_extended_real is True
assert (i**o).is_extended_real is False
assert (i**k).is_real is None
assert (i**(4*k)).is_extended_real is True
x = Symbol("x", nonnegative=True)
y = Symbol("y", nonnegative=True)
assert im(x**y).expand(complex=True) is S.Zero
assert (x**y).is_real is True
i = Symbol('i', imaginary=True)
assert (exp(i)**I).is_extended_real is True
assert log(exp(i)).is_imaginary is None # i could be 2*pi*I
c = Symbol('c', complex=True)
assert log(c).is_real is None # c could be 0 or 2, too
assert log(exp(c)).is_real is None # log(0), log(E), ...
n = Symbol('n', negative=False)
assert log(n).is_real is None
n = Symbol('n', nonnegative=True)
assert log(n).is_real is None
assert sqrt(-I).is_real is False # issue 7843
i = Symbol('i', integer=True)
assert (1/(i-1)).is_real is None
assert (1/(i-1)).is_extended_real is None
def test_real_Pow():
k = Symbol('k', integer=True, nonzero=True)
assert (k**(I*pi/log(k))).is_real
def test_Pow_is_finite():
xe = Symbol('xe', extended_real=True)
xr = Symbol('xr', real=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
i = Symbol('i', integer=True)
assert (xe**2).is_finite is None # xe could be oo
assert (xr**2).is_finite is True
assert (xe**xe).is_finite is None
assert (xr**xe).is_finite is None
assert (xe**xr).is_finite is None
# FIXME: The line below should be True rather than None
# assert (xr**xr).is_finite is True
assert (xr**xr).is_finite is None
assert (p**xe).is_finite is None
assert (p**xr).is_finite is True
assert (n**xe).is_finite is None
assert (n**xr).is_finite is True
assert (sin(xe)**2).is_finite is True
assert (sin(xr)**2).is_finite is True
assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi
assert (sin(xr)**xr).is_finite is None
# FIXME: Should the line below be True rather than None?
assert (sin(xe)**exp(xe)).is_finite is None
assert (sin(xr)**exp(xr)).is_finite is True
assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes
assert (1/sin(xr)).is_finite is None
assert (1/exp(xe)).is_finite is None # xe could be -oo
assert (1/exp(xr)).is_finite is True
assert (1/S.Pi).is_finite is True
assert (1/(i-1)).is_finite is None
def test_Pow_is_even_odd():
x = Symbol('x')
k = Symbol('k', even=True)
n = Symbol('n', odd=True)
m = Symbol('m', integer=True, nonnegative=True)
p = Symbol('p', integer=True, positive=True)
assert ((-1)**n).is_odd
assert ((-1)**k).is_odd
assert ((-1)**(m - p)).is_odd
assert (k**2).is_even is True
assert (n**2).is_even is False
assert (2**k).is_even is None
assert (x**2).is_even is None
assert (k**m).is_even is None
assert (n**m).is_even is False
assert (k**p).is_even is True
assert (n**p).is_even is False
assert (m**k).is_even is None
assert (p**k).is_even is None
assert (m**n).is_even is None
assert (p**n).is_even is None
assert (k**x).is_even is None
assert (n**x).is_even is None
assert (k**2).is_odd is False
assert (n**2).is_odd is True
assert (3**k).is_odd is None
assert (k**m).is_odd is None
assert (n**m).is_odd is True
assert (k**p).is_odd is False
assert (n**p).is_odd is True
assert (m**k).is_odd is None
assert (p**k).is_odd is None
assert (m**n).is_odd is None
assert (p**n).is_odd is None
assert (k**x).is_odd is None
assert (n**x).is_odd is None
def test_Pow_is_negative_positive():
r = Symbol('r', real=True)
k = Symbol('k', integer=True, positive=True)
n = Symbol('n', even=True)
m = Symbol('m', odd=True)
x = Symbol('x')
assert (2**r).is_positive is True
assert ((-2)**r).is_positive is None
assert ((-2)**n).is_positive is True
assert ((-2)**m).is_positive is False
assert (k**2).is_positive is True
assert (k**(-2)).is_positive is True
assert (k**r).is_positive is True
assert ((-k)**r).is_positive is None
assert ((-k)**n).is_positive is True
assert ((-k)**m).is_positive is False
assert (2**r).is_negative is False
assert ((-2)**r).is_negative is None
assert ((-2)**n).is_negative is False
assert ((-2)**m).is_negative is True
assert (k**2).is_negative is False
assert (k**(-2)).is_negative is False
assert (k**r).is_negative is False
assert ((-k)**r).is_negative is None
assert ((-k)**n).is_negative is False
assert ((-k)**m).is_negative is True
assert (2**x).is_positive is None
assert (2**x).is_negative is None
def test_Pow_is_zero():
z = Symbol('z', zero=True)
e = z**2
assert e.is_zero
assert e.is_positive is False
assert e.is_negative is False
assert Pow(0, 0, evaluate=False).is_zero is False
assert Pow(0, 3, evaluate=False).is_zero
assert Pow(0, oo, evaluate=False).is_zero
assert Pow(0, -3, evaluate=False).is_zero is False
assert Pow(0, -oo, evaluate=False).is_zero is False
assert Pow(2, 2, evaluate=False).is_zero is False
a = Symbol('a', zero=False)
assert Pow(a, 3).is_zero is False # issue 7965
assert Pow(2, oo, evaluate=False).is_zero is False
assert Pow(2, -oo, evaluate=False).is_zero
assert Pow(S.Half, oo, evaluate=False).is_zero
assert Pow(S.Half, -oo, evaluate=False).is_zero is False
# All combinations of real/complex base/exponent
h = S.Half
T = True
F = False
N = None
pow_iszero = [
['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo],
[ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N],
[ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
[ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
[ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
[ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
[ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N]
]
def test_table(table):
n = len(table[0])
for row in range(1, n):
base = table[row][0]
for col in range(1, n):
exp = table[0][col]
is_zero = table[row][col]
# The actual test here:
assert Pow(base, exp, evaluate=False).is_zero is is_zero
test_table(pow_iszero)
# A zero symbol...
zo, zo2 = symbols('zo, zo2', zero=True)
# All combinations of finite symbols
zf, zf2 = symbols('zf, zf2', finite=True)
wf, wf2 = symbols('wf, wf2', nonzero=True)
xf, xf2 = symbols('xf, xf2', real=True)
yf, yf2 = symbols('yf, yf2', nonzero=True)
af, af2 = symbols('af, af2', positive=True)
bf, bf2 = symbols('bf, bf2', nonnegative=True)
cf, cf2 = symbols('cf, cf2', negative=True)
df, df2 = symbols('df, df2', nonpositive=True)
# Without finiteness:
zi, zi2 = symbols('zi, zi2')
wi, wi2 = symbols('wi, wi2', zero=False)
xi, xi2 = symbols('xi, xi2', extended_real=True)
yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True)
ai, ai2 = symbols('ai, ai2', extended_positive=True)
bi, bi2 = symbols('bi, bi2', extended_nonnegative=True)
ci, ci2 = symbols('ci, ci2', extended_negative=True)
di, di2 = symbols('di, di2', extended_nonpositive=True)
pow_iszero_sym = [
['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di],
[ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F],
[ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N]
]
test_table(pow_iszero_sym)
# In some cases (x**x).is_zero is different from (x**y).is_zero even if y
# has the same assumptions as x.
assert (zo ** zo).is_zero is False
assert (wf ** wf).is_zero is False
assert (yf ** yf).is_zero is False
assert (af ** af).is_zero is False
assert (cf ** cf).is_zero is False
assert (zf ** zf).is_zero is None
assert (xf ** xf).is_zero is None
assert (bf ** bf).is_zero is False # None in table
assert (df ** df).is_zero is None
assert (zi ** zi).is_zero is None
assert (wi ** wi).is_zero is None
assert (xi ** xi).is_zero is None
assert (yi ** yi).is_zero is None
assert (ai ** ai).is_zero is False # None in table
assert (bi ** bi).is_zero is False # None in table
assert (ci ** ci).is_zero is None
assert (di ** di).is_zero is None
def test_Pow_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', integer=True, nonnegative=True)
l = Symbol('l', integer=True, positive=True)
n = Symbol('n', even=True)
m = Symbol('m', odd=True)
assert (x**(4*k)).is_nonnegative is True
assert (2**x).is_nonnegative is True
assert ((-2)**x).is_nonnegative is None
assert ((-2)**n).is_nonnegative is True
assert ((-2)**m).is_nonnegative is False
assert (k**2).is_nonnegative is True
assert (k**(-2)).is_nonnegative is None
assert (k**k).is_nonnegative is True
assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U
assert (l**x).is_nonnegative is True
assert (l**x).is_positive is True
assert ((-k)**x).is_nonnegative is None
assert ((-k)**m).is_nonnegative is None
assert (2**x).is_nonpositive is False
assert ((-2)**x).is_nonpositive is None
assert ((-2)**n).is_nonpositive is False
assert ((-2)**m).is_nonpositive is True
assert (k**2).is_nonpositive is None
assert (k**(-2)).is_nonpositive is None
assert (k**x).is_nonpositive is None
assert ((-k)**x).is_nonpositive is None
assert ((-k)**n).is_nonpositive is None
assert (x**2).is_nonnegative is True
i = symbols('i', imaginary=True)
assert (i**2).is_nonpositive is True
assert (i**4).is_nonpositive is False
assert (i**3).is_nonpositive is False
assert (I**i).is_nonnegative is True
assert (exp(I)**i).is_nonnegative is True
assert ((-l)**n).is_nonnegative is True
assert ((-l)**m).is_nonpositive is True
assert ((-k)**n).is_nonnegative is None
assert ((-k)**m).is_nonpositive is None
def test_Mul_is_imaginary_real():
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
i1 = Symbol('i1', imaginary=True)
i2 = Symbol('i2', imaginary=True)
x = Symbol('x')
assert I.is_imaginary is True
assert I.is_real is False
assert (-I).is_imaginary is True
assert (-I).is_real is False
assert (3*I).is_imaginary is True
assert (3*I).is_real is False
assert (I*I).is_imaginary is False
assert (I*I).is_real is True
e = (p + p*I)
j = Symbol('j', integer=True, zero=False)
assert (e**j).is_real is None
assert (e**(2*j)).is_real is None
assert (e**j).is_imaginary is None
assert (e**(2*j)).is_imaginary is None
assert (e**-1).is_imaginary is False
assert (e**2).is_imaginary
assert (e**3).is_imaginary is False
assert (e**4).is_imaginary is False
assert (e**5).is_imaginary is False
assert (e**-1).is_real is False
assert (e**2).is_real is False
assert (e**3).is_real is False
assert (e**4).is_real is True
assert (e**5).is_real is False
assert (e**3).is_complex
assert (r*i1).is_imaginary is None
assert (r*i1).is_real is None
assert (x*i1).is_imaginary is None
assert (x*i1).is_real is None
assert (i1*i2).is_imaginary is False
assert (i1*i2).is_real is True
assert (r*i1*i2).is_imaginary is False
assert (r*i1*i2).is_real is True
# Github's issue 5874:
nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I
a = Symbol('a', real=True, nonzero=True)
b = Symbol('b', real=True)
assert (i1*nr).is_real is None
assert (a*nr).is_real is False
assert (b*nr).is_real is None
ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I
a = Symbol('a', real=True, nonzero=True)
b = Symbol('b', real=True)
assert (i1*ni).is_real is False
assert (a*ni).is_real is None
assert (b*ni).is_real is None
def test_Mul_hermitian_antihermitian():
a = Symbol('a', hermitian=True, zero=False)
b = Symbol('b', hermitian=True)
c = Symbol('c', hermitian=False)
d = Symbol('d', antihermitian=True)
e1 = Mul(a, b, c, evaluate=False)
e2 = Mul(b, a, c, evaluate=False)
e3 = Mul(a, b, c, d, evaluate=False)
e4 = Mul(b, a, c, d, evaluate=False)
e5 = Mul(a, c, evaluate=False)
e6 = Mul(a, c, d, evaluate=False)
assert e1.is_hermitian is None
assert e2.is_hermitian is None
assert e1.is_antihermitian is None
assert e2.is_antihermitian is None
assert e3.is_antihermitian is None
assert e4.is_antihermitian is None
assert e5.is_antihermitian is None
assert e6.is_antihermitian is None
def test_Add_is_comparable():
assert (x + y).is_comparable is False
assert (x + 1).is_comparable is False
assert (Rational(1, 3) - sqrt(8)).is_comparable is True
def test_Mul_is_comparable():
assert (x*y).is_comparable is False
assert (x*2).is_comparable is False
assert (sqrt(2)*Rational(1, 3)).is_comparable is True
def test_Pow_is_comparable():
assert (x**y).is_comparable is False
assert (x**2).is_comparable is False
assert (sqrt(Rational(1, 3))).is_comparable is True
def test_Add_is_positive_2():
e = Rational(1, 3) - sqrt(8)
assert e.is_positive is False
assert e.is_negative is True
e = pi - 1
assert e.is_positive is True
assert e.is_negative is False
def test_Add_is_irrational():
i = Symbol('i', irrational=True)
assert i.is_irrational is True
assert i.is_rational is False
assert (i + 1).is_irrational is True
assert (i + 1).is_rational is False
def test_Mul_is_irrational():
expr = Mul(1, 2, 3, evaluate=False)
assert expr.is_irrational is False
expr = Mul(1, I, I, evaluate=False)
assert expr.is_rational is None # I * I = -1 but *no evaluation allowed*
# sqrt(2) * I * I = -sqrt(2) is irrational but
# this can't be determined without evaluating the
# expression and the eval_is routines shouldn't do that
expr = Mul(sqrt(2), I, I, evaluate=False)
assert expr.is_irrational is None
def test_issue_3531():
# https://github.com/sympy/sympy/issues/3531
# https://github.com/sympy/sympy/pull/18116
class MightyNumeric(tuple):
def __rtruediv__(self, other):
return "something"
assert sympify(1)/MightyNumeric((1, 2)) == "something"
def test_issue_3531b():
class Foo:
def __init__(self):
self.field = 1.0
def __mul__(self, other):
self.field = self.field * other
def __rmul__(self, other):
self.field = other * self.field
f = Foo()
x = Symbol("x")
assert f*x == x*f
def test_bug3():
a = Symbol("a")
b = Symbol("b", positive=True)
e = 2*a + b
f = b + 2*a
assert e == f
def test_suppressed_evaluation():
a = Add(0, 3, 2, evaluate=False)
b = Mul(1, 3, 2, evaluate=False)
c = Pow(3, 2, evaluate=False)
assert a != 6
assert a.func is Add
assert a.args == (0, 3, 2)
assert b != 6
assert b.func is Mul
assert b.args == (1, 3, 2)
assert c != 9
assert c.func is Pow
assert c.args == (3, 2)
def test_AssocOp_doit():
a = Add(x,x, evaluate=False)
b = Mul(y,y, evaluate=False)
c = Add(b,b, evaluate=False)
d = Mul(a,a, evaluate=False)
assert c.doit(deep=False).func == Mul
assert c.doit(deep=False).args == (2,y,y)
assert c.doit().func == Mul
assert c.doit().args == (2, Pow(y,2))
assert d.doit(deep=False).func == Pow
assert d.doit(deep=False).args == (a, 2*S.One)
assert d.doit().func == Mul
assert d.doit().args == (4*S.One, Pow(x,2))
def test_Add_Mul_Expr_args():
nonexpr = [Basic(), Poly(x, x), FiniteSet(x)]
for typ in [Add, Mul]:
for obj in nonexpr:
with warns_deprecated_sympy():
typ(obj, 1)
def test_Add_as_coeff_mul():
# issue 5524. These should all be (1, self)
assert (x + 1).as_coeff_mul() == (1, (x + 1,))
assert (x + 2).as_coeff_mul() == (1, (x + 2,))
assert (x + 3).as_coeff_mul() == (1, (x + 3,))
assert (x - 1).as_coeff_mul() == (1, (x - 1,))
assert (x - 2).as_coeff_mul() == (1, (x - 2,))
assert (x - 3).as_coeff_mul() == (1, (x - 3,))
n = Symbol('n', integer=True)
assert (n + 1).as_coeff_mul() == (1, (n + 1,))
assert (n + 2).as_coeff_mul() == (1, (n + 2,))
assert (n + 3).as_coeff_mul() == (1, (n + 3,))
assert (n - 1).as_coeff_mul() == (1, (n - 1,))
assert (n - 2).as_coeff_mul() == (1, (n - 2,))
assert (n - 3).as_coeff_mul() == (1, (n - 3,))
def test_Pow_as_coeff_mul_doesnt_expand():
assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),))
assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y))
def test_issue_3514_18626():
assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2
assert S.Half*sqrt(6)*sqrt(2) == sqrt(3)
assert sqrt(6)/2*sqrt(2) == sqrt(3)
assert sqrt(6)*sqrt(2)/2 == sqrt(3)
assert sqrt(8)**Rational(2, 3) == 2
def test_make_args():
assert Add.make_args(x) == (x,)
assert Mul.make_args(x) == (x,)
assert Add.make_args(x*y*z) == (x*y*z,)
assert Mul.make_args(x*y*z) == (x*y*z).args
assert Add.make_args(x + y + z) == (x + y + z).args
assert Mul.make_args(x + y + z) == (x + y + z,)
assert Add.make_args((x + y)**z) == ((x + y)**z,)
assert Mul.make_args((x + y)**z) == ((x + y)**z,)
def test_issue_5126():
assert (-2)**x*(-3)**x != 6**x
i = Symbol('i', integer=1)
assert (-2)**i*(-3)**i == 6**i
def test_Rational_as_content_primitive():
c, p = S.One, S.Zero
assert (c*p).as_content_primitive() == (c, p)
c, p = S.Half, S.One
assert (c*p).as_content_primitive() == (c, p)
def test_Add_as_content_primitive():
assert (x + 2).as_content_primitive() == (1, x + 2)
assert (3*x + 2).as_content_primitive() == (1, 3*x + 2)
assert (3*x + 3).as_content_primitive() == (3, x + 1)
assert (3*x + 6).as_content_primitive() == (3, x + 2)
assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y)
assert (3*x + 3*y).as_content_primitive() == (3, x + y)
assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y)
assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2)
assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2)
assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2)
assert (2*x/3 + 4*y/9).as_content_primitive() == \
(Rational(2, 9), 3*x + 2*y)
assert (2*x/3 + 2.5*y).as_content_primitive() == \
(Rational(1, 3), 2*x + 7.5*y)
# the coefficient may sort to a position other than 0
p = 3 + x + y
assert (2*p).expand().as_content_primitive() == (2, p)
assert (2.0*p).expand().as_content_primitive() == (1, 2.*p)
p *= -1
assert (2*p).expand().as_content_primitive() == (2, p)
def test_Mul_as_content_primitive():
assert (2*x).as_content_primitive() == (2, x)
assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x))
assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \
(18, x*(1 + y)*(x + 1)**2)
assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \
(S.Half, 24*(x + 1)**2*(2*x + 1) + 1)
def test_Pow_as_content_primitive():
assert (x**y).as_content_primitive() == (1, x**y)
assert ((2*x + 2)**y).as_content_primitive() == \
(1, (Mul(2, (x + 1), evaluate=False))**y)
assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3)
def test_issue_5460():
u = Mul(2, (1 + x), evaluate=False)
assert (2 + u).args == (2, u)
def test_product_irrational():
from sympy import I, pi
assert (I*pi).is_irrational is False
# The following used to be deduced from the above bug:
assert (I*pi).is_positive is False
def test_issue_5919():
assert (x/(y*(1 + y))).expand() == x/(y**2 + y)
def test_Mod():
assert Mod(x, 1).func is Mod
assert pi % pi is S.Zero
assert Mod(5, 3) == 2
assert Mod(-5, 3) == 1
assert Mod(5, -3) == -1
assert Mod(-5, -3) == -2
assert type(Mod(3.2, 2, evaluate=False)) == Mod
assert 5 % x == Mod(5, x)
assert x % 5 == Mod(x, 5)
assert x % y == Mod(x, y)
assert (x % y).subs({x: 5, y: 3}) == 2
assert Mod(nan, 1) is nan
assert Mod(1, nan) is nan
assert Mod(nan, nan) is nan
Mod(0, x) == 0
with raises(ZeroDivisionError):
Mod(x, 0)
k = Symbol('k', integer=True)
m = Symbol('m', integer=True, positive=True)
assert (x**m % x).func is Mod
assert (k**(-m) % k).func is Mod
assert k**m % k == 0
assert (-2*k)**m % k == 0
# Float handling
point3 = Float(3.3) % 1
assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1)
assert Mod(-3.3, 1) == 1 - point3
assert Mod(0.7, 1) == Float(0.7)
e = Mod(1.3, 1)
assert comp(e, .3) and e.is_Float
e = Mod(1.3, .7)
assert comp(e, .6) and e.is_Float
e = Mod(1.3, Rational(7, 10))
assert comp(e, .6) and e.is_Float
e = Mod(Rational(13, 10), 0.7)
assert comp(e, .6) and e.is_Float
e = Mod(Rational(13, 10), Rational(7, 10))
assert comp(e, .6) and e.is_Rational
# check that sign is right
r2 = sqrt(2)
r3 = sqrt(3)
for i in [-r3, -r2, r2, r3]:
for j in [-r3, -r2, r2, r3]:
assert verify_numerically(i % j, i.n() % j.n())
for _x in range(4):
for _y in range(9):
reps = [(x, _x), (y, _y)]
assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9
# denesting
t = Symbol('t', real=True)
assert Mod(Mod(x, t), t) == Mod(x, t)
assert Mod(-Mod(x, t), t) == Mod(-x, t)
assert Mod(Mod(x, 2*t), t) == Mod(x, t)
assert Mod(-Mod(x, 2*t), t) == Mod(-x, t)
assert Mod(Mod(x, t), 2*t) == Mod(x, t)
assert Mod(-Mod(x, t), -2*t) == -Mod(x, t)
for i in [-4, -2, 2, 4]:
for j in [-4, -2, 2, 4]:
for k in range(4):
assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j
assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j
# known difference
assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5)
p = symbols('p', positive=True)
assert Mod(2, p + 3) == 2
assert Mod(-2, p + 3) == p + 1
assert Mod(2, -p - 3) == -p - 1
assert Mod(-2, -p - 3) == -2
assert Mod(p + 5, p + 3) == 2
assert Mod(-p - 5, p + 3) == p + 1
assert Mod(p + 5, -p - 3) == -p - 1
assert Mod(-p - 5, -p - 3) == -2
assert Mod(p + 1, p - 1).func is Mod
# handling sums
assert (x + 3) % 1 == Mod(x, 1)
assert (x + 3.0) % 1 == Mod(1.*x, 1)
assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1)
a = Mod(.6*x + y, .3*y)
b = Mod(0.1*y + 0.6*x, 0.3*y)
# Test that a, b are equal, with 1e-14 accuracy in coefficients
eps = 1e-14
assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps
assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps
assert (x + 1) % x == 1 % x
assert (x + y) % x == y % x
assert (x + y + 2) % x == (y + 2) % x
assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x)
assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x)
# gcd extraction
assert (-3*x) % (-2*y) == -Mod(3*x, 2*y)
assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x)
assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x)
assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x)
assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x)
assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x)
assert (12*x) % (2*y) == 2*Mod(6*x, y)
assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y)
assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y)
assert (-2*pi) % (3*pi) == pi
assert (2*x + 2) % (x + 1) == 0
assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1)
assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y)
i = Symbol('i', integer=True)
assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y)
assert Mod(4*i, 4) == 0
# issue 8677
n = Symbol('n', integer=True, positive=True)
assert factorial(n) % n == 0
assert factorial(n + 2) % n == 0
assert (factorial(n + 4) % (n + 5)).func is Mod
# Wilson's theorem
factorial(18042, evaluate=False) % 18043 == 18042
p = Symbol('n', prime=True)
factorial(p - 1) % p == p - 1
factorial(p - 1) % -p == -1
(factorial(3, evaluate=False) % 4).doit() == 2
n = Symbol('n', composite=True, odd=True)
factorial(n - 1) % n == 0
# symbolic with known parity
n = Symbol('n', even=True)
assert Mod(n, 2) == 0
n = Symbol('n', odd=True)
assert Mod(n, 2) == 1
# issue 10963
assert (x**6000%400).args[1] == 400
#issue 13543
assert Mod(Mod(x + 1, 2) + 1 , 2) == Mod(x,2)
assert Mod(Mod(x + 2, 4)*(x + 4), 4) == Mod(x*(x + 2), 4)
assert Mod(Mod(x + 2, 4)*4, 4) == 0
# issue 15493
i, j = symbols('i j', integer=True, positive=True)
assert Mod(3*i, 2) == Mod(i, 2)
assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1)
assert Mod(8*i, 4) == 0
# rewrite
assert Mod(x, y).rewrite(floor) == x - y*floor(x/y)
assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y)
def test_Mod_Pow():
# modular exponentiation
assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer)
assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497)
assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1
assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \
pow(32131231232,9**10**6,10**12)
assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \
pow(33284959323,123**999,11**13)
assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \
pow(78789849597,333**555,12**9)
# modular nested exponentiation
expr = Pow(2, 2, evaluate=False)
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 16
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 6487
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 32191
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 18016
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 5137
expr = Pow(2, 2, evaluate=False)
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 16
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 256
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 6487
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 38281
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 15928
expr = Pow(2, 2, evaluate=False)
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 256
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 9229
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 25708
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 26608
expr = Pow(expr, expr, evaluate=False)
# XXX This used to fail in a nondeterministic way because of overflow
# error.
assert Mod(expr, 3**10) == 1966
def test_Mod_is_integer():
p = Symbol('p', integer=True)
q1 = Symbol('q1', integer=True)
q2 = Symbol('q2', integer=True, nonzero=True)
assert Mod(x, y).is_integer is None
assert Mod(p, q1).is_integer is None
assert Mod(x, q2).is_integer is None
assert Mod(p, q2).is_integer
def test_Mod_is_nonposneg():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, positive=True)
assert (n%3).is_nonnegative
assert Mod(n, -3).is_nonpositive
assert Mod(n, k).is_nonnegative
assert Mod(n, -k).is_nonpositive
assert Mod(k, n).is_nonnegative is None
def test_issue_6001():
A = Symbol("A", commutative=False)
eq = A + A**2
# it doesn't matter whether it's True or False; they should
# just all be the same
assert (
eq.is_commutative ==
(eq + 1).is_commutative ==
(A + 1).is_commutative)
B = Symbol("B", commutative=False)
# Although commutative terms could cancel we return True
# meaning "there are non-commutative symbols; aftersubstitution
# that definition can change, e.g. (A*B).subs(B,A**-1) -> 1
assert (sqrt(2)*A).is_commutative is False
assert (sqrt(2)*A*B).is_commutative is False
def test_polar():
from sympy import polar_lift
p = Symbol('p', polar=True)
x = Symbol('x')
assert p.is_polar
assert x.is_polar is None
assert S.One.is_polar is None
assert (p**x).is_polar is True
assert (x**p).is_polar is None
assert ((2*p)**x).is_polar is True
assert (2*p).is_polar is True
assert (-2*p).is_polar is not True
assert (polar_lift(-2)*p).is_polar is True
q = Symbol('q', polar=True)
assert (p*q)**2 == p**2 * q**2
assert (2*q)**2 == 4 * q**2
assert ((p*q)**x).expand() == p**x * q**x
def test_issue_6040():
a, b = Pow(1, 2, evaluate=False), S.One
assert a != b
assert b != a
assert not (a == b)
assert not (b == a)
def test_issue_6082():
# Comparison is symmetric
assert Basic.compare(Max(x, 1), Max(x, 2)) == \
- Basic.compare(Max(x, 2), Max(x, 1))
# Equal expressions compare equal
assert Basic.compare(Max(x, 1), Max(x, 1)) == 0
# Basic subtypes (such as Max) compare different than standard types
assert Basic.compare(Max(1, x), frozenset((1, x))) != 0
def test_issue_6077():
assert x**2.0/x == x**1.0
assert x/x**2.0 == x**-1.0
assert x*x**2.0 == x**3.0
assert x**1.5*x**2.5 == x**4.0
assert 2**(2.0*x)/2**x == 2**(1.0*x)
assert 2**x/2**(2.0*x) == 2**(-1.0*x)
assert 2**x*2**(2.0*x) == 2**(3.0*x)
assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x)
def test_mul_flatten_oo():
p = symbols('p', positive=True)
n, m = symbols('n,m', negative=True)
x_im = symbols('x_im', imaginary=True)
assert n*oo is -oo
assert n*m*oo is oo
assert p*oo is oo
assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo
def test_add_flatten():
# see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524
a = oo + I*oo
b = oo - I*oo
assert a + b is nan
assert a - b is nan
# FIXME: This evaluates as:
# >>> 1/a
# 0*(oo + oo*I)
# which should not simplify to 0. Should be fixed in Pow.eval
#assert (1/a).simplify() == (1/b).simplify() == 0
a = Pow(2, 3, evaluate=False)
assert a + a == 16
def test_issue_5160_6087_6089_6090():
# issue 6087
assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2)
# issue 6089
A, B, C = symbols('A,B,C', commutative=False)
assert (2.*B*C)**3 == 8.0*(B*C)**3
assert (-2.*B*C)**3 == -8.0*(B*C)**3
assert (-2*B*C)**2 == 4*(B*C)**2
# issue 5160
assert sqrt(-1.0*x) == 1.0*sqrt(-x)
assert sqrt(1.0*x) == 1.0*sqrt(x)
# issue 6090
assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2
def test_float_int_round():
assert int(float(sqrt(10))) == int(sqrt(10))
assert int(pi**1000) % 10 == 2
assert int(Float('1.123456789012345678901234567890e20', '')) == \
int(112345678901234567890)
assert int(Float('1.123456789012345678901234567890e25', '')) == \
int(11234567890123456789012345)
# decimal forces float so it's not an exact integer ending in 000000
assert int(Float('1.123456789012345678901234567890e35', '')) == \
112345678901234567890123456789000192
assert int(Float('123456789012345678901234567890e5', '')) == \
12345678901234567890123456789000000
assert Integer(Float('1.123456789012345678901234567890e20', '')) == \
112345678901234567890
assert Integer(Float('1.123456789012345678901234567890e25', '')) == \
11234567890123456789012345
# decimal forces float so it's not an exact integer ending in 000000
assert Integer(Float('1.123456789012345678901234567890e35', '')) == \
112345678901234567890123456789000192
assert Integer(Float('123456789012345678901234567890e5', '')) == \
12345678901234567890123456789000000
assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', ''))
assert same_and_same_prec(Float('123000e2',''), Float('12300000', ''))
assert int(1 + Rational('.9999999999999999999999999')) == 1
assert int(pi/1e20) == 0
assert int(1 + pi/1e20) == 1
assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2)
assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2)
assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1
raises(TypeError, lambda: float(x))
raises(TypeError, lambda: float(sqrt(-1)))
assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \
12345678901234567891
def test_issue_6611a():
assert Mul.flatten([3**Rational(1, 3),
Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \
([Rational(1, 3), (-1)**Rational(2, 3)], [], None)
def test_denest_add_mul():
# when working with evaluated expressions make sure they denest
eq = x + 1
eq = Add(eq, 2, evaluate=False)
eq = Add(eq, 2, evaluate=False)
assert Add(*eq.args) == x + 5
eq = x*2
eq = Mul(eq, 2, evaluate=False)
eq = Mul(eq, 2, evaluate=False)
assert Mul(*eq.args) == 8*x
# but don't let them denest unecessarily
eq = Mul(-2, x - 2, evaluate=False)
assert 2*eq == Mul(-4, x - 2, evaluate=False)
assert -eq == Mul(2, x - 2, evaluate=False)
def test_mul_coeff():
# It is important that all Numbers be removed from the seq;
# This can be tricky when powers combine to produce those numbers
p = exp(I*pi/3)
assert p**2*x*p*y*p*x*p**2 == x**2*y
def test_mul_zero_detection():
nz = Dummy(real=True, zero=False)
r = Dummy(extended_real=True)
c = Dummy(real=False, complex=True)
c2 = Dummy(real=False, complex=True)
i = Dummy(imaginary=True)
e = nz*r*c
assert e.is_imaginary is None
assert e.is_extended_real is None
e = nz*c
assert e.is_imaginary is None
assert e.is_extended_real is False
e = nz*i*c
assert e.is_imaginary is False
assert e.is_extended_real is None
# check for more than one complex; it is important to use
# uniquely named Symbols to ensure that two factors appear
# e.g. if the symbols have the same name they just become
# a single factor, a power.
e = nz*i*c*c2
assert e.is_imaginary is None
assert e.is_extended_real is None
# _eval_is_extended_real and _eval_is_zero both employ trapping of the
# zero value so args should be tested in both directions and
# TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED
# real is unknown
def test(z, b, e):
if z.is_zero and b.is_finite:
assert e.is_extended_real and e.is_zero
else:
assert e.is_extended_real is None
if b.is_finite:
if z.is_zero:
assert e.is_zero
else:
assert e.is_zero is None
elif b.is_finite is False:
if z.is_zero is None:
assert e.is_zero is None
else:
assert e.is_zero is False
for iz, ib in cartes(*[[True, False, None]]*2):
z = Dummy('z', nonzero=iz)
b = Dummy('f', finite=ib)
e = Mul(z, b, evaluate=False)
test(z, b, e)
z = Dummy('nz', nonzero=iz)
b = Dummy('f', finite=ib)
e = Mul(b, z, evaluate=False)
test(z, b, e)
# real is True
def test(z, b, e):
if z.is_zero and not b.is_finite:
assert e.is_extended_real is None
else:
assert e.is_extended_real is True
for iz, ib in cartes(*[[True, False, None]]*2):
z = Dummy('z', nonzero=iz, extended_real=True)
b = Dummy('b', finite=ib, extended_real=True)
e = Mul(z, b, evaluate=False)
test(z, b, e)
z = Dummy('z', nonzero=iz, extended_real=True)
b = Dummy('b', finite=ib, extended_real=True)
e = Mul(b, z, evaluate=False)
test(z, b, e)
def test_Mul_with_zero_infinite():
zer = Dummy(zero=True)
inf = Dummy(finite=False)
e = Mul(zer, inf, evaluate=False)
assert e.is_extended_positive is None
assert e.is_hermitian is None
e = Mul(inf, zer, evaluate=False)
assert e.is_extended_positive is None
assert e.is_hermitian is None
def test_Mul_does_not_cancel_infinities():
a, b = symbols('a b')
assert ((zoo + 3*a)/(3*a + zoo)) is nan
assert ((b - oo)/(b - oo)) is nan
# issue 13904
expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b))
assert expr.subs(b, a) is nan
def test_Mul_does_not_distribute_infinity():
a, b = symbols('a b')
assert ((1 + I)*oo).is_Mul
assert ((a + b)*(-oo)).is_Mul
assert ((a + 1)*zoo).is_Mul
assert ((1 + I)*oo).is_finite is False
z = (1 + I)*oo
assert ((1 - I)*z).expand() is oo
def test_issue_8247_8354():
from sympy import tan
z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert z.is_positive is False # it's 0
z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) +
12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) +
174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''')
assert z.is_positive is False # it's 0
z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \
sqrt(3)*(-3 + 4*cos(19*pi/90)**2)
assert z.is_positive is not True # it's zero and it shouldn't hang
z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) +
29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 +
72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) +
1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) -
2) - 2*2**(1/3))**2''')
assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough)
def test_Add_is_zero():
x, y = symbols('x y', zero=True)
assert (x + y).is_zero
# Issue 15873
e = -2*I + (1 + I)**2
assert e.is_zero is None
def test_issue_14392():
assert (sin(zoo)**2).as_real_imag() == (nan, nan)
def test_divmod():
assert divmod(x, y) == (x//y, x % y)
assert divmod(x, 3) == (x//3, x % 3)
assert divmod(3, x) == (3//x, 3 % x)
def test__neg__():
assert -(x*y) == -x*y
assert -(-x*y) == x*y
assert -(1.*x) == -1.*x
assert -(-1.*x) == 1.*x
assert -(2.*x) == -2.*x
assert -(-2.*x) == 2.*x
with distribute(False):
eq = -(x + y)
assert eq.is_Mul and eq.args == (-1, x + y)
def test_issue_18507():
assert Mul(zoo, zoo, 0) is nan
|
d26be338ee50e63285353a2d115b42098b59a01b4c2113afcef18000e5d0e051 | """Implementation of :class:`AlgebraicField` class. """
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.polyclasses import ANP
from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed
from sympy.utilities import public
@public
class AlgebraicField(Field, CharacteristicZero, SimpleDomain):
"""A class for representing algebraic number fields. """
dtype = ANP
is_AlgebraicField = is_Algebraic = True
is_Numerical = True
has_assoc_Ring = False
has_assoc_Field = True
def __init__(self, dom, *ext):
if not dom.is_QQ:
raise DomainError("ground domain must be a rational field")
from sympy.polys.numberfields import to_number_field
if len(ext) == 1 and isinstance(ext[0], tuple):
self.orig_ext = ext[0][1:]
else:
self.orig_ext = ext
self.ext = to_number_field(ext)
self.mod = self.ext.minpoly.rep
self.domain = self.dom = dom
self.ngens = 1
self.symbols = self.gens = (self.ext,)
self.unit = self([dom(1), dom(0)])
self.zero = self.dtype.zero(self.mod.rep, dom)
self.one = self.dtype.one(self.mod.rep, dom)
def new(self, element):
return self.dtype(element, self.mod.rep, self.dom)
def __str__(self):
return str(self.dom) + '<' + str(self.ext) + '>'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.dom, self.ext))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, AlgebraicField) and \
self.dtype == other.dtype and self.ext == other.ext
def algebraic_field(self, *extension):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
return AlgebraicField(self.dom, *((self.ext,) + extension))
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
# Precompute a converter to be reused:
if not hasattr(self, '_converter'):
self._converter = _make_converter(self)
return self._converter(a)
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
try:
return self([self.dom.from_sympy(a)])
except CoercionFailed:
pass
from sympy.polys.numberfields import to_number_field
try:
return self(to_number_field(a, self.ext).native_coeffs())
except (NotAlgebraic, IsomorphismFailed):
raise CoercionFailed(
"%s is not a valid algebraic number in %s" % (a, self))
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return self.dom.is_positive(a.LC())
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return self.dom.is_negative(a.LC())
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return self.dom.is_nonpositive(a.LC())
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return self.dom.is_nonnegative(a.LC())
def numer(self, a):
"""Returns numerator of ``a``. """
return a
def denom(self, a):
"""Returns denominator of ``a``. """
return self.one
def from_AlgebraicField(K1, a, K0):
"""Convert AlgebraicField element 'a' to another AlgebraicField """
return K1.from_sympy(K0.to_sympy(a))
def from_GaussianIntegerRing(K1, a, K0):
"""Convert a GaussianInteger element 'a' to ``dtype``. """
return K1.from_sympy(K0.to_sympy(a))
def from_GaussianRationalField(K1, a, K0):
"""Convert a GaussianRational element 'a' to ``dtype``. """
return K1.from_sympy(K0.to_sympy(a))
def _make_converter(K):
"""Construct the converter to convert back to Expr"""
# Precompute the effect of converting to sympy and expanding expressions
# like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every
# conversion from K to Expr is slow. Here we compute the expansions for
# each power of the generator and collect together the resulting algebraic
# terms and the rational coefficients into a matrix.
from sympy import Add, S
gen = K.ext.as_expr()
todom = K.dom.from_sympy
# We'll let Expr compute the expansions. We won't make any presumptions
# about what this results in except that it is QQ-linear in some terms
# that we will call algebraics. The final result will be expressed in
# terms of those.
powers = [S.One, gen]
for n in range(2, K.mod.degree()):
powers.append((gen * powers[-1]).expand())
# Collect the rational coefficients and algebraic Expr that can
# map the ANP coefficients into an expanded sympy expression
terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers]
algebraics = set().union(*terms)
matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics]
# Create a function to do the conversion efficiently:
def converter(a):
"""Convert a to Expr using converter"""
from sympy import Add, Mul
ai = a.rep[::-1]
tosympy = K.dom.to_sympy
coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix]
coeffs_sympy = [tosympy(c) for c in coeffs_dom]
res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics)))
return res
return converter
|
f43ec63c6cb78ecc6ab06299c6f8d0dcbcddc46929b621dd709f5d56a51ad10f | """Implementation of :class:`QuotientRing` class."""
from sympy.polys.agca.modules import FreeModuleQuotientRing
from sympy.polys.domains.ring import Ring
from sympy.polys.polyerrors import NotReversible, CoercionFailed
from sympy.utilities import public
# TODO
# - successive quotients (when quotient ideals are implemented)
# - poly rings over quotients?
# - division by non-units in integral domains?
@public
class QuotientRingElement:
"""
Class representing elements of (commutative) quotient rings.
Attributes:
- ring - containing ring
- data - element of ring.ring (i.e. base ring) representing self
"""
def __init__(self, ring, data):
self.ring = ring
self.data = data
def __str__(self):
from sympy import sstr
return sstr(self.data) + " + " + str(self.ring.base_ideal)
__repr__ = __str__
def __bool__(self):
return not self.ring.is_zero(self)
def __add__(self, om):
if not isinstance(om, self.__class__) or om.ring != self.ring:
try:
om = self.ring.convert(om)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring(self.data + om.data)
__radd__ = __add__
def __neg__(self):
return self.ring(self.data*self.ring.ring.convert(-1))
def __sub__(self, om):
return self.__add__(-om)
def __rsub__(self, om):
return (-self).__add__(om)
def __mul__(self, o):
if not isinstance(o, self.__class__):
try:
o = self.ring.convert(o)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring(self.data*o.data)
__rmul__ = __mul__
def __rtruediv__(self, o):
return self.ring.revert(self)*o
def __truediv__(self, o):
if not isinstance(o, self.__class__):
try:
o = self.ring.convert(o)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring.revert(o)*self
def __pow__(self, oth):
if oth < 0:
return self.ring.revert(self) ** -oth
return self.ring(self.data ** oth)
def __eq__(self, om):
if not isinstance(om, self.__class__) or om.ring != self.ring:
return False
return self.ring.is_zero(self - om)
def __ne__(self, om):
return not self == om
class QuotientRing(Ring):
"""
Class representing (commutative) quotient rings.
You should not usually instantiate this by hand, instead use the constructor
from the base ring in the construction.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**3 + 1)
>>> QQ.old_poly_ring(x).quotient_ring(I)
QQ[x]/<x**3 + 1>
Shorter versions are possible:
>>> QQ.old_poly_ring(x)/I
QQ[x]/<x**3 + 1>
>>> QQ.old_poly_ring(x)/[x**3 + 1]
QQ[x]/<x**3 + 1>
Attributes:
- ring - the base ring
- base_ideal - the ideal used to form the quotient
"""
has_assoc_Ring = True
has_assoc_Field = False
dtype = QuotientRingElement
def __init__(self, ring, ideal):
if not ideal.ring == ring:
raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal))
self.ring = ring
self.base_ideal = ideal
self.zero = self(self.ring.zero)
self.one = self(self.ring.one)
def __str__(self):
return str(self.ring) + "/" + str(self.base_ideal)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal))
def new(self, a):
"""Construct an element of `self` domain from `a`. """
if not isinstance(a, self.ring.dtype):
a = self.ring(a)
# TODO optionally disable reduction?
return self.dtype(self, self.base_ideal.reduce_element(a))
def __eq__(self, other):
"""Returns `True` if two domains are equivalent. """
return isinstance(other, QuotientRing) and \
self.ring == other.ring and self.base_ideal == other.base_ideal
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return K1(K1.ring.convert(a, K0))
from_QQ_python = from_ZZ_python
from_ZZ_gmpy = from_ZZ_python
from_QQ_gmpy = from_ZZ_python
from_RealField = from_ZZ_python
from_GlobalPolynomialRing = from_ZZ_python
from_FractionField = from_ZZ_python
def from_sympy(self, a):
return self(self.ring.from_sympy(a))
def to_sympy(self, a):
return self.ring.to_sympy(a.data)
def from_QuotientRing(self, a, K0):
if K0 == self:
return a
def poly_ring(self, *gens):
"""Returns a polynomial ring, i.e. `K[X]`. """
raise NotImplementedError('nested domains not allowed')
def frac_field(self, *gens):
"""Returns a fraction field, i.e. `K(X)`. """
raise NotImplementedError('nested domains not allowed')
def revert(self, a):
"""
Compute a**(-1), if possible.
"""
I = self.ring.ideal(a.data) + self.base_ideal
try:
return self(I.in_terms_of_generators(1)[0])
except ValueError: # 1 not in I
raise NotReversible('%s not a unit in %r' % (a, self))
def is_zero(self, a):
return self.base_ideal.contains(a.data)
def free_module(self, rank):
"""
Generate a free module of rank ``rank`` over ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
(QQ[x]/<x**2 + 1>)**2
"""
return FreeModuleQuotientRing(self, rank)
|
765c45dad7e87d91857d2ecd5b55e394039b78352337b68220dd5efa1c7080cc | """Implementation of :class:`ExpressionDomain` class. """
from sympy.core import sympify, SympifyError
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.polyutils import PicklableWithSlots
from sympy.utilities import public
eflags = dict(deep=False, mul=True, power_exp=False, power_base=False,
basic=False, multinomial=False, log=False)
@public
class ExpressionDomain(Field, CharacteristicZero, SimpleDomain):
"""A class for arbitrary expressions. """
is_SymbolicDomain = is_EX = True
class Expression(PicklableWithSlots):
"""An arbitrary expression. """
__slots__ = ('ex',)
def __init__(self, ex):
if not isinstance(ex, self.__class__):
self.ex = sympify(ex)
else:
self.ex = ex.ex
def __repr__(f):
return 'EX(%s)' % repr(f.ex)
def __str__(f):
return 'EX(%s)' % str(f.ex)
def __hash__(self):
return hash((self.__class__.__name__, self.ex))
def as_expr(f):
return f.ex
def numer(f):
return f.__class__(f.ex.as_numer_denom()[0])
def denom(f):
return f.__class__(f.ex.as_numer_denom()[1])
def simplify(f, ex):
return f.__class__(ex.cancel().expand(**eflags))
def __abs__(f):
return f.__class__(abs(f.ex))
def __neg__(f):
return f.__class__(-f.ex)
def _to_ex(f, g):
try:
return f.__class__(g)
except SympifyError:
return None
def __add__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex + g.ex)
else:
return NotImplemented
def __radd__(f, g):
return f.simplify(f.__class__(g).ex + f.ex)
def __sub__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex - g.ex)
else:
return NotImplemented
def __rsub__(f, g):
return f.simplify(f.__class__(g).ex - f.ex)
def __mul__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex*g.ex)
else:
return NotImplemented
def __rmul__(f, g):
return f.simplify(f.__class__(g).ex*f.ex)
def __pow__(f, n):
n = f._to_ex(n)
if n is not None:
return f.simplify(f.ex**n.ex)
else:
return NotImplemented
def __truediv__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex/g.ex)
else:
return NotImplemented
def __rtruediv__(f, g):
return f.simplify(f.__class__(g).ex/f.ex)
def __eq__(f, g):
return f.ex == f.__class__(g).ex
def __ne__(f, g):
return not f == g
def __bool__(f):
return not f.ex.is_zero
def gcd(f, g):
from sympy.polys import gcd
return f.__class__(gcd(f.ex, f.__class__(g).ex))
def lcm(f, g):
from sympy.polys import lcm
return f.__class__(lcm(f.ex, f.__class__(g).ex))
dtype = Expression
zero = Expression(0)
one = Expression(1)
rep = 'EX'
has_assoc_Ring = False
has_assoc_Field = True
def __init__(self):
pass
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return a.as_expr()
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
return self.dtype(a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_GaussianIntegerRing(K1, a, K0):
"""Convert a ``GaussianRational`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_GaussianRationalField(K1, a, K0):
"""Convert a ``GaussianRational`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_PolynomialRing(K1, a, K0):
"""Convert a ``DMP`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_FractionField(K1, a, K0):
"""Convert a ``DMF`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_ExpressionDomain(K1, a, K0):
"""Convert a ``EX`` object to ``dtype``. """
return a
def get_ring(self):
"""Returns a ring associated with ``self``. """
return self # XXX: EX is not a ring but we don't have much choice here.
def get_field(self):
"""Returns a field associated with ``self``. """
return self
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return a.ex.as_coeff_mul()[0].is_positive
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return a.ex.could_extract_minus_sign()
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return a.ex.as_coeff_mul()[0].is_nonpositive
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return a.ex.as_coeff_mul()[0].is_nonnegative
def numer(self, a):
"""Returns numerator of ``a``. """
return a.numer()
def denom(self, a):
"""Returns denominator of ``a``. """
return a.denom()
def gcd(self, a, b):
return self(1)
def lcm(self, a, b):
return a.lcm(b)
|
8b227ba99f4cca18c11bc980360861b0ebfa568907a753ffe6bd5c68e6318bae | """Ground types for various mathematical domains in SymPy. """
import builtins
from sympy.core.compatibility import HAS_GMPY
PythonInteger = builtins.int
PythonReal = builtins.float
PythonComplex = builtins.complex
from .pythonrational import PythonRational
from sympy.core.numbers import (
igcdex as python_gcdex,
igcd2 as python_gcd,
ilcm as python_lcm,
)
from sympy import (
Float as SymPyReal,
Integer as SymPyInteger,
Rational as SymPyRational,
)
if HAS_GMPY == 1:
from gmpy import (
mpz as GMPYInteger,
mpq as GMPYRational,
fac as gmpy_factorial,
numer as gmpy_numer,
denom as gmpy_denom,
gcdext as gmpy_gcdex,
gcd as gmpy_gcd,
lcm as gmpy_lcm,
sqrt as gmpy_sqrt,
qdiv as gmpy_qdiv,
)
elif HAS_GMPY == 2:
from gmpy2 import (
mpz as GMPYInteger,
mpq as GMPYRational,
fac as gmpy_factorial,
numer as gmpy_numer,
denom as gmpy_denom,
gcdext as gmpy_gcdex,
gcd as gmpy_gcd,
lcm as gmpy_lcm,
isqrt as gmpy_sqrt,
qdiv as gmpy_qdiv,
)
else:
class _GMPYInteger:
def __init__(self, obj):
pass
class _GMPYRational:
def __init__(self, obj):
pass
GMPYInteger = _GMPYInteger
GMPYRational = _GMPYRational
gmpy_factorial = None
gmpy_numer = None
gmpy_denom = None
gmpy_gcdex = None
gmpy_gcd = None
gmpy_lcm = None
gmpy_sqrt = None
gmpy_qdiv = None
import mpmath.libmp as mlib
def python_sqrt(n):
return int(mlib.isqrt(n))
def python_factorial(n):
return int(mlib.ifac(n))
__all__ = [
'PythonInteger', 'PythonReal', 'PythonComplex',
'PythonRational',
'python_gcdex', 'python_gcd', 'python_lcm',
'SymPyReal', 'SymPyInteger', 'SymPyRational',
'GMPYInteger', 'GMPYRational', 'gmpy_factorial', 'gmpy_numer',
'gmpy_denom', 'gmpy_gcdex', 'gmpy_gcd', 'gmpy_lcm', 'gmpy_sqrt',
'gmpy_qdiv',
'GMPYInteger', 'GMPYRational',
'mlib',
'python_sqrt', 'python_factorial'
]
|
cbe176110ce2c795bcd22f3b3245d8c7e3685a4a79df42a3df9ca90cdd1d971c | """Test sparse polynomials. """
from functools import reduce
from operator import add, mul
from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement
from sympy.polys.fields import field, FracField
from sympy.polys.domains import ZZ, QQ, RR, FF, EX
from sympy.polys.orderings import lex, grlex
from sympy.polys.polyerrors import GeneratorsError, \
ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed
from sympy.testing.pytest import raises
from sympy.core import Symbol, symbols
from sympy import sqrt, pi, oo
def test_PolyRing___init__():
x, y, z, t = map(Symbol, "xyzt")
assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3
assert len(PolyRing(x, ZZ, lex).gens) == 1
assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3
assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3
assert len(PolyRing("", ZZ, lex).gens) == 0
assert len(PolyRing([], ZZ, lex).gens) == 0
raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex))
assert PolyRing("x", ZZ[t], lex).domain == ZZ[t]
assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t]
assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t]
raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex))
_lex = Symbol("lex")
assert PolyRing("x", ZZ, lex).order == lex
assert PolyRing("x", ZZ, _lex).order == lex
assert PolyRing("x", ZZ, 'lex').order == lex
R1 = PolyRing("x,y", ZZ, lex)
R2 = PolyRing("x,y", ZZ, lex)
R3 = PolyRing("x,y,z", ZZ, lex)
assert R1.x == R1.gens[0]
assert R1.y == R1.gens[1]
assert R1.x == R2.x
assert R1.y == R2.y
assert R1.x != R3.x
assert R1.y != R3.y
def test_PolyRing___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(R)
def test_PolyRing___eq__():
assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0]
assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0]
assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0]
def test_PolyRing_ring_new():
R, x, y, z = ring("x,y,z", QQ)
assert R.ring_new(7) == R(7)
assert R.ring_new(7*x*y*z) == 7*x*y*z
f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6
assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f
assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f
assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f
R, = ring("", QQ)
assert R.ring_new([((), 7)]) == R(7)
def test_PolyRing_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R.drop(x) == PolyRing("y,z", ZZ, lex)
assert R.drop(y) == PolyRing("x,z", ZZ, lex)
assert R.drop(z) == PolyRing("x,y", ZZ, lex)
assert R.drop(0) == PolyRing("y,z", ZZ, lex)
assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex)
assert R.drop(0).drop(0).drop(0) == ZZ
assert R.drop(1) == PolyRing("x,z", ZZ, lex)
assert R.drop(2) == PolyRing("x,y", ZZ, lex)
assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex)
assert R.drop(2).drop(1).drop(0) == ZZ
raises(ValueError, lambda: R.drop(3))
raises(ValueError, lambda: R.drop(x).drop(y))
def test_PolyRing___getitem__():
R, x,y,z = ring("x,y,z", ZZ)
assert R[0:] == PolyRing("x,y,z", ZZ, lex)
assert R[1:] == PolyRing("y,z", ZZ, lex)
assert R[2:] == PolyRing("z", ZZ, lex)
assert R[3:] == ZZ
def test_PolyRing_is_():
R = PolyRing("x", QQ, lex)
assert R.is_univariate is True
assert R.is_multivariate is False
R = PolyRing("x,y,z", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is True
R = PolyRing("", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is False
def test_PolyRing_add():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.add(F) == reduce(add, F) == 4*x**2 + 24
R, = ring("", ZZ)
assert R.add([2, 5, 7]) == 14
def test_PolyRing_mul():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945
R, = ring("", ZZ)
assert R.mul([2, 3, 5]) == 30
def test_sring():
x, y, z, t = symbols("x,y,z,t")
R = PolyRing("x,y,z", ZZ, lex)
assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z)
R = PolyRing("x,y,z", QQ, lex)
assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3)
assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3])
Rt = PolyRing("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z)
Rt = PolyRing("t", QQ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3)
Rt = FracField("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3)
r = sqrt(2) - sqrt(3)
R, a = sring(r, extension=True)
assert R.domain == QQ.algebraic_field(sqrt(2) + sqrt(3))
assert R.gens == ()
assert a == R.domain.from_sympy(r)
def test_PolyElement___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(x*y*z)
def test_PolyElement___eq__():
R, x, y = ring("x,y", ZZ, lex)
assert ((x*y + 5*x*y) == 6) == False
assert ((x*y + 5*x*y) == 6*x*y) == True
assert (6 == (x*y + 5*x*y)) == False
assert (6*x*y == (x*y + 5*x*y)) == True
assert ((x*y - x*y) == 0) == True
assert (0 == (x*y - x*y)) == True
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y + 5*x*y) != 6) == True
assert ((x*y + 5*x*y) != 6*x*y) == False
assert (6 != (x*y + 5*x*y)) == True
assert (6*x*y != (x*y + 5*x*y)) == False
assert ((x*y - x*y) != 0) == False
assert (0 != (x*y - x*y)) == False
assert ((x*y - x*y) != 1) == True
assert (1 != (x*y - x*y)) == True
assert R.one == QQ(1, 1) == R.one
assert R.one == 1 == R.one
Rt, t = ring("t", ZZ)
R, x, y = ring("x,y", Rt)
assert (t**3*x/x == t**3) == True
assert (t**3*x/x == t**4) == False
def test_PolyElement__lt_le_gt_ge__():
R, x, y = ring("x,y", ZZ)
assert R(1) < x < x**2 < x**3
assert R(1) <= x <= x**2 <= x**3
assert x**3 > x**2 > x > R(1)
assert x**3 >= x**2 >= x >= R(1)
def test_PolyElement_copy():
R, x, y, z = ring("x,y,z", ZZ)
f = x*y + 3*z
g = f.copy()
assert f == g
g[(1, 1, 1)] = 7
assert f != g
def test_PolyElement_as_expr():
R, x, y, z = ring("x,y,z", ZZ)
f = 3*x**2*y - x*y*z + 7*z**3 + 1
X, Y, Z = R.symbols
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
R, = ring("", ZZ)
R(3).as_expr() == 3
def test_PolyElement_from_expr():
x, y, z = symbols("x,y,z")
R, X, Y, Z = ring((x, y, z), ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
f = R.from_expr(x)
assert f == X and isinstance(f, R.dtype)
f = R.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, R.dtype)
f = R.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype)
f = R.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype)
raises(ValueError, lambda: R.from_expr(1/x))
raises(ValueError, lambda: R.from_expr(2**x))
raises(ValueError, lambda: R.from_expr(7*x + sqrt(2)))
R, = ring("", ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
def test_PolyElement_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degree() is -oo
assert R(1).degree() == 0
assert (x + 1).degree() == 1
assert (2*y**3 + z).degree() == 0
assert (x*y**3 + z).degree() == 1
assert (x**5*y**3 + z).degree() == 5
assert R(0).degree(x) is -oo
assert R(1).degree(x) == 0
assert (x + 1).degree(x) == 1
assert (2*y**3 + z).degree(x) == 0
assert (x*y**3 + z).degree(x) == 1
assert (7*x**5*y**3 + z).degree(x) == 5
assert R(0).degree(y) is -oo
assert R(1).degree(y) == 0
assert (x + 1).degree(y) == 0
assert (2*y**3 + z).degree(y) == 3
assert (x*y**3 + z).degree(y) == 3
assert (7*x**5*y**3 + z).degree(y) == 3
assert R(0).degree(z) is -oo
assert R(1).degree(z) == 0
assert (x + 1).degree(z) == 0
assert (2*y**3 + z).degree(z) == 1
assert (x*y**3 + z).degree(z) == 1
assert (7*x**5*y**3 + z).degree(z) == 1
R, = ring("", ZZ)
assert R(0).degree() is -oo
assert R(1).degree() == 0
def test_PolyElement_tail_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degree() is -oo
assert R(1).tail_degree() == 0
assert (x + 1).tail_degree() == 0
assert (2*y**3 + x**3*z).tail_degree() == 0
assert (x*y**3 + x**3*z).tail_degree() == 1
assert (x**5*y**3 + x**3*z).tail_degree() == 3
assert R(0).tail_degree(x) is -oo
assert R(1).tail_degree(x) == 0
assert (x + 1).tail_degree(x) == 0
assert (2*y**3 + x**3*z).tail_degree(x) == 0
assert (x*y**3 + x**3*z).tail_degree(x) == 1
assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3
assert R(0).tail_degree(y) is -oo
assert R(1).tail_degree(y) == 0
assert (x + 1).tail_degree(y) == 0
assert (2*y**3 + x**3*z).tail_degree(y) == 0
assert (x*y**3 + x**3*z).tail_degree(y) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0
assert R(0).tail_degree(z) is -oo
assert R(1).tail_degree(z) == 0
assert (x + 1).tail_degree(z) == 0
assert (2*y**3 + x**3*z).tail_degree(z) == 0
assert (x*y**3 + x**3*z).tail_degree(z) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0
R, = ring("", ZZ)
assert R(0).tail_degree() is -oo
assert R(1).tail_degree() == 0
def test_PolyElement_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degrees() == (-oo, -oo, -oo)
assert R(1).degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2)
def test_PolyElement_tail_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degrees() == (-oo, -oo, -oo)
assert R(1).tail_degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0)
def test_PolyElement_coeff():
R, x, y, z = ring("x,y,z", ZZ, lex)
f = 3*x**2*y - x*y*z + 7*z**3 + 23
assert f.coeff(1) == 23
raises(ValueError, lambda: f.coeff(3))
assert f.coeff(x) == 0
assert f.coeff(y) == 0
assert f.coeff(z) == 0
assert f.coeff(x**2*y) == 3
assert f.coeff(x*y*z) == -1
assert f.coeff(z**3) == 7
raises(ValueError, lambda: f.coeff(3*x**2*y))
raises(ValueError, lambda: f.coeff(-x*y*z))
raises(ValueError, lambda: f.coeff(7*z**3))
R, = ring("", ZZ)
R(3).coeff(1) == 3
def test_PolyElement_LC():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LC == QQ(0)
assert (QQ(1,2)*x).LC == QQ(1, 2)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4)
def test_PolyElement_LM():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LM == (0, 0)
assert (QQ(1,2)*x).LM == (1, 0)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1)
def test_PolyElement_LT():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LT == ((0, 0), QQ(0))
assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2))
assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4))
R, = ring("", ZZ)
assert R(0).LT == ((), 0)
assert R(1).LT == ((), 1)
def test_PolyElement_leading_monom():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_monom() == 0
assert (QQ(1,2)*x).leading_monom() == x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y
def test_PolyElement_leading_term():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_term() == 0
assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y
def test_PolyElement_terms():
R, x,y,z = ring("x,y,z", QQ)
terms = (x**2/3 + y**3/4 + z**4/5).terms()
assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
R, = ring("", ZZ)
assert R(3).terms() == [((), 3)]
def test_PolyElement_monoms():
R, x,y,z = ring("x,y,z", QQ)
monoms = (x**2/3 + y**3/4 + z**4/5).monoms()
assert monoms == [(2,0,0), (0,3,0), (0,0,4)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
def test_PolyElement_coeffs():
R, x,y,z = ring("x,y,z", QQ)
coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs()
assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1]
assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
assert f.coeffs(lex) == f.coeffs('lex') == [2, 1]
def test_PolyElement___add__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3}
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u}
assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u}
assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1}
assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u}
assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u}
raises(TypeError, lambda: t + x)
raises(TypeError, lambda: x + t)
raises(TypeError, lambda: t + u)
raises(TypeError, lambda: u + t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)}
def test_PolyElement___sub__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3}
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u}
assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1}
assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u}
assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u}
raises(TypeError, lambda: t - x)
raises(TypeError, lambda: x - t)
raises(TypeError, lambda: t - u)
raises(TypeError, lambda: u - t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)}
def test_PolyElement___mul__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1}
raises(TypeError, lambda: t*x + z)
raises(TypeError, lambda: x*t + z)
raises(TypeError, lambda: t*u + z)
raises(TypeError, lambda: u*t + z)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)}
def test_PolyElement___truediv__():
R, x,y,z = ring("x,y,z", ZZ)
assert (2*x**2 - 4)/2 == x**2 - 2
assert (2*x**2 - 3)/2 == x**2
assert (x**2 - 1).quo(x) == x
assert (x**2 - x).quo(x) == x - 1
assert (x**2 - 1)/x == x - x**(-1)
assert (x**2 - x)/x == x - 1
assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2
assert (x**2 - 1).quo(2*x) == 0
assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x
R, x,y,z = ring("x,y,z", ZZ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0
R, x,y,z = ring("x,y,z", QQ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1}
raises(TypeError, lambda: u/(u**2*x + u))
raises(TypeError, lambda: t/x)
raises(TypeError, lambda: x/t)
raises(TypeError, lambda: t/u)
raises(TypeError, lambda: u/t)
R, x = ring("x", ZZ)
f, g = x**2 + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x, y = ring("x,y", ZZ)
f, g = x*y + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x = ring("x", ZZ)
f, g = x**2 + 1, 2*x - 4
q, r = R(0), x**2 + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3
q, r = 5*x**2 - 6*x, 20*x + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9
q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x = ring("x", QQ)
f, g = x**2 + 1, 2*x - 4
q, r = x/2 + 1, R(5)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", QQ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = x/2 + y/2, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
def test_PolyElement___pow__():
R, x = ring("x", ZZ, grlex)
f = 2*x + 3
assert f**0 == 1
assert f**1 == f
raises(ValueError, lambda: f**(-1))
assert x**(-1) == x**(-1)
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9
assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81
assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243
R, x,y,z = ring("x,y,z", ZZ, grlex)
f = x**3*y - 2*x*y**2 - 3*z + 1
g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g
R, t = ring("t", ZZ)
f = -11200*t**4 - 2604*t**2 + 49
g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \
+ 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \
+ 92413760096*t**4 - 1225431984*t**2 + 5764801
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g
def test_PolyElement_div():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
q = x**2 - 9*x - 27
r = -123
assert f.div([g]) == ([q], r)
R, x = ring("x", ZZ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(1)]) == ([f], 0)
R, x = ring("x", QQ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0)
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0)
assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8)
f = x - 1
g = y - 1
assert f.div([g]) == ([0], f)
f = x*y**2 + 1
G = [x*y + 1, y + 1]
Q = [y, -1]
r = 2
assert f.div(G) == (Q, r)
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
Q = [x + y, 1]
r = x + y + 1
assert f.div(G) == (Q, r)
G = [y**2 - 1, x*y - 1]
Q = [x + 1, x]
r = 2*x + 1
assert f.div(G) == (Q, r)
R, = ring("", ZZ)
assert R(3).div(R(2)) == (0, 3)
R, = ring("", QQ)
assert R(3).div(R(2)) == (QQ(3, 2), 0)
def test_PolyElement_rem():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
r = -123
assert f.rem([g]) == f.div([g])[1] == r
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.rem([R(2)]) == f.div([R(2)])[1] == 0
assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8
f = x - 1
g = y - 1
assert f.rem([g]) == f.div([g])[1] == f
f = x*y**2 + 1
G = [x*y + 1, y + 1]
r = 2
assert f.rem(G) == f.div(G)[1] == r
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
r = x + y + 1
assert f.rem(G) == f.div(G)[1] == r
G = [y**2 - 1, x*y - 1]
r = 2*x + 1
assert f.rem(G) == f.div(G)[1] == r
def test_PolyElement_deflate():
R, x = ring("x", ZZ)
assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1])
R, x,y = ring("x,y", ZZ)
assert R(0).deflate(R(0)) == ((1, 1), [0, 0])
assert R(1).deflate(R(0)) == ((1, 1), [1, 0])
assert R(1).deflate(R(2)) == ((1, 1), [1, 2])
assert R(1).deflate(2*y) == ((1, 1), [1, 2*y])
assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y])
assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y])
assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y])
f = x**4*y**2 + x**2*y + 1
g = x**2*y**3 + x**2*y + 1
assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1])
def test_PolyElement_clear_denoms():
R, x,y = ring("x,y", QQ)
assert R(1).clear_denoms() == (ZZ(1), 1)
assert R(7).clear_denoms() == (ZZ(1), 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x)
assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x)
rQQ, x,t = ring("x,t", QQ, lex)
rZZ, X,T = ring("x,t", ZZ, lex)
F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7
- QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6
- QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5
- QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4
- QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3
- QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2
- QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t
- QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140),
t**8 + QQ(693749860237914515552,67859264524169150569)*t**7
+ QQ(27761407182086143225024,610733380717522355121)*t**6
+ QQ(7785127652157884044288,67859264524169150569)*t**5
+ QQ(36567075214771261409792,203577793572507451707)*t**4
+ QQ(36336335165196147384320,203577793572507451707)*t**3
+ QQ(7452455676042754048000,67859264524169150569)*t**2
+ QQ(2593331082514399232000,67859264524169150569)*t
+ QQ(390399197427343360000,67859264524169150569)]
G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X -
160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 -
1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 -
5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 -
10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 -
13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 -
9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 -
3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T -
632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000,
610733380717522355121*T**8 +
6243748742141230639968*T**7 +
27761407182086143225024*T**6 +
70066148869420956398592*T**5 +
109701225644313784229376*T**4 +
109009005495588442152960*T**3 +
67072101084384786432000*T**2 +
23339979742629593088000*T +
3513592776846090240000]
assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G
def test_PolyElement_cofactors():
R, x, y = ring("x,y", ZZ)
f, g = R(0), R(0)
assert f.cofactors(g) == (0, 0, 0)
f, g = R(2), R(0)
assert f.cofactors(g) == (2, 1, 0)
f, g = R(-2), R(0)
assert f.cofactors(g) == (2, -1, 0)
f, g = R(0), R(-2)
assert f.cofactors(g) == (2, 0, -1)
f, g = R(0), 2*x + 4
assert f.cofactors(g) == (2*x + 4, 0, 1)
f, g = 2*x + 4, R(0)
assert f.cofactors(g) == (2*x + 4, 1, 0)
f, g = R(2), R(2)
assert f.cofactors(g) == (2, 1, 1)
f, g = R(-2), R(2)
assert f.cofactors(g) == (2, -1, 1)
f, g = R(2), R(-2)
assert f.cofactors(g) == (2, 1, -1)
f, g = R(-2), R(-2)
assert f.cofactors(g) == (2, -1, -1)
f, g = x**2 + 2*x + 1, R(1)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1)
f, g = x**2 + 2*x + 1, R(2)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2)
f, g = 2*x**2 + 4*x + 2, R(2)
assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1)
f, g = R(2), 2*x**2 + 4*x + 2
assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1)
f, g = 2*x**2 + 4*x + 2, x + 1
assert f.cofactors(g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert f.cofactors(g) == (x + 1, 1, 2*x + 2)
R, x, y, z, t = ring("x,y,z,t", ZZ)
f, g = t**2 + 2*t + 1, 2*t + 2
assert f.cofactors(g) == (t + 1, t + 1, 2)
f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1
h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1
assert f.cofactors(g) == (h, cff, cfg)
assert g.cofactors(f) == (h, cfg, cff)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
h = x + 1
assert f.cofactors(g) == (h, g, QQ(1,2))
assert g.cofactors(f) == (h, QQ(1,2), g)
R, x, y = ring("x,y", RR)
f = 2.1*x*y**2 - 2.1*x*y + 2.1*x
g = 2.1*x**3
h = 1.0*x
assert f.cofactors(g) == (h, f/h, g/h)
assert g.cofactors(f) == (h, g/h, f/h)
def test_PolyElement_gcd():
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
assert f.gcd(g) == x + 1
def test_PolyElement_cancel():
R, x, y = ring("x,y", ZZ)
f = 2*x**3 + 4*x**2 + 2*x
g = 3*x**2 + 3*x
F = 2*x + 2
G = 3
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x
g = QQ(1,3)*x**2 + QQ(1,3)*x
F = 3*x + 3
G = 2
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
Fx, x = field("x", ZZ)
Rt, t = ring("t", Fx)
f = (-x**2 - 4)/4*t
g = t**2 + (x**2 + 2)/2
assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4)
def test_PolyElement_max_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).max_norm() == 0
assert R(1).max_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4
def test_PolyElement_l1_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).l1_norm() == 0
assert R(1).l1_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10
def test_PolyElement_diff():
R, X = xring("x:11", QQ)
f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2
assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0]
assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2
assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10]
def test_PolyElement___call__():
R, x = ring("x", ZZ)
f = 3*x + 1
assert f(0) == 1
assert f(1) == 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1))
raises(CoercionFailed, lambda: f(QQ(1,7)))
R, x,y = ring("x,y", ZZ)
f = 3*x + y**2 + 1
assert f(0, 0) == 1
assert f(1, 7) == 53
Ry = R.drop(x)
assert f(0) == Ry.y**2 + 1
assert f(1) == Ry.y**2 + 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1, 2))
raises(CoercionFailed, lambda: f(1, QQ(1,7)))
raises(CoercionFailed, lambda: f(QQ(1,7), 1))
raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7)))
def test_PolyElement_evaluate():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.evaluate(x, 0)
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3
r = f.evaluate(x, 0)
assert r == 3 and isinstance(r, R.drop(x).dtype)
r = f.evaluate([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.drop(x, y).dtype)
r = f.evaluate(y, 0)
assert r == 3 and isinstance(r, R.drop(y).dtype)
r = f.evaluate([(y, 0), (x, 0)])
assert r == 3 and isinstance(r, R.drop(y, x).dtype)
r = f.evaluate([(x, 0), (y, 0), (z, 0)])
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_subs():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.subs([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_compose():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
assert f.compose(x, x) == f
assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3
raises(CoercionFailed, lambda: f.compose(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.compose([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1)
q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3
assert r == q and isinstance(r, R.dtype)
def test_PolyElement_is_():
R, x,y,z = ring("x,y,z", QQ)
assert (x - x).is_generator == False
assert (x - x).is_ground == True
assert (x - x).is_monomial == True
assert (x - x).is_term == True
assert (x - x + 1).is_generator == False
assert (x - x + 1).is_ground == True
assert (x - x + 1).is_monomial == True
assert (x - x + 1).is_term == True
assert x.is_generator == True
assert x.is_ground == False
assert x.is_monomial == True
assert x.is_term == True
assert (x*y).is_generator == False
assert (x*y).is_ground == False
assert (x*y).is_monomial == True
assert (x*y).is_term == True
assert (3*x).is_generator == False
assert (3*x).is_ground == False
assert (3*x).is_monomial == False
assert (3*x).is_term == True
assert (3*x + 1).is_generator == False
assert (3*x + 1).is_ground == False
assert (3*x + 1).is_monomial == False
assert (3*x + 1).is_term == False
assert R(0).is_zero is True
assert R(1).is_zero is False
assert R(0).is_one is False
assert R(1).is_one is True
assert (x - 1).is_monic is True
assert (2*x - 1).is_monic is False
assert (3*x + 2).is_primitive is True
assert (4*x + 2).is_primitive is False
assert (x + y + z + 1).is_linear is True
assert (x*y*z + 1).is_linear is False
assert (x*y + z + 1).is_quadratic is True
assert (x*y*z + 1).is_quadratic is False
assert (x - 1).is_squarefree is True
assert ((x - 1)**2).is_squarefree is False
assert (x**2 + x + 1).is_irreducible is True
assert (x**2 + 2*x + 1).is_irreducible is False
_, t = ring("t", FF(11))
assert (7*t + 3).is_irreducible is True
assert (7*t**2 + 3*t + 1).is_irreducible is False
_, u = ring("u", ZZ)
f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2
assert f.is_cyclotomic is False
assert (f + 1).is_cyclotomic is True
raises(MultivariatePolynomialError, lambda: x.is_cyclotomic)
R, = ring("", ZZ)
assert R(4).is_squarefree is True
assert R(6).is_irreducible is True
def test_PolyElement_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex)
assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex)
assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False
raises(ValueError, lambda: z.drop(0).drop(0).drop(0))
raises(ValueError, lambda: x.drop(0))
def test_PolyElement_pdiv():
_, x, y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, 0
assert f.pdiv(g) == (q, r)
assert f.prem(g) == r
assert f.pquo(g) == q
assert f.pexquo(g) == q
def test_PolyElement_gcdex():
_, x = ring("x", QQ)
f, g = 2*x, x**2 - 16
s, t, h = x/32, -QQ(1, 16), 1
assert f.half_gcdex(g) == (s, h)
assert f.gcdex(g) == (s, t, h)
def test_PolyElement_subresultants():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
assert f.subresultants(g) == [f, g, h]
def test_PolyElement_resultant():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
assert f.resultant(g) == h
def test_PolyElement_discriminant():
_, x = ring("x", ZZ)
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
assert f.discriminant() == g
F, a, b, c = ring("a,b,c", ZZ)
_, x = ring("x", F)
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
assert f.discriminant() == g
def test_PolyElement_decompose():
_, x = ring("x", ZZ)
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
assert g.compose(x, h) == f
assert f.decompose() == [g, h]
def test_PolyElement_shift():
_, x = ring("x", ZZ)
assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1
def test_PolyElement_sturm():
F, t = field("t", ZZ)
_, x = ring("x", F)
f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625
assert f.sturm() == [
x**3 - 100*x**2 + t**4/64*x - 25*t**4/16,
3*x**2 - 200*x + t**4/64,
(-t**4/96 + F(20000)/9)*x + 25*t**4/18,
(-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000),
]
def test_PolyElement_gff_list():
_, x = ring("x", ZZ)
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert f.gff_list() == [(x, 1), (x + 2, 4)]
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
def test_PolyElement_sqf_norm():
R, x = ring("x", QQ.algebraic_field(sqrt(3)))
X = R.to_ground().x
assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1)
R, x = ring("x", QQ.algebraic_field(sqrt(2)))
X = R.to_ground().x
assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1)
def test_PolyElement_sqf_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
assert f.sqf_part() == p
assert f.sqf_list() == (1, [(g, 1), (h, 2)])
def test_PolyElement_factor_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)])
|
966efe7886cb13d3093e303b1d3e77bcc4ccb3c2037efe25dffbc3de9d4f82c2 | """Tests for tools for constructing domains for expressions. """
from sympy.polys.constructor import construct_domain
from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.domains.complexfield import ComplexField
from sympy import (
S, sqrt, sin, exp, Float, E, I, GoldenRatio, pi, Catalan, Rational)
from sympy.abc import x, y
def test_construct_domain():
assert construct_domain([1, 2, 3]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([1, 2, 3], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S.One, S(2), S(3)]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([S.One, S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S.Half, S(2)]) == (QQ, [QQ(1, 2), QQ(2)])
result = construct_domain([3.14, 1, S.Half])
assert isinstance(result[0], RealField)
assert result[1] == [RR(3.14), RR(1.0), RR(0.5)]
result = construct_domain([3.14, I, S.Half])
assert isinstance(result[0], ComplexField)
assert result[1] == [CC(3.14), CC(1.0j), CC(0.5)]
assert construct_domain([1, I]) == (ZZ_I, [ZZ_I(1, 0), ZZ_I(0, 1)])
assert construct_domain([1, I/2]) == (QQ_I, [QQ_I(1, 0), QQ_I(0, S.Half)])
assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([1, sqrt(2)], extension=None) == (EX, [EX(1), EX(sqrt(2))])
assert construct_domain([x, sqrt(x)]) == (EX, [EX(x), EX(sqrt(x))])
assert construct_domain([x, sqrt(x), sqrt(y)]) == (EX, [EX(x), EX(sqrt(x)), EX(sqrt(y))])
alg = QQ.algebraic_field(sqrt(2))
assert construct_domain([7, S.Half, sqrt(2)], extension=True) == \
(alg, [alg.convert(7), alg.convert(S.Half), alg.convert(sqrt(2))])
alg = QQ.algebraic_field(sqrt(2) + sqrt(3))
assert construct_domain([7, sqrt(2), sqrt(3)], extension=True) == \
(alg, [alg.convert(7), alg.convert(sqrt(2)), alg.convert(sqrt(3))])
dom = ZZ[x]
assert construct_domain([2*x, 3]) == \
(dom, [dom.convert(2*x), dom.convert(3)])
dom = ZZ[x, y]
assert construct_domain([2*x, 3*y]) == \
(dom, [dom.convert(2*x), dom.convert(3*y)])
dom = QQ[x]
assert construct_domain([x/2, 3]) == \
(dom, [dom.convert(x/2), dom.convert(3)])
dom = QQ[x, y]
assert construct_domain([x/2, 3*y]) == \
(dom, [dom.convert(x/2), dom.convert(3*y)])
dom = ZZ_I[x]
assert construct_domain([2*x, I]) == \
(dom, [dom.convert(2*x), dom.convert(I)])
dom = ZZ_I[x, y]
assert construct_domain([2*x, I*y]) == \
(dom, [dom.convert(2*x), dom.convert(I*y)])
dom = QQ_I[x]
assert construct_domain([x/2, I]) == \
(dom, [dom.convert(x/2), dom.convert(I)])
dom = QQ_I[x, y]
assert construct_domain([x/2, I*y]) == \
(dom, [dom.convert(x/2), dom.convert(I*y)])
dom = RR[x]
assert construct_domain([x/2, 3.5]) == \
(dom, [dom.convert(x/2), dom.convert(3.5)])
dom = RR[x, y]
assert construct_domain([x/2, 3.5*y]) == \
(dom, [dom.convert(x/2), dom.convert(3.5*y)])
dom = CC[x]
assert construct_domain([I*x/2, 3.5]) == \
(dom, [dom.convert(I*x/2), dom.convert(3.5)])
dom = CC[x, y]
assert construct_domain([I*x/2, 3.5*y]) == \
(dom, [dom.convert(I*x/2), dom.convert(3.5*y)])
dom = CC[x]
assert construct_domain([x/2, I*3.5]) == \
(dom, [dom.convert(x/2), dom.convert(I*3.5)])
dom = CC[x, y]
assert construct_domain([x/2, I*3.5*y]) == \
(dom, [dom.convert(x/2), dom.convert(I*3.5*y)])
dom = ZZ.frac_field(x)
assert construct_domain([2/x, 3]) == \
(dom, [dom.convert(2/x), dom.convert(3)])
dom = ZZ.frac_field(x, y)
assert construct_domain([2/x, 3*y]) == \
(dom, [dom.convert(2/x), dom.convert(3*y)])
dom = RR.frac_field(x)
assert construct_domain([2/x, 3.5]) == \
(dom, [dom.convert(2/x), dom.convert(3.5)])
dom = RR.frac_field(x, y)
assert construct_domain([2/x, 3.5*y]) == \
(dom, [dom.convert(2/x), dom.convert(3.5*y)])
dom = RealField(prec=336)[x]
assert construct_domain([pi.evalf(100)*x]) == \
(dom, [dom.convert(pi.evalf(100)*x)])
assert construct_domain(2) == (ZZ, ZZ(2))
assert construct_domain(S(2)/3) == (QQ, QQ(2, 3))
assert construct_domain(Rational(2, 3)) == (QQ, QQ(2, 3))
assert construct_domain({}) == (ZZ, {})
def test_complex_exponential():
w = exp(-I*2*pi/3, evaluate=False)
alg = QQ.algebraic_field(w)
assert construct_domain([w**2, w, 1], extension=True) == (
alg,
[alg.convert(w**2),
alg.convert(w),
alg.convert(1)]
)
def test_composite_option():
assert construct_domain({(1,): sin(y)}, composite=False) == \
(EX, {(1,): EX(sin(y))})
assert construct_domain({(1,): y}, composite=False) == \
(EX, {(1,): EX(y)})
assert construct_domain({(1, 1): 1}, composite=False) == \
(ZZ, {(1, 1): 1})
assert construct_domain({(1, 0): y}, composite=False) == \
(EX, {(1, 0): EX(y)})
def test_precision():
f1 = Float("1.01")
f2 = Float("1.0000000000000000000001")
for u in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300,
f1, f2]:
result = construct_domain([u])
v = float(result[1][0])
assert abs(u - v) / u < 1e-14 # Test relative accuracy
result = construct_domain([f1])
y = result[1][0]
assert y-1 > 1e-50
result = construct_domain([f2])
y = result[1][0]
assert y-1 > 1e-50
def test_issue_11538():
for n in [E, pi, Catalan]:
assert construct_domain(n)[0] == ZZ[n]
assert construct_domain(x + n)[0] == ZZ[x, n]
assert construct_domain(GoldenRatio)[0] == EX
assert construct_domain(x + GoldenRatio)[0] == EX
|
c3e03e0666f8f315a6118ed10581b50e887df0d9a9ef5f10b85e21f6e530fbee | """Tests for computational algebraic number field theory. """
from sympy import (S, Rational, Symbol, Poly, sqrt, I, oo, Tuple, expand,
pi, cos, sin, exp, GoldenRatio, TribonacciConstant, cbrt)
from sympy.solvers.solveset import nonlinsolve
from sympy.geometry import Circle, intersection
from sympy.testing.pytest import raises, slow
from sympy.sets.sets import FiniteSet
from sympy import Point2D
from sympy.polys.numberfields import (
minimal_polynomial,
primitive_element,
is_isomorphism_possible,
field_isomorphism_pslq,
field_isomorphism,
to_number_field,
AlgebraicNumber,
isolate, IntervalPrinter,
)
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import (
IsomorphismFailed,
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polyclasses import DMP
from sympy.polys.domains import QQ
from sympy.polys.rootoftools import rootof
from sympy.polys.polytools import degree
from sympy.abc import x, y, z
Q = Rational
def test_minimal_polynomial():
assert minimal_polynomial(-7, x) == x + 7
assert minimal_polynomial(-1, x) == x + 1
assert minimal_polynomial( 0, x) == x
assert minimal_polynomial( 1, x) == x - 1
assert minimal_polynomial( 7, x) == x - 7
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(5), x) == x**2 - 5
assert minimal_polynomial(sqrt(6), x) == x**2 - 6
assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8
assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45
assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96
assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1
assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9
assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47
assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1
assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9
assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47
assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5
assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49
assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37
assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1
assert minimal_polynomial(
sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23
a = 1 - 9*sqrt(2) + 7*sqrt(3)
assert minimal_polynomial(
1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1
assert minimal_polynomial(
1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1
raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))
assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2, domain='QQ')
assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2, domain='QQ')
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(b, x) == x**2 - 3
assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2, domain='QQ')
assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3, domain='QQ')
assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577
assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153
a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7)
f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
31608*x**2 - 189648*x + 141358
assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f
assert minimal_polynomial(
a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519
# issue 5994
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
assert minimal_polynomial(eq, x) == 8000*x**2 - 1
ex = 1 + sqrt(2) + sqrt(3)
mp = minimal_polynomial(ex, x)
assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8
ex = 1/(1 + sqrt(2) + sqrt(3))
mp = minimal_polynomial(ex, x)
assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512
assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1
a = 1 + sqrt(2)
assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1
p = 1/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = 2/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2
assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3
assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2
assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x,
compose=False) == x**4 + 18*x**2 + 49
# minimal polynomial of I
assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
K = QQ.algebraic_field(I*(sqrt(2) + 1))
assert minimal_polynomial(I, x, domain=K) == x - I
assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
#issue 11553
assert minimal_polynomial(GoldenRatio, x) == x**2 - x - 1
assert minimal_polynomial(TribonacciConstant + 3, x) == x**3 - 10*x**2 + 32*x - 34
assert minimal_polynomial(GoldenRatio, x, domain=QQ.algebraic_field(sqrt(5))) == \
2*x - sqrt(5) - 1
assert minimal_polynomial(TribonacciConstant, x, domain=QQ.algebraic_field(cbrt(19 - 3*sqrt(33)))) == \
48*x - 19*(19 - 3*sqrt(33))**Rational(2, 3) - 3*sqrt(33)*(19 - 3*sqrt(33))**Rational(2, 3) \
- 16*(19 - 3*sqrt(33))**Rational(1, 3) - 16
# AlgebraicNumber with an alias.
# Wester H24
phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi')
minimal_polynomial(phi, x) == x**2 - x - 1
def test_minimal_polynomial_hi_prec():
p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + Rational(1, 10)**30)
mp = minimal_polynomial(p, x)
# checked with Wolfram Alpha
assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000
def test_minimal_polynomial_sq():
from sympy import Add, expand_multinomial
p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321
p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = Add(*[sqrt(i) for i in range(1, 12)])
mp = minimal_polynomial(p, x)
assert mp.subs({x: 0}) == -71965773323122507776
def test_minpoly_compose():
# issue 6868
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
mp = minimal_polynomial(eq + 3, x)
assert mp == 8000*x**2 - 48000*x + 71999
# issue 5888
assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(exp(I*pi*Rational(2, 7)), x)
assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
mp = minimal_polynomial(exp(I*pi*Rational(2, 15)), x)
assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
mp = minimal_polynomial(cos(pi*Rational(2, 7)), x)
assert mp == 8*x**3 + 4*x**2 - 4*x - 1
mp = minimal_polynomial(sin(pi*Rational(2, 7)), x)
ex = (5*cos(pi*Rational(2, 7)) - 7)/(9*cos(pi/7) - 5*cos(pi*Rational(3, 7)))
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(sin(pi*Rational(2, 15)), x) == \
256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
assert minimal_polynomial(sin(pi*Rational(5, 14)), x) == 8*x**3 - 4*x**2 - 4*x + 1
assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1
ex = rootof(x**3 +x*4 + 1, 0)
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 4*x + 1
mp = minimal_polynomial(ex + 1, x)
assert mp == x**3 - 3*x**2 + 7*x - 4
assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1
assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1
assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1
assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1
assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1
assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3
assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
2816*x**6 - 1232*x**4 + 220*x**2 - 11
ex = 2**Rational(1, 3)*exp(Rational(2, 3)*I*pi)
assert minimal_polynomial(ex, x) == x**3 - 2
raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x))
# issue 5934
ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1
raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))
ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2)
mp = minimal_polynomial(ex, x)
assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576
def test_minpoly_issue_7113():
# see discussion in https://github.com/sympy/sympy/pull/2234
from sympy.simplify.simplify import nsimplify
r = nsimplify(pi, tolerance=0.000000001)
mp = minimal_polynomial(r, x)
assert mp == 1768292677839237920489538677417507171630859375*x**109 - \
2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464
def test_minpoly_issue_7574():
ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3)
assert minimal_polynomial(ex, x) == x + 1
def test_primitive_element():
assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1])
assert primitive_element(
[sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1])
assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1])
assert primitive_element([sqrt(
2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1])
assert primitive_element(
[sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \
(x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-
Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element(
[sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \
(Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1], [[Q(1, 2), 0, -Q(9, 2),
0], [-Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1])
raises(ValueError, lambda: primitive_element([], x, ex=False))
raises(ValueError, lambda: primitive_element([], x, ex=True))
# Issue 14117
a, b = I*sqrt(2*sqrt(2) + 3), I*sqrt(-2*sqrt(2) + 3)
assert primitive_element([a, b, I], x) == (x**4 + 6*x**2 + 1, [1, 0, 0])
def test_field_isomorphism_pslq():
a = AlgebraicNumber(I)
b = AlgebraicNumber(I*sqrt(3))
raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b))
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
d = AlgebraicNumber(sqrt(2) + sqrt(3))
e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7))
assert field_isomorphism_pslq(a, a) == [1, 0]
assert field_isomorphism_pslq(a, b) is None
assert field_isomorphism_pslq(a, c) is None
assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0]
assert field_isomorphism_pslq(
a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0]
assert field_isomorphism_pslq(b, a) is None
assert field_isomorphism_pslq(b, b) == [1, 0]
assert field_isomorphism_pslq(b, c) is None
assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0]
assert field_isomorphism_pslq(b, e) == [-Q(
3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0]
assert field_isomorphism_pslq(c, a) is None
assert field_isomorphism_pslq(c, b) is None
assert field_isomorphism_pslq(c, c) == [1, 0]
assert field_isomorphism_pslq(c, d) is None
assert field_isomorphism_pslq(c, e) == [Q(
3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0]
assert field_isomorphism_pslq(d, a) is None
assert field_isomorphism_pslq(d, b) is None
assert field_isomorphism_pslq(d, c) is None
assert field_isomorphism_pslq(d, d) == [1, 0]
assert field_isomorphism_pslq(d, e) == [-Q(
3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0]
assert field_isomorphism_pslq(e, a) is None
assert field_isomorphism_pslq(e, b) is None
assert field_isomorphism_pslq(e, c) is None
assert field_isomorphism_pslq(e, d) is None
assert field_isomorphism_pslq(e, e) == [1, 0]
f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5)
assert field_isomorphism_pslq(
f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5]
def test_field_isomorphism():
assert field_isomorphism(3, sqrt(2)) == [3]
assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
p = AlgebraicNumber( sqrt(2) + sqrt(3))
q = AlgebraicNumber(-sqrt(2) + sqrt(3))
r = AlgebraicNumber( sqrt(2) - sqrt(3))
s = AlgebraicNumber(-sqrt(2) - sqrt(3))
pos_coeffs = [ S.Half, S.Zero, Rational(-9, 2), S.Zero]
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(9, 2), S.Zero]
a = AlgebraicNumber(sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
a = AlgebraicNumber(-sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
pos_coeffs = [ S.Half, S.Zero, Rational(-11, 2), S.Zero]
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(11, 2), S.Zero]
a = AlgebraicNumber(sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(-sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
pos_coeffs = [ Rational(3, 2), S.Zero, Rational(-33, 2), -S(8)]
neg_coeffs = [Rational(-3, 2), S.Zero, Rational(33, 2), -S(8)]
a = AlgebraicNumber(3*sqrt(3) - 8)
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1)
pos_1_coeffs = [ S.Half, S.Zero, Rational(-5, 2), S.One]
neg_5_coeffs = [Rational(-5, 2), S.Zero, Rational(49, 2), S.One]
pos_5_coeffs = [ Rational(5, 2), S.Zero, Rational(-49, 2), S.One]
neg_1_coeffs = [Rational(-1, 2), S.Zero, Rational(5, 2), S.One]
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_1_coeffs
assert field_isomorphism(a, q, fast=True) == neg_5_coeffs
assert field_isomorphism(a, r, fast=True) == pos_5_coeffs
assert field_isomorphism(a, s, fast=True) == neg_1_coeffs
assert field_isomorphism(a, p, fast=False) == pos_1_coeffs
assert field_isomorphism(a, q, fast=False) == neg_5_coeffs
assert field_isomorphism(a, r, fast=False) == pos_5_coeffs
assert field_isomorphism(a, s, fast=False) == neg_1_coeffs
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
assert is_isomorphism_possible(a, b) is True
assert is_isomorphism_possible(b, a) is True
assert is_isomorphism_possible(c, p) is False
assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None
assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None
def test_to_number_field():
assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2))
assert to_number_field(
[sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3))
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S.Half, S.Zero, Rational(-9, 2), S.Zero])
assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a
assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a
raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3)))
def test_AlgebraicNumber():
minpoly, root = x**2 - 2, sqrt(2)
a = AlgebraicNumber(root, gen=x)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S.One, S.Zero]
assert a.native_coeffs() == [QQ(1), QQ(0)]
a = AlgebraicNumber(root, gen=x, alias='y')
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
a = AlgebraicNumber(root, gen=x, alias=Symbol('y'))
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
assert AlgebraicNumber(sqrt(2), []).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), ()).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), (0, 0)).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), [8]).rep == DMP([QQ(8)], QQ)
assert AlgebraicNumber(sqrt(2), [Rational(8, 3)]).rep == DMP([QQ(8, 3)], QQ)
assert AlgebraicNumber(sqrt(2), [7, 3]).rep == DMP([QQ(7), QQ(3)], QQ)
assert AlgebraicNumber(
sqrt(2), [Rational(7, 9), Rational(3, 2)]).rep == DMP([QQ(7, 9), QQ(3, 2)], QQ)
assert AlgebraicNumber(sqrt(2), [1, 2, 3]).rep == DMP([QQ(2), QQ(5)], QQ)
a = AlgebraicNumber(AlgebraicNumber(root, gen=x), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S.One, S(2)]
assert a.native_coeffs() == [QQ(1), QQ(2)]
a = AlgebraicNumber((minpoly, root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
a = AlgebraicNumber((Poly(minpoly), root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert AlgebraicNumber( sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ)
assert AlgebraicNumber(-sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(2))
assert a == b
c = AlgebraicNumber(sqrt(2), gen=x)
assert a == b
assert a == c
a = AlgebraicNumber(sqrt(2), [1, 2])
b = AlgebraicNumber(sqrt(2), [1, 3])
assert a != b and a != sqrt(2) + 3
assert (a == x) is False and (a != x) is True
a = AlgebraicNumber(sqrt(2), [1, 0])
b = AlgebraicNumber(sqrt(2), [1, 0], alias=y)
assert a.as_poly(x) == Poly(x, domain='QQ')
assert b.as_poly() == Poly(y, domain='QQ')
assert a.as_expr() == sqrt(2)
assert a.as_expr(x) == x
assert b.as_expr() == sqrt(2)
assert b.as_expr(x) == x
a = AlgebraicNumber(sqrt(2), [2, 3])
b = AlgebraicNumber(sqrt(2), [2, 3], alias=y)
p = a.as_poly()
assert p == Poly(2*p.gen + 3)
assert a.as_poly(x) == Poly(2*x + 3, domain='QQ')
assert b.as_poly() == Poly(2*y + 3, domain='QQ')
assert a.as_expr() == 2*sqrt(2) + 3
assert a.as_expr(x) == 2*x + 3
assert b.as_expr() == 2*sqrt(2) + 3
assert b.as_expr(x) == 2*x + 3
a = AlgebraicNumber(sqrt(2))
b = to_number_field(sqrt(2))
assert a.args == b.args == (sqrt(2), Tuple(1, 0))
b = AlgebraicNumber(sqrt(2), alias='alpha')
assert b.args == (sqrt(2), Tuple(1, 0), Symbol('alpha'))
a = AlgebraicNumber(sqrt(2), [1, 2, 3])
assert a.args == (sqrt(2), Tuple(1, 2, 3))
def test_to_algebraic_integer():
a = AlgebraicNumber(sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 3
assert a.root == sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(2*sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, [Rational(7, 19), 3], gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(7, 19), QQ(3)], QQ)
def test_IntervalPrinter():
ip = IntervalPrinter()
assert ip.doprint(x**Q(1, 3)) == "x**(mpi('1/3'))"
assert ip.doprint(sqrt(x)) == "x**(mpi('1/2'))"
def test_isolate():
assert isolate(1) == (1, 1)
assert isolate(S.Half) == (S.Half, S.Half)
assert isolate(sqrt(2)) == (1, 2)
assert isolate(-sqrt(2)) == (-2, -1)
assert isolate(sqrt(2), eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert isolate(-sqrt(2), eps=Rational(1, 100)) == (Rational(-17, 12), Rational(-24, 17))
raises(NotImplementedError, lambda: isolate(I))
def test_minpoly_fraction_field():
assert minimal_polynomial(1/x, y) == -x*y + 1
assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1
assert minimal_polynomial(sqrt(x), y) == y**2 - x
assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1
assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1
assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x
assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \
y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4
assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x
assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \
y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2
assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x
assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x
assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y, domain='ZZ(x)')
assert minimal_polynomial(1 / (x + 1), y, polys=True) == \
Poly((x + 1)*y - 1, y, domain='ZZ(x)')
assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y, domain='ZZ(x)')
assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \
Poly(z**2*y**2 - x, y, domain='ZZ(x, z)')
# this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x
a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**Rational(5, 2)* \
(1 + x**(-3))**Rational(3, 2)) + 1/(x**Rational(11, 2)*(1 + x**(-3))**Rational(3, 2))
assert minimal_polynomial(a, y) == y
raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x))
raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False))
@slow
def test_minpoly_fraction_field_slow():
assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1),
y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z
def test_minpoly_domain():
assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - sqrt(2)
assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - 2*sqrt(2)
assert minimal_polynomial(sqrt(Rational(3,2)), x,
domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3
raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ))
def test_issue_14831():
a = -2*sqrt(2)*sqrt(12*sqrt(2) + 17)
assert minimal_polynomial(a, x) == x**2 + 16*x - 8
e = (-3*sqrt(12*sqrt(2) + 17) + 12*sqrt(2) +
17 - 2*sqrt(2)*sqrt(12*sqrt(2) + 17))
assert minimal_polynomial(e, x) == x
def test_issue_18248():
assert nonlinsolve([x*y**3-sqrt(2)/3, x*y**6-4/(9*(sqrt(3)))],x,y) == \
FiniteSet((sqrt(3)/2, sqrt(6)/3), (sqrt(3)/2, -sqrt(6)/6 - sqrt(2)*I/2),
(sqrt(3)/2, -sqrt(6)/6 + sqrt(2)*I/2))
def test_issue_13230():
c1 = Circle(Point2D(3, sqrt(5)), 5)
c2 = Circle(Point2D(4, sqrt(7)), 6)
assert intersection(c1, c2) == [Point2D(-1 + (-sqrt(7) + sqrt(5))*(-2*sqrt(7)/29
+ 9*sqrt(5)/29 + sqrt(196*sqrt(35) + 1941)/29), -2*sqrt(7)/29 + 9*sqrt(5)/29
+ sqrt(196*sqrt(35) + 1941)/29), Point2D(-1 + (-sqrt(7) + sqrt(5))*(-sqrt(196*sqrt(35)
+ 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29), -sqrt(196*sqrt(35) + 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29)]
def test_issue_19760():
e = 1/(sqrt(1 + sqrt(2)) - sqrt(2)*sqrt(1 + sqrt(2))) + 1
mp_expected = x**4 - 4*x**3 + 4*x**2 - 2
for comp in (True, False):
mp = Poly(minimal_polynomial(e, compose=comp))
assert mp(x) == mp_expected, "minimal_polynomial(e, compose=%s) = %s; %s expected" % (comp, mp(x), mp_expected)
def test_issue_20163():
assert apart(1/(x**6+1), extension=[sqrt(3), I]) == \
(sqrt(3) + I)/(2*x + sqrt(3) + I)/6 + \
(sqrt(3) - I)/(2*x + sqrt(3) - I)/6 - \
(sqrt(3) - I)/(2*x - sqrt(3) + I)/6 - \
(sqrt(3) + I)/(2*x - sqrt(3) - I)/6 + \
I/(x + I)/6 - I/(x - I)/6
|
3e4db8c809425e786bc6c4abeff7e361ae2c43ebcfece035d620dd990426a45f | """Test sparse rational functions. """
from sympy.polys.fields import field, sfield, FracField, FracElement
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ, QQ
from sympy.polys.orderings import lex
from sympy.testing.pytest import raises, XFAIL
from sympy.core import symbols, E
from sympy import sqrt, Rational, exp, log
def test_FracField___init__():
F1 = FracField("x,y", ZZ, lex)
F2 = FracField("x,y", ZZ, lex)
F3 = FracField("x,y,z", ZZ, lex)
assert F1.x == F1.gens[0]
assert F1.y == F1.gens[1]
assert F1.x == F2.x
assert F1.y == F2.y
assert F1.x != F3.x
assert F1.y != F3.y
def test_FracField___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(F)
def test_FracField___eq__():
assert field("x,y,z", QQ)[0] == field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] is field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y,z", ZZ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y,z", ZZ)[0]
assert field("x,y,z", ZZ)[0] != field("x,y,z", QQ)[0]
assert field("x,y,z", ZZ)[0] is not field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y", QQ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y", QQ)[0]
assert field("x,y", QQ)[0] != field("x,y,z", QQ)[0]
assert field("x,y", QQ)[0] is not field("x,y,z", QQ)[0]
def test_sfield():
x = symbols("x")
F = FracField((E, exp(exp(x)), exp(x)), ZZ, lex)
e, exex, ex = F.gens
assert sfield(exp(x)*exp(exp(x) + 1 + log(exp(x) + 3)/2)**2/(exp(x) + 3)) \
== (F, e**2*exex**2*ex)
F = FracField((x, exp(1/x), log(x), x**QQ(1, 3)), ZZ, lex)
_, ex, lg, x3 = F.gens
assert sfield(((x-3)*log(x)+4*x**2)*exp(1/x+log(x)/3)/x**2) == \
(F, (4*F.x**2*ex + F.x*ex*lg - 3*ex*lg)/x3**5)
F = FracField((x, log(x), sqrt(x + log(x))), ZZ, lex)
_, lg, srt = F.gens
assert sfield((x + 1) / (x * (x + log(x))**QQ(3, 2)) - 1/(x * log(x)**2)) \
== (F, (F.x*lg**2 - F.x*srt + lg**2 - lg*srt)/
(F.x**2*lg**2*srt + F.x*lg**3*srt))
def test_FracElement___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(x*y/z)
def test_FracElement_copy():
F, x, y, z = field("x,y,z", ZZ)
f = x*y/3*z
g = f.copy()
assert f == g
g.numer[(1, 1, 1)] = 7
assert f != g
def test_FracElement_as_expr():
F, x, y, z = field("x,y,z", ZZ)
f = (3*x**2*y - x*y*z)/(7*z**3 + 1)
X, Y, Z = F.symbols
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
def test_FracElement_from_expr():
x, y, z = symbols("x,y,z")
F, X, Y, Z = field((x, y, z), ZZ)
f = F.from_expr(1)
assert f == 1 and isinstance(f, F.dtype)
f = F.from_expr(Rational(3, 7))
assert f == F(3)/7 and isinstance(f, F.dtype)
f = F.from_expr(x)
assert f == X and isinstance(f, F.dtype)
f = F.from_expr(Rational(3,7)*x)
assert f == X*Rational(3, 7) and isinstance(f, F.dtype)
f = F.from_expr(1/x)
assert f == 1/X and isinstance(f, F.dtype)
f = F.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, F.dtype)
f = F.from_expr(x*y/z)
assert f == X*Y/Z and isinstance(f, F.dtype)
f = F.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, F.dtype)
f = F.from_expr((x*y*z + x*y + x)/(x*y + 7))
assert f == (X*Y*Z + X*Y + X)/(X*Y + 7) and isinstance(f, F.dtype)
f = F.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, F.dtype)
raises(ValueError, lambda: F.from_expr(2**x))
raises(ValueError, lambda: F.from_expr(7*x + sqrt(2)))
assert isinstance(ZZ[2**x].get_field().convert(2**(-x)),
FracElement)
assert isinstance(ZZ[x**2].get_field().convert(x**(-6)),
FracElement)
assert isinstance(ZZ[exp(Rational(1, 3))].get_field().convert(E),
FracElement)
def test_FracField_nested():
a, b, x = symbols('a b x')
F1 = ZZ.frac_field(a, b)
F2 = F1.frac_field(x)
frac = F2(a + b)
assert frac.numer == F1.poly_ring(x)(a + b)
assert frac.numer.coeffs() == [F1(a + b)]
assert frac.denom == F1.poly_ring(x)(1)
F3 = ZZ.poly_ring(a, b)
F4 = F3.frac_field(x)
frac = F4(a + b)
assert frac.numer == F3.poly_ring(x)(a + b)
assert frac.numer.coeffs() == [F3(a + b)]
assert frac.denom == F3.poly_ring(x)(1)
frac = F2(F3(a + b))
assert frac.numer == F1.poly_ring(x)(a + b)
assert frac.numer.coeffs() == [F1(a + b)]
assert frac.denom == F1.poly_ring(x)(1)
frac = F4(F1(a + b))
assert frac.numer == F3.poly_ring(x)(a + b)
assert frac.numer.coeffs() == [F3(a + b)]
assert frac.denom == F3.poly_ring(x)(1)
def test_FracElement__lt_le_gt_ge__():
F, x, y = field("x,y", ZZ)
assert F(1) < 1/x < 1/x**2 < 1/x**3
assert F(1) <= 1/x <= 1/x**2 <= 1/x**3
assert -7/x < 1/x < 3/x < y/x < 1/x**2
assert -7/x <= 1/x <= 3/x <= y/x <= 1/x**2
assert 1/x**3 > 1/x**2 > 1/x > F(1)
assert 1/x**3 >= 1/x**2 >= 1/x >= F(1)
assert 1/x**2 > y/x > 3/x > 1/x > -7/x
assert 1/x**2 >= y/x >= 3/x >= 1/x >= -7/x
def test_FracElement___neg__():
F, x,y = field("x,y", QQ)
f = (7*x - 9)/y
g = (-7*x + 9)/y
assert -f == g
assert -g == f
def test_FracElement___add__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f + g == g + f == (x + y)/(x*y)
assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2*x
F, x,y = field("x,y", ZZ)
assert x + 3 == 3 + x
assert x + QQ(3,7) == QQ(3,7) + x == (7*x + 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
def test_FracElement___sub__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f - g == (-x + y)/(x*y)
assert x - F.ring.gens[0] == F.ring.gens[0] - x == 0
F, x,y = field("x,y", ZZ)
assert x - 3 == -(3 - x)
assert x - QQ(3,7) == -(QQ(3,7) - x) == (7*x - 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
def test_FracElement___mul__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f*g == g*f == 1/(x*y)
assert x*F.ring.gens[0] == F.ring.gens[0]*x == x**2
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x*QQ(3,7) == QQ(3,7)*x == x*Rational(3, 7)
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
def test_FracElement___truediv__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f/g == y/x
assert x/F.ring.gens[0] == F.ring.gens[0]/x == 1
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x/QQ(3,7) == (QQ(3,7)/x)**-1 == x*Rational(7, 3)
raises(ZeroDivisionError, lambda: x/0)
raises(ZeroDivisionError, lambda: 1/(x - x))
raises(ZeroDivisionError, lambda: x/(x - x))
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
def test_FracElement___pow__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f**3 == 1/x**3
assert g**3 == 1/y**3
assert (f*g)**3 == 1/(x**3*y**3)
assert (f*g)**-3 == (x*y)**3
raises(ZeroDivisionError, lambda: (x - x)**-3)
def test_FracElement_diff():
F, x,y,z = field("x,y,z", ZZ)
assert ((x**2 + y)/(z + 1)).diff(x) == 2*x/(z + 1)
@XFAIL
def test_FracElement___call__():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
r = f(1, 1, 1)
assert r == 4 and not isinstance(r, FracElement)
raises(ZeroDivisionError, lambda: f(1, 1, 0))
def test_FracElement_evaluate():
F, x,y,z = field("x,y,z", ZZ)
Fyz = field("y,z", ZZ)[0]
f = (x**2 + 3*y)/z
assert f.evaluate(x, 0) == 3*Fyz.y/Fyz.z
raises(ZeroDivisionError, lambda: f.evaluate(z, 0))
def test_FracElement_subs():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
assert f.subs(x, 0) == 3*y/z
raises(ZeroDivisionError, lambda: f.subs(z, 0))
def test_FracElement_compose():
pass
def test_FracField_index():
a = symbols("a")
F, x, y, z = field('x y z', QQ)
assert F.index(x) == 0
assert F.index(y) == 1
raises(ValueError, lambda: F.index(1))
raises(ValueError, lambda: F.index(a))
pass
|
2b41cf2d1630b2130b1b67183202ab75ba8f38296834d4d5d526d3f57b2044ae | """Tests for user-friendly public interface to polynomial functions. """
import pickle
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
total_degree,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resultant, discriminant,
terms_gcd, cofactors,
gcd, gcd_list,
lcm, lcm_list,
trunc,
monic, content, primitive,
compose, decompose,
sturm,
gff_list, gff,
sqf_norm, sqf_part, sqf_list, sqf,
factor_list, factor,
intervals, refine_root, count_roots,
real_roots, nroots, ground_roots,
nth_power_roots_poly,
cancel, reduced, groebner,
GroebnerBasis, is_zero_dimensional,
_torational_factor_list,
to_rational_coeffs)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
UnificationFailed,
RefinementFailed,
GeneratorsNeeded,
GeneratorsError,
PolynomialError,
CoercionFailed,
DomainError,
OptionError,
FlagError)
from sympy.polys.polyclasses import DMP
from sympy.polys.fields import field
from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.orderings import lex, grlex, grevlex
from sympy import (
S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise, Derivative,
exp, sin, tanh, expand, oo, I, pi, re, im, rootof, Eq, Tuple, Expr, diff)
from sympy.core.basic import _aresame
from sympy.core.compatibility import iterable
from sympy.core.mul import _keep_coeff
from sympy.testing.pytest import raises, warns_deprecated_sympy
from sympy.abc import a, b, c, d, p, q, t, w, x, y, z
from sympy import MatrixSymbol, Matrix
def _epsilon_eq(a, b):
for u, v in zip(a, b):
if abs(u - v) > 1e-10:
return False
return True
def _strict_eq(a, b):
if type(a) == type(b):
if iterable(a):
if len(a) == len(b):
return all(_strict_eq(c, d) for c, d in zip(a, b))
else:
return False
else:
return isinstance(a, Poly) and a.eq(b, strict=True)
else:
return False
def test_Poly_mixed_operations():
p = Poly(x, x)
with warns_deprecated_sympy():
p * exp(x)
with warns_deprecated_sympy():
p + exp(x)
with warns_deprecated_sympy():
p - exp(x)
def test_Poly_from_dict():
K = FF(3)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=(
x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K)
assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \
Poly(sin(y)*x, x, domain='EX')
assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \
Poly(y*x, x, domain='EX')
assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \
Poly(x*y, x, y, domain='ZZ')
assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \
Poly(y*x, x, z, domain='EX')
def test_Poly_from_list():
K = FF(3)
assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR)
assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR)
raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y)))
def test_Poly_from_poly():
f = Poly(x + 7, x, domain=ZZ)
g = Poly(x + 2, x, modulus=3)
h = Poly(x + y, x, y, domain=ZZ)
K = FF(3)
assert Poly.from_poly(f) == f
assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=x) == f
assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]')
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ))
assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ')
assert Poly.from_poly(
f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)')
K = FF(2)
assert Poly.from_poly(g) == g
assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ))
assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K)
assert Poly.from_poly(g, gens=x) == g
assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ))
assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K)
K = FF(3)
assert Poly.from_poly(h) == h
assert Poly.from_poly(
h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ))
assert Poly.from_poly(
h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ))
assert Poly.from_poly(
h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3))
assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ))
assert Poly.from_poly(
h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ))
assert Poly.from_poly(
h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3))
assert Poly.from_poly(h, gens=(x, y)) == h
assert Poly.from_poly(
h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
def test_Poly_from_expr():
raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero))
raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7)))
F3 = FF(3)
assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ)
assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ)
def test_poly_from_domain_element():
dom = ZZ[x]
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = dom.get_field()
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = QQ[x]
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = dom.get_field()
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = ZZ.old_poly_ring(x)
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = dom.get_field()
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = QQ.old_poly_ring(x)
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = dom.get_field()
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = QQ.algebraic_field(I)
assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom)
def test_Poly__new__():
raises(GeneratorsError, lambda: Poly(x + 1, x, x))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x]))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y]))
raises(OptionError, lambda: Poly(x, x, symmetric=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False))
raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex'))
raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex'))
raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1}))
raises(GeneratorsNeeded, lambda: Poly([2, 1]))
raises(GeneratorsNeeded, lambda: Poly((2, 1)))
raises(GeneratorsNeeded, lambda: Poly(1))
f = a*x**2 + b*x + c
assert Poly({2: a, 1: b, 0: c}, x) == f
assert Poly(iter([a, b, c]), x) == f
assert Poly([a, b, c], x) == f
assert Poly((a, b, c), x) == f
f = Poly({}, x, y, z)
assert f.gens == (x, y, z) and f.as_expr() == 0
assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x)
assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ'))
assert Poly(
3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1]
assert _epsilon_eq(
Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0])
assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(
3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ'))
assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1]
assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0]
assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \
Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y)
assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I)
f = 3*x**5 - x**4 + x**3 - x** 2 + 65538
assert Poly(f, x, modulus=65537, symmetric=True) == \
Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537,
symmetric=True)
assert Poly(f, x, modulus=65537, symmetric=False) == \
Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x,
modulus=65537, symmetric=False)
assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField)
def test_Poly__args():
assert Poly(x**2 + 1).args == (x**2 + 1, x)
def test_Poly__gens():
assert Poly((x - p)*(x - q), x).gens == (x,)
assert Poly((x - p)*(x - q), p).gens == (p,)
assert Poly((x - p)*(x - q), q).gens == (q,)
assert Poly((x - p)*(x - q), x, p).gens == (x, p)
assert Poly((x - p)*(x - q), x, q).gens == (x, q)
assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q)
assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q)
assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x)
assert Poly((x - p)*(x - q)).gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q)
assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p)
assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p)
assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x)
def test_Poly_zero():
assert Poly(x).zero == Poly(0, x, domain=ZZ)
assert Poly(x/2).zero == Poly(0, x, domain=QQ)
def test_Poly_one():
assert Poly(x).one == Poly(1, x, domain=ZZ)
assert Poly(x/2).one == Poly(1, x, domain=QQ)
def test_Poly__unify():
raises(UnificationFailed, lambda: Poly(x)._unify(y))
F3 = FF(3)
F5 = FF(5)
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == (
DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == (
DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5))
assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \
(Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>'))
F, A, B = field("a,b", ZZ)
assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)'))
f = Poly(t**2 + t/3 + x, t, domain='QQ(x)')
g = Poly(t**2 + t/3 + x, t, domain='QQ[x]')
assert f._unify(g)[2:] == (f.rep, f.rep)
def test_Poly_free_symbols():
assert Poly(x**2 + 1).free_symbols == {x}
assert Poly(x**2 + y*z).free_symbols == {x, y, z}
assert Poly(x**2 + y*z, x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z}
assert Poly(1 + x + x**2, x, y, z).free_symbols == {x}
assert Poly(x + sin(y), z).free_symbols == {x, y}
def test_PurePoly_free_symbols():
assert PurePoly(x**2 + 1).free_symbols == set()
assert PurePoly(x**2 + y*z).free_symbols == set()
assert PurePoly(x**2 + y*z, x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z)).free_symbols == set()
assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z}
def test_Poly__eq__():
assert (Poly(x, x) == Poly(x, x)) is True
assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False
assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False
assert (Poly(x*y, x, y) == Poly(x, x)) is False
assert (Poly(x, x, y) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, y)) is False
assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False
assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False
f = Poly(x, x, domain=ZZ)
g = Poly(x, x, domain=QQ)
assert f.eq(g) is False
assert f.ne(g) is True
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
t0 = Symbol('t0')
f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]')
g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)')
assert (f == g) is False
def test_PurePoly__eq__():
assert (PurePoly(x, x) == PurePoly(x, x)) is True
assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True
assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True
assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x) == PurePoly(x, x, y)) is False
assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True
assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(y, y, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
def test_PurePoly_Poly():
assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True
assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True
def test_Poly_get_domain():
assert Poly(2*x).get_domain() == ZZ
assert Poly(2*x, domain='ZZ').get_domain() == ZZ
assert Poly(2*x, domain='QQ').get_domain() == QQ
assert Poly(x/2).get_domain() == QQ
raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ'))
assert Poly(x/2, domain='QQ').get_domain() == QQ
assert isinstance(Poly(0.2*x).get_domain(), RealField)
def test_Poly_set_domain():
assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ')
assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1)
assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10))
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ))
raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ))
raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y]))
def test_Poly_get_modulus():
assert Poly(x**2 + 1, modulus=2).get_modulus() == 2
raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus())
def test_Poly_set_modulus():
assert Poly(
x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7)
assert Poly(
x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2)
assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2)
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2))
def test_Poly_add_ground():
assert Poly(x + 1).add_ground(2) == Poly(x + 3)
def test_Poly_sub_ground():
assert Poly(x + 1).sub_ground(2) == Poly(x - 1)
def test_Poly_mul_ground():
assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2)
def test_Poly_quo_ground():
assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2)
assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1)
def test_Poly_exquo_ground():
assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2)
raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2))
def test_Poly_abs():
assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x)
def test_Poly_neg():
assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x)
def test_Poly_add():
assert Poly(0, x).add(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) + Poly(0, x) == Poly(0, x)
assert Poly(1, x).add(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y)
assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y)
assert Poly(1, x) + x == Poly(x + 1, x)
with warns_deprecated_sympy():
Poly(1, x) + sin(x)
assert Poly(x, x) + 1 == Poly(x + 1, x)
assert 1 + Poly(x, x) == Poly(x + 1, x)
def test_Poly_sub():
assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) - Poly(0, x) == Poly(0, x)
assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y)
assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y)
assert Poly(1, x) - x == Poly(1 - x, x)
with warns_deprecated_sympy():
Poly(1, x) - sin(x)
assert Poly(x, x) - 1 == Poly(x - 1, x)
assert 1 - Poly(x, x) == Poly(1 - x, x)
def test_Poly_mul():
assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) * Poly(0, x) == Poly(0, x)
assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x)
assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y)
assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y)
assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y)
assert Poly(1, x) * x == Poly(x, x)
with warns_deprecated_sympy():
Poly(1, x) * sin(x)
assert Poly(x, x) * 2 == Poly(2*x, x)
assert 2 * Poly(x, x) == Poly(2*x, x)
def test_issue_13079():
assert Poly(x)*x == Poly(x**2, x, domain='ZZ')
assert x*Poly(x) == Poly(x**2, x, domain='ZZ')
assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ')
def test_Poly_sqr():
assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y)
def test_Poly_pow():
assert Poly(x, x).pow(10) == Poly(x**10, x)
assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x)
assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y)
assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y)
assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y)
raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1))
raises(TypeError, lambda: Poly(x*y + 1, x, y)**x)
def test_Poly_divmod():
f, g = Poly(x**2), Poly(x)
q, r = g, Poly(0, x)
assert divmod(f, g) == (q, r)
assert f // g == q
assert f % g == r
assert divmod(f, x) == (q, r)
assert f // x == q
assert f % x == r
q, r = Poly(0, x), Poly(2, x)
assert divmod(2, g) == (q, r)
assert 2 // g == q
assert 2 % g == r
assert Poly(x)/Poly(x) == 1
assert Poly(x**2)/Poly(x) == x
assert Poly(x)/Poly(x**2) == 1/x
def test_Poly_eq_ne():
assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True
assert (Poly(x + y, x) == Poly(x + y, x, y)) is False
assert (Poly(x + y, x, y) == Poly(x + y, x)) is False
assert (Poly(x + y, x) == Poly(x + y, x)) is True
assert (Poly(x + y, y) == Poly(x + y, y)) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, y) == x + y) is True
assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False
assert (Poly(x + y, x) != Poly(x + y, x, y)) is True
assert (Poly(x + y, x, y) != Poly(x + y, x)) is True
assert (Poly(x + y, x) != Poly(x + y, x)) is False
assert (Poly(x + y, y) != Poly(x + y, y)) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, y) != x + y) is False
assert (Poly(x, x) == sin(x)) is False
assert (Poly(x, x) != sin(x)) is True
def test_Poly_nonzero():
assert not bool(Poly(0, x)) is True
assert not bool(Poly(1, x)) is False
def test_Poly_properties():
assert Poly(0, x).is_zero is True
assert Poly(1, x).is_zero is False
assert Poly(1, x).is_one is True
assert Poly(2, x).is_one is False
assert Poly(x - 1, x).is_sqf is True
assert Poly((x - 1)**2, x).is_sqf is False
assert Poly(x - 1, x).is_monic is True
assert Poly(2*x - 1, x).is_monic is False
assert Poly(3*x + 2, x).is_primitive is True
assert Poly(4*x + 2, x).is_primitive is False
assert Poly(1, x).is_ground is True
assert Poly(x, x).is_ground is False
assert Poly(x + y + z + 1).is_linear is True
assert Poly(x*y*z + 1).is_linear is False
assert Poly(x*y + z + 1).is_quadratic is True
assert Poly(x*y*z + 1).is_quadratic is False
assert Poly(x*y).is_monomial is True
assert Poly(x*y + 1).is_monomial is False
assert Poly(x**2 + x*y).is_homogeneous is True
assert Poly(x**3 + x*y).is_homogeneous is False
assert Poly(x).is_univariate is True
assert Poly(x*y).is_univariate is False
assert Poly(x*y).is_multivariate is True
assert Poly(x).is_multivariate is False
assert Poly(
x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False
assert Poly(
x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True
def test_Poly_is_irreducible():
assert Poly(x**2 + x + 1).is_irreducible is True
assert Poly(x**2 + 2*x + 1).is_irreducible is False
assert Poly(7*x + 3, modulus=11).is_irreducible is True
assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False
def test_Poly_subs():
assert Poly(x + 1).subs(x, 0) == 1
assert Poly(x + 1).subs(x, x) == Poly(x + 1)
assert Poly(x + 1).subs(x, y) == Poly(y + 1)
assert Poly(x*y, x).subs(y, x) == x**2
assert Poly(x*y, x).subs(x, y) == y**2
def test_Poly_replace():
assert Poly(x + 1).replace(x) == Poly(x + 1)
assert Poly(x + 1).replace(y) == Poly(y + 1)
raises(PolynomialError, lambda: Poly(x + y).replace(z))
assert Poly(x + 1).replace(x, x) == Poly(x + 1)
assert Poly(x + 1).replace(x, y) == Poly(y + 1)
assert Poly(x + y).replace(x, x) == Poly(x + y)
assert Poly(x + y).replace(x, z) == Poly(z + y, z, y)
assert Poly(x + y).replace(y, y) == Poly(x + y)
assert Poly(x + y).replace(y, z) == Poly(x + z, x, z)
assert Poly(x + y).replace(z, t) == Poly(x + y)
raises(PolynomialError, lambda: Poly(x + y).replace(x, y))
assert Poly(x + y, x).replace(x, z) == Poly(z + y, z)
assert Poly(x + y, y).replace(y, z) == Poly(x + z, z)
raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y))
raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x))
def test_Poly_reorder():
raises(PolynomialError, lambda: Poly(x + y).reorder(x, z))
assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x)
def test_Poly_ltrim():
f = Poly(y**2 + y*z**2, x, y, z).ltrim(y)
assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z)
assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y)
raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y))
raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1))
def test_Poly_has_only_gens():
assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True
assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False
raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t))
def test_Poly_to_ring():
assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ')
assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ')
raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring())
raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring())
def test_Poly_to_field():
assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ')
assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3)
assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0)
def test_Poly_to_exact():
assert Poly(2*x).to_exact() == Poly(2*x)
assert Poly(x/2).to_exact() == Poly(x/2)
assert Poly(0.1*x).to_exact() == Poly(x/10)
def test_Poly_retract():
f = Poly(x**2 + 1, x, domain=QQ[y])
assert f.retract() == Poly(x**2 + 1, x, domain='ZZ')
assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ')
assert Poly(0, x, y).retract() == Poly(0, x, y)
def test_Poly_slice():
f = Poly(x**3 + 2*x**2 + 3*x + 4)
assert f.slice(0, 0) == Poly(0, x)
assert f.slice(0, 1) == Poly(4, x)
assert f.slice(0, 2) == Poly(3*x + 4, x)
assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 0) == Poly(0, x)
assert f.slice(x, 0, 1) == Poly(4, x)
assert f.slice(x, 0, 2) == Poly(3*x + 4, x)
assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
def test_Poly_coeffs():
assert Poly(0, x).coeffs() == [0]
assert Poly(1, x).coeffs() == [1]
assert Poly(2*x + 1, x).coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2]
def test_Poly_monoms():
assert Poly(0, x).monoms() == [(0,)]
assert Poly(1, x).monoms() == [(0,)]
assert Poly(2*x + 1, x).monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)]
def test_Poly_terms():
assert Poly(0, x).terms() == [((0,), 0)]
assert Poly(1, x).terms() == [((0,), 1)]
assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
def test_Poly_all_coeffs():
assert Poly(0, x).all_coeffs() == [0]
assert Poly(1, x).all_coeffs() == [1]
assert Poly(2*x + 1, x).all_coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1]
def test_Poly_all_monoms():
assert Poly(0, x).all_monoms() == [(0,)]
assert Poly(1, x).all_monoms() == [(0,)]
assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)]
def test_Poly_all_terms():
assert Poly(0, x).all_terms() == [((0,), 0)]
assert Poly(1, x).all_terms() == [((0,), 1)]
assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \
[((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \
[((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)]
def test_Poly_termwise():
f = Poly(x**2 + 20*x + 400)
g = Poly(x**2 + 2*x + 4)
def func(monom, coeff):
(k,) = monom
return coeff//10**(2 - k)
assert f.termwise(func) == g
def func(monom, coeff):
(k,) = monom
return (k,), coeff//10**(2 - k)
assert f.termwise(func) == g
def test_Poly_length():
assert Poly(0, x).length() == 0
assert Poly(1, x).length() == 1
assert Poly(x, x).length() == 1
assert Poly(x + 1, x).length() == 2
assert Poly(x**2 + 1, x).length() == 2
assert Poly(x**2 + x + 1, x).length() == 3
def test_Poly_as_dict():
assert Poly(0, x).as_dict() == {}
assert Poly(0, x, y, z).as_dict() == {}
assert Poly(1, x).as_dict() == {(0,): 1}
assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1}
assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3}
assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3}
assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3,
(1, 1, 0): 4, (1, 0, 1): 5}
def test_Poly_as_expr():
assert Poly(0, x).as_expr() == 0
assert Poly(0, x, y, z).as_expr() == 0
assert Poly(1, x).as_expr() == 1
assert Poly(1, x, y, z).as_expr() == 1
assert Poly(x**2 + 3, x).as_expr() == x**2 + 3
assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3
assert Poly(
3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z
f = Poly(x**2 + 2*x*y**2 - y, x, y)
assert f.as_expr() == -y + x**2 + 2*x*y**2
assert f.as_expr({x: 5}) == 25 - y + 10*y**2
assert f.as_expr({y: 6}) == -6 + 72*x + x**2
assert f.as_expr({x: 5, y: 6}) == 379
assert f.as_expr(5, 6) == 379
raises(GeneratorsError, lambda: f.as_expr({z: 7}))
def test_Poly_lift():
assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \
Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521,
x, domain='QQ')
def test_Poly_deflate():
assert Poly(0, x).deflate() == ((1,), Poly(0, x))
assert Poly(1, x).deflate() == ((1,), Poly(1, x))
assert Poly(x, x).deflate() == ((1,), Poly(x, x))
assert Poly(x**2, x).deflate() == ((2,), Poly(x, x))
assert Poly(x**17, x).deflate() == ((17,), Poly(x, x))
assert Poly(
x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z))
def test_Poly_inject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x)
assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x)
def test_Poly_eject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
ex = x + y + z + t + w
g = Poly(ex, x, y, z, t, w)
assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]')
assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]')
assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]')
assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]')
assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]')
assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]')
raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y))
raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y))
def test_Poly_exclude():
assert Poly(x, x, y).exclude() == Poly(x, x)
assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y)
assert Poly(1, x, y).exclude() == Poly(1, x, y)
def test_Poly__gen_to_level():
assert Poly(1, x, y)._gen_to_level(-2) == 0
assert Poly(1, x, y)._gen_to_level(-1) == 1
assert Poly(1, x, y)._gen_to_level( 0) == 0
assert Poly(1, x, y)._gen_to_level( 1) == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2))
assert Poly(1, x, y)._gen_to_level(x) == 0
assert Poly(1, x, y)._gen_to_level(y) == 1
assert Poly(1, x, y)._gen_to_level('x') == 0
assert Poly(1, x, y)._gen_to_level('y') == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z'))
def test_Poly_degree():
assert Poly(0, x).degree() is -oo
assert Poly(1, x).degree() == 0
assert Poly(x, x).degree() == 1
assert Poly(0, x).degree(gen=0) is -oo
assert Poly(1, x).degree(gen=0) == 0
assert Poly(x, x).degree(gen=0) == 1
assert Poly(0, x).degree(gen=x) is -oo
assert Poly(1, x).degree(gen=x) == 0
assert Poly(x, x).degree(gen=x) == 1
assert Poly(0, x).degree(gen='x') is -oo
assert Poly(1, x).degree(gen='x') == 0
assert Poly(x, x).degree(gen='x') == 1
raises(PolynomialError, lambda: Poly(1, x).degree(gen=1))
raises(PolynomialError, lambda: Poly(1, x).degree(gen=y))
raises(PolynomialError, lambda: Poly(1, x).degree(gen='y'))
assert Poly(1, x, y).degree() == 0
assert Poly(2*y, x, y).degree() == 0
assert Poly(x*y, x, y).degree() == 1
assert Poly(1, x, y).degree(gen=x) == 0
assert Poly(2*y, x, y).degree(gen=x) == 0
assert Poly(x*y, x, y).degree(gen=x) == 1
assert Poly(1, x, y).degree(gen=y) == 0
assert Poly(2*y, x, y).degree(gen=y) == 1
assert Poly(x*y, x, y).degree(gen=y) == 1
assert degree(0, x) is -oo
assert degree(1, x) == 0
assert degree(x, x) == 1
assert degree(x*y**2, x) == 1
assert degree(x*y**2, y) == 2
assert degree(x*y**2, z) == 0
assert degree(pi) == 1
raises(TypeError, lambda: degree(y**2 + x**3))
raises(TypeError, lambda: degree(y**2 + x**3, 1))
raises(PolynomialError, lambda: degree(x, 1.1))
raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x))
assert degree(Poly(0,x),z) is -oo
assert degree(Poly(1,x),z) == 0
assert degree(Poly(x**2+y**3,y)) == 3
assert degree(Poly(y**2 + x**3, y, x), 1) == 3
assert degree(Poly(y**2 + x**3, x), z) == 0
assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4
def test_Poly_degree_list():
assert Poly(0, x).degree_list() == (-oo,)
assert Poly(0, x, y).degree_list() == (-oo, -oo)
assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo)
assert Poly(1, x).degree_list() == (0,)
assert Poly(1, x, y).degree_list() == (0, 0)
assert Poly(1, x, y, z).degree_list() == (0, 0, 0)
assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2)
assert degree_list(1, x) == (0,)
assert degree_list(x, x) == (1,)
assert degree_list(x*y**2) == (1, 2)
raises(ComputationFailed, lambda: degree_list(1))
def test_Poly_total_degree():
assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5
assert Poly(x**2 + z**3).total_degree() == 3
assert Poly(x*y*z + z**4).total_degree() == 4
assert Poly(x**3 + x + 1).total_degree() == 3
assert total_degree(x*y + z**3) == 3
assert total_degree(x*y + z**3, x, y) == 2
assert total_degree(1) == 0
assert total_degree(Poly(y**2 + x**3 + z**4)) == 4
assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3
assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4
assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7
def test_Poly_homogenize():
assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z)
assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z)
assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2)
def test_Poly_homogeneous_order():
assert Poly(0, x, y).homogeneous_order() is -oo
assert Poly(1, x, y).homogeneous_order() == 0
assert Poly(x, x, y).homogeneous_order() == 1
assert Poly(x*y, x, y).homogeneous_order() == 2
assert Poly(x + 1, x, y).homogeneous_order() is None
assert Poly(x*y + x, x, y).homogeneous_order() is None
assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5
assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None
def test_Poly_LC():
assert Poly(0, x).LC() == 0
assert Poly(1, x).LC() == 1
assert Poly(2*x**2 + x, x).LC() == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1
assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2
assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1
def test_Poly_TC():
assert Poly(0, x).TC() == 0
assert Poly(1, x).TC() == 1
assert Poly(2*x**2 + x, x).TC() == 0
def test_Poly_EC():
assert Poly(0, x).EC() == 0
assert Poly(1, x).EC() == 1
assert Poly(2*x**2 + x, x).EC() == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2
def test_Poly_coeff():
assert Poly(0, x).coeff_monomial(1) == 0
assert Poly(0, x).coeff_monomial(x) == 0
assert Poly(1, x).coeff_monomial(1) == 1
assert Poly(1, x).coeff_monomial(x) == 0
assert Poly(x**8, x).coeff_monomial(1) == 0
assert Poly(x**8, x).coeff_monomial(x**7) == 0
assert Poly(x**8, x).coeff_monomial(x**8) == 1
assert Poly(x**8, x).coeff_monomial(x**9) == 0
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3
p = Poly(24*x*y*exp(8) + 23*x, x, y)
assert p.coeff_monomial(x) == 23
assert p.coeff_monomial(y) == 0
assert p.coeff_monomial(x*y) == 24*exp(8)
assert p.as_expr().coeff(x) == 24*y*exp(8) + 23
raises(NotImplementedError, lambda: p.coeff(x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y))
def test_Poly_nth():
assert Poly(0, x).nth(0) == 0
assert Poly(0, x).nth(1) == 0
assert Poly(1, x).nth(0) == 1
assert Poly(1, x).nth(1) == 0
assert Poly(x**8, x).nth(0) == 0
assert Poly(x**8, x).nth(7) == 0
assert Poly(x**8, x).nth(8) == 1
assert Poly(x**8, x).nth(9) == 0
assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1
assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3
raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1))
def test_Poly_LM():
assert Poly(0, x).LM() == (0,)
assert Poly(1, x).LM() == (0,)
assert Poly(2*x**2 + x, x).LM() == (2,)
assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3)
assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7)
assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3
assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_LM_custom_order():
f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1)
rev_lex = lambda monom: tuple(reversed(monom))
assert f.LM(order='lex') == (2, 3, 1)
assert f.LM(order=rev_lex) == (2, 1, 3)
def test_Poly_EM():
assert Poly(0, x).EM() == (0,)
assert Poly(1, x).EM() == (0,)
assert Poly(2*x**2 + x, x).EM() == (1,)
assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7)
assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3)
def test_Poly_LT():
assert Poly(0, x).LT() == ((0,), 0)
assert Poly(1, x).LT() == ((0,), 1)
assert Poly(2*x**2 + x, x).LT() == ((2,), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1)
assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3
assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_ET():
assert Poly(0, x).ET() == ((0,), 0)
assert Poly(1, x).ET() == ((0,), 1)
assert Poly(2*x**2 + x, x).ET() == ((1,), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2)
def test_Poly_max_norm():
assert Poly(-1, x).max_norm() == 1
assert Poly( 0, x).max_norm() == 0
assert Poly( 1, x).max_norm() == 1
def test_Poly_l1_norm():
assert Poly(-1, x).l1_norm() == 1
assert Poly( 0, x).l1_norm() == 0
assert Poly( 1, x).l1_norm() == 1
def test_Poly_clear_denoms():
coeff, poly = Poly(x + 2, x).clear_denoms()
assert coeff == 1 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/2 + 1, x).clear_denoms()
assert coeff == 2 and poly == Poly(
x + 2, x, domain='QQ') and poly.get_domain() == QQ
coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True)
assert coeff == 2 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True)
assert coeff == y and poly == Poly(
x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y]
coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms()
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
coeff, poly = Poly(
x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True)
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
def test_Poly_rat_clear_denoms():
f = Poly(x**2/y + 1, x)
g = Poly(x**3 + y, x)
assert f.rat_clear_denoms(g) == \
(Poly(x**2 + y, x), Poly(y*x**3 + y**2, x))
f = f.set_domain(EX)
g = g.set_domain(EX)
assert f.rat_clear_denoms(g) == (f, g)
def test_issue_20427():
f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 +
253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 +
253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201
+ 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**
(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3))
+ 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(
217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*
sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**(
S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3)
+ 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x)
assert f == Poly(0, x, domain='EX')
def test_Poly_integrate():
assert Poly(x + 1).integrate() == Poly(x**2/2 + x)
assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x)
assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x)
assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x)
assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y)
assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y)
assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y)
def test_Poly_diff():
assert Poly(x**2 + x).diff() == Poly(2*x + 1)
assert Poly(x**2 + x).diff(x) == Poly(2*x + 1)
assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1)
assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y)
assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x)
assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1)
assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1)
def test_issue_9585():
assert diff(Poly(x**2 + x)) == Poly(2*x + 1)
assert diff(Poly(x**2 + x), x, evaluate=False) == \
Derivative(Poly(x**2 + x), x)
assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1)
def test_Poly_eval():
assert Poly(0, x).eval(7) == 0
assert Poly(1, x).eval(7) == 1
assert Poly(x, x).eval(7) == 7
assert Poly(0, x).eval(0, 7) == 0
assert Poly(1, x).eval(0, 7) == 1
assert Poly(x, x).eval(0, 7) == 7
assert Poly(0, x).eval(x, 7) == 0
assert Poly(1, x).eval(x, 7) == 1
assert Poly(x, x).eval(x, 7) == 7
assert Poly(0, x).eval('x', 7) == 0
assert Poly(1, x).eval('x', 7) == 1
assert Poly(x, x).eval('x', 7) == 7
raises(PolynomialError, lambda: Poly(1, x).eval(1, 7))
raises(PolynomialError, lambda: Poly(1, x).eval(y, 7))
raises(PolynomialError, lambda: Poly(1, x).eval('y', 7))
assert Poly(123, x, y).eval(7) == Poly(123, y)
assert Poly(2*y, x, y).eval(7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(7) == Poly(7*y, y)
assert Poly(123, x, y).eval(x, 7) == Poly(123, y)
assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y)
assert Poly(123, x, y).eval(y, 7) == Poly(123, x)
assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x)
assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x)
assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y)
assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x)
assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49
assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48
assert Poly(x*y + y, x, y).eval((6, 7)) == 49
assert Poly(x*y + y, x, y).eval([6, 7]) == 49
assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2)
assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1
raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8)))
raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False))
# issue 6344
alpha = Symbol('alpha')
result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1)
f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]')
assert f.eval((z + 1)/(z - 1)) == result
g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]')
assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)')
def test_Poly___call__():
f = Poly(2*x*y + 3*x + y + 2*z)
assert f(2) == Poly(5*y + 2*z + 6)
assert f(2, 5) == Poly(2*z + 31)
assert f(2, 5, 7) == 45
def test_parallel_poly_from_expr():
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr([Poly(
x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(
x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([x - 1, Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(x - 1, x), Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \
[Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')]
raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1]))
def test_pdiv():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.pdiv(G) == (Q, R)
assert F.prem(G) == R
assert F.pquo(G) == Q
assert F.pexquo(G) == Q
assert pdiv(f, g) == (q, r)
assert prem(f, g) == r
assert pquo(f, g) == q
assert pexquo(f, g) == q
assert pdiv(f, g, x, y) == (q, r)
assert prem(f, g, x, y) == r
assert pquo(f, g, x, y) == q
assert pexquo(f, g, x, y) == q
assert pdiv(f, g, (x, y)) == (q, r)
assert prem(f, g, (x, y)) == r
assert pquo(f, g, (x, y)) == q
assert pexquo(f, g, (x, y)) == q
assert pdiv(F, G) == (Q, R)
assert prem(F, G) == R
assert pquo(F, G) == Q
assert pexquo(F, G) == Q
assert pdiv(f, g, polys=True) == (Q, R)
assert prem(f, g, polys=True) == R
assert pquo(f, g, polys=True) == Q
assert pexquo(f, g, polys=True) == Q
assert pdiv(F, G, polys=False) == (q, r)
assert prem(F, G, polys=False) == r
assert pquo(F, G, polys=False) == q
assert pexquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: pdiv(4, 2))
raises(ComputationFailed, lambda: prem(4, 2))
raises(ComputationFailed, lambda: pquo(4, 2))
raises(ComputationFailed, lambda: pexquo(4, 2))
def test_div():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.div(G) == (Q, R)
assert F.rem(G) == R
assert F.quo(G) == Q
assert F.exquo(G) == Q
assert div(f, g) == (q, r)
assert rem(f, g) == r
assert quo(f, g) == q
assert exquo(f, g) == q
assert div(f, g, x, y) == (q, r)
assert rem(f, g, x, y) == r
assert quo(f, g, x, y) == q
assert exquo(f, g, x, y) == q
assert div(f, g, (x, y)) == (q, r)
assert rem(f, g, (x, y)) == r
assert quo(f, g, (x, y)) == q
assert exquo(f, g, (x, y)) == q
assert div(F, G) == (Q, R)
assert rem(F, G) == R
assert quo(F, G) == Q
assert exquo(F, G) == Q
assert div(f, g, polys=True) == (Q, R)
assert rem(f, g, polys=True) == R
assert quo(f, g, polys=True) == Q
assert exquo(f, g, polys=True) == Q
assert div(F, G, polys=False) == (q, r)
assert rem(F, G, polys=False) == r
assert quo(F, G, polys=False) == q
assert exquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: div(4, 2))
raises(ComputationFailed, lambda: rem(4, 2))
raises(ComputationFailed, lambda: quo(4, 2))
raises(ComputationFailed, lambda: exquo(4, 2))
f, g = x**2 + 1, 2*x - 4
qz, rz = 0, x**2 + 1
qq, rq = x/2 + 1, 5
assert div(f, g) == (qq, rq)
assert div(f, g, auto=True) == (qq, rq)
assert div(f, g, auto=False) == (qz, rz)
assert div(f, g, domain=ZZ) == (qz, rz)
assert div(f, g, domain=QQ) == (qq, rq)
assert div(f, g, domain=ZZ, auto=True) == (qq, rq)
assert div(f, g, domain=ZZ, auto=False) == (qz, rz)
assert div(f, g, domain=QQ, auto=True) == (qq, rq)
assert div(f, g, domain=QQ, auto=False) == (qq, rq)
assert rem(f, g) == rq
assert rem(f, g, auto=True) == rq
assert rem(f, g, auto=False) == rz
assert rem(f, g, domain=ZZ) == rz
assert rem(f, g, domain=QQ) == rq
assert rem(f, g, domain=ZZ, auto=True) == rq
assert rem(f, g, domain=ZZ, auto=False) == rz
assert rem(f, g, domain=QQ, auto=True) == rq
assert rem(f, g, domain=QQ, auto=False) == rq
assert quo(f, g) == qq
assert quo(f, g, auto=True) == qq
assert quo(f, g, auto=False) == qz
assert quo(f, g, domain=ZZ) == qz
assert quo(f, g, domain=QQ) == qq
assert quo(f, g, domain=ZZ, auto=True) == qq
assert quo(f, g, domain=ZZ, auto=False) == qz
assert quo(f, g, domain=QQ, auto=True) == qq
assert quo(f, g, domain=QQ, auto=False) == qq
f, g, q = x**2, 2*x, x/2
assert exquo(f, g) == q
assert exquo(f, g, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False))
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ))
assert exquo(f, g, domain=QQ) == q
assert exquo(f, g, domain=ZZ, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False))
assert exquo(f, g, domain=QQ, auto=True) == q
assert exquo(f, g, domain=QQ, auto=False) == q
f, g = Poly(x**2), Poly(x)
q, r = f.div(g)
assert q.get_domain().is_ZZ and r.get_domain().is_ZZ
r = f.rem(g)
assert r.get_domain().is_ZZ
q = f.quo(g)
assert q.get_domain().is_ZZ
q = f.exquo(g)
assert q.get_domain().is_ZZ
f, g = Poly(x+y, x), Poly(2*x+y, x)
q, r = f.div(g)
assert q.get_domain().is_Frac and r.get_domain().is_Frac
# https://github.com/sympy/sympy/issues/19579
p = Poly(2+3*I, x, domain=ZZ_I)
q = Poly(1-I, x, domain=ZZ_I)
assert p.div(q, auto=False) == \
(Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I'))
assert p.div(q, auto=True) == \
(Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I'))
def test_issue_7864():
q, r = div(a, .408248290463863*a)
assert abs(q - 2.44948974278318) < 1e-14
assert r == 0
def test_gcdex():
f, g = 2*x, x**2 - 16
s, t, h = x/32, Rational(-1, 16), 1
F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ]
assert F.half_gcdex(G) == (S, H)
assert F.gcdex(G) == (S, T, H)
assert F.invert(G) == S
assert half_gcdex(f, g) == (s, h)
assert gcdex(f, g) == (s, t, h)
assert invert(f, g) == s
assert half_gcdex(f, g, x) == (s, h)
assert gcdex(f, g, x) == (s, t, h)
assert invert(f, g, x) == s
assert half_gcdex(f, g, (x,)) == (s, h)
assert gcdex(f, g, (x,)) == (s, t, h)
assert invert(f, g, (x,)) == s
assert half_gcdex(F, G) == (S, H)
assert gcdex(F, G) == (S, T, H)
assert invert(F, G) == S
assert half_gcdex(f, g, polys=True) == (S, H)
assert gcdex(f, g, polys=True) == (S, T, H)
assert invert(f, g, polys=True) == S
assert half_gcdex(F, G, polys=False) == (s, h)
assert gcdex(F, G, polys=False) == (s, t, h)
assert invert(F, G, polys=False) == s
assert half_gcdex(100, 2004) == (-20, 4)
assert gcdex(100, 2004) == (-20, 1, 4)
assert invert(3, 7) == 5
raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False))
def test_revert():
f = Poly(1 - x**2/2 + x**4/24 - x**6/720)
g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1)
assert f.revert(8) == g
def test_subresultants():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.subresultants(G) == [F, G, H]
assert subresultants(f, g) == [f, g, h]
assert subresultants(f, g, x) == [f, g, h]
assert subresultants(f, g, (x,)) == [f, g, h]
assert subresultants(F, G) == [F, G, H]
assert subresultants(f, g, polys=True) == [F, G, H]
assert subresultants(F, G, polys=False) == [f, g, h]
raises(ComputationFailed, lambda: subresultants(4, 2))
def test_resultant():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
F, G = Poly(f), Poly(g)
assert F.resultant(G) == h
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == h
assert resultant(f, g, polys=True) == h
assert resultant(F, G, polys=False) == h
assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2])
f, g, h = x - a, x - b, a - b
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.resultant(G) == H
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == H
assert resultant(f, g, polys=True) == H
assert resultant(F, G, polys=False) == h
raises(ComputationFailed, lambda: resultant(4, 2))
def test_discriminant():
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
F = Poly(f)
assert F.discriminant() == g
assert discriminant(f) == g
assert discriminant(f, x) == g
assert discriminant(f, (x,)) == g
assert discriminant(F) == g
assert discriminant(f, polys=True) == g
assert discriminant(F, polys=False) == g
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
F, G = Poly(f), Poly(g)
assert F.discriminant() == G
assert discriminant(f) == g
assert discriminant(f, x, a, b, c) == g
assert discriminant(f, (x, a, b, c)) == g
assert discriminant(F) == G
assert discriminant(f, polys=True) == G
assert discriminant(F, polys=False) == g
raises(ComputationFailed, lambda: discriminant(4))
def test_dispersion():
# We test only the API here. For more mathematical
# tests see the dedicated test file.
fp = poly((x + 1)*(x + 2), x)
assert sorted(fp.dispersionset()) == [0, 1]
assert fp.dispersion() == 1
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(fp.dispersionset(gp)) == [2, 3, 4]
assert fp.dispersion(gp) == 4
def test_gcd_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert gcd_list(F) == x - 1
assert gcd_list(F, polys=True) == Poly(x - 1)
assert gcd_list([]) == 0
assert gcd_list([1, 2]) == 1
assert gcd_list([4, 6, 8]) == 2
assert gcd_list([x*(y + 42) - x*y - x*42]) == 0
gcd = gcd_list([], x)
assert gcd.is_Number and gcd is S.Zero
gcd = gcd_list([], x, polys=True)
assert gcd.is_Poly and gcd.is_zero
a = sqrt(2)
assert gcd_list([a, -a]) == gcd_list([-a, a]) == a
raises(ComputationFailed, lambda: gcd_list([], polys=True))
def test_lcm_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2
assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2)
assert lcm_list([]) == 1
assert lcm_list([1, 2]) == 2
assert lcm_list([4, 6, 8]) == 24
assert lcm_list([x*(y + 42) - x*y - x*42]) == 0
lcm = lcm_list([], x)
assert lcm.is_Number and lcm is S.One
lcm = lcm_list([], x, polys=True)
assert lcm.is_Poly and lcm.is_one
raises(ComputationFailed, lambda: lcm_list([], polys=True))
def test_gcd():
f, g = x**3 - 1, x**2 - 1
s, t = x**2 + x + 1, x + 1
h, r = x - 1, x**4 + x**3 - x - 1
F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ]
assert F.cofactors(G) == (H, S, T)
assert F.gcd(G) == H
assert F.lcm(G) == R
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == r
assert cofactors(f, g, x) == (h, s, t)
assert gcd(f, g, x) == h
assert lcm(f, g, x) == r
assert cofactors(f, g, (x,)) == (h, s, t)
assert gcd(f, g, (x,)) == h
assert lcm(f, g, (x,)) == r
assert cofactors(F, G) == (H, S, T)
assert gcd(F, G) == H
assert lcm(F, G) == R
assert cofactors(f, g, polys=True) == (H, S, T)
assert gcd(f, g, polys=True) == H
assert lcm(f, g, polys=True) == R
assert cofactors(F, G, polys=False) == (h, s, t)
assert gcd(F, G, polys=False) == h
assert lcm(F, G, polys=False) == r
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
assert cofactors(8, 6) == (2, 4, 3)
assert gcd(8, 6) == 2
assert lcm(8, 6) == 24
f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4
l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4
h, s, t = x - 4, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11) == (h, s, t)
assert gcd(f, g, modulus=11) == h
assert lcm(f, g, modulus=11) == l
f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7
l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7
h, s, t = x + 7, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t)
assert gcd(f, g, modulus=11, symmetric=False) == h
assert lcm(f, g, modulus=11, symmetric=False) == l
a, b = sqrt(2), -sqrt(2)
assert gcd(a, b) == gcd(b, a) == a
a, b = sqrt(-2), -sqrt(-2)
assert gcd(a, b) in (a, b)
raises(TypeError, lambda: gcd(x))
raises(TypeError, lambda: lcm(x))
def test_gcd_numbers_vs_polys():
assert isinstance(gcd(3, 9), Integer)
assert isinstance(gcd(3*x, 9), Integer)
assert gcd(3, 9) == 3
assert gcd(3*x, 9) == 3
assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational)
assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational)
assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4)
assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1
assert isinstance(gcd(3.0, 9.0), Float)
assert isinstance(gcd(3.0*x, 9.0), Float)
assert gcd(3.0, 9.0) == 1.0
assert gcd(3.0*x, 9.0) == 1.0
def test_terms_gcd():
assert terms_gcd(1) == 1
assert terms_gcd(1, x) == 1
assert terms_gcd(x - 1) == x - 1
assert terms_gcd(-x - 1) == -x - 1
assert terms_gcd(2*x + 3) == 2*x + 3
assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False)
assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2)
assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2)
assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2)
assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2)
assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2)
assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3)
assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \
(3*x + 3)*(x*y + x)
assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \
3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1)
assert terms_gcd(sin(x + x*y), deep=True) == \
sin(x*(y + 1))
eq = Eq(2*x, 2*y + 2*z*y)
assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1))
assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1))
raises(TypeError, lambda: terms_gcd(x < 2))
def test_trunc():
f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f = Poly(x**2 + 2*x + 3, modulus=5)
assert f.trunc(2) == Poly(x**2 + 1, modulus=5)
def test_monic():
f, g = 2*x - 1, x - S.Half
F, G = Poly(f, domain='QQ'), Poly(g)
assert F.monic() == G
assert monic(f) == g
assert monic(f, x) == g
assert monic(f, (x,)) == g
assert monic(F) == G
assert monic(f, polys=True) == G
assert monic(F, polys=False) == g
raises(ComputationFailed, lambda: monic(4))
assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2
raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False))
assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0
assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2
def test_content():
f, F = 4*x + 2, Poly(4*x + 2)
assert F.content() == 2
assert content(f) == 2
raises(ComputationFailed, lambda: content(4))
f = Poly(2*x, modulus=3)
assert f.content() == 1
def test_primitive():
f, g = 4*x + 2, 2*x + 1
F, G = Poly(f), Poly(g)
assert F.primitive() == (2, G)
assert primitive(f) == (2, g)
assert primitive(f, x) == (2, g)
assert primitive(f, (x,)) == (2, g)
assert primitive(F) == (2, G)
assert primitive(f, polys=True) == (2, G)
assert primitive(F, polys=False) == (2, g)
raises(ComputationFailed, lambda: primitive(4))
f = Poly(2*x, modulus=3)
g = Poly(2.0*x, domain=RR)
assert f.primitive() == (1, f)
assert g.primitive() == (1.0, g)
assert primitive(S('-3*x/4 + y + 11/8')) == \
S('(1/8, -6*x + 8*y + 11)')
def test_compose():
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
F, G, H = map(Poly, (f, g, h))
assert G.compose(H) == F
assert compose(g, h) == f
assert compose(g, h, x) == f
assert compose(g, h, (x,)) == f
assert compose(G, H) == F
assert compose(g, h, polys=True) == F
assert compose(G, H, polys=False) == f
assert F.decompose() == [G, H]
assert decompose(f) == [g, h]
assert decompose(f, x) == [g, h]
assert decompose(f, (x,)) == [g, h]
assert decompose(F) == [G, H]
assert decompose(f, polys=True) == [G, H]
assert decompose(F, polys=False) == [g, h]
raises(ComputationFailed, lambda: compose(4, 2))
raises(ComputationFailed, lambda: decompose(4))
assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y
assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y
def test_shift():
assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x)
def test_transform():
# Also test that 3-way unification is done correctly
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(4, x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(3*x**2/2 + Rational(5, 2), x) == \
cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \
Poly(Rational(9, 4), x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x) == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half)))
# Unify ZZ, QQ, and RR
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x, domain='RR') == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half)))
raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1)))
def test_sturm():
f, F = x, Poly(x, domain='QQ')
g, G = 1, Poly(1, x, domain='QQ')
assert F.sturm() == [F, G]
assert sturm(f) == [f, g]
assert sturm(f, x) == [f, g]
assert sturm(f, (x,)) == [f, g]
assert sturm(F) == [F, G]
assert sturm(f, polys=True) == [F, G]
assert sturm(F, polys=False) == [f, g]
raises(ComputationFailed, lambda: sturm(4))
raises(DomainError, lambda: sturm(f, auto=False))
f = Poly(S(1024)/(15625*pi**8)*x**5
- S(4096)/(625*pi**8)*x**4
+ S(32)/(15625*pi**4)*x**3
- S(128)/(625*pi**4)*x**2
+ Rational(1, 62500)*x
- Rational(1, 625), x, domain='ZZ(pi)')
assert sturm(f) == \
[Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'),
Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'),
Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'),
Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')]
def test_gff():
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)]
assert gff_list(f) == [(x, 1), (x + 2, 4)]
raises(NotImplementedError, lambda: gff(f))
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert Poly(f).gff_list() == [(
Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)]
assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
raises(NotImplementedError, lambda: gff(f))
def test_norm():
a, b = sqrt(2), sqrt(3)
f = Poly(a*x + b*y, x, y, extension=(a, b))
assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ')
def test_sqf_norm():
assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \
(1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1)
assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \
(1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1)
assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
def test_sqf():
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
F, G, H, P = map(Poly, (f, g, h, p))
assert F.sqf_part() == P
assert sqf_part(f) == p
assert sqf_part(f, x) == p
assert sqf_part(f, (x,)) == p
assert sqf_part(F) == P
assert sqf_part(f, polys=True) == P
assert sqf_part(F, polys=False) == p
assert F.sqf_list() == (1, [(G, 1), (H, 2)])
assert sqf_list(f) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, x) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)])
assert sqf_list(F) == (1, [(G, 1), (H, 2)])
assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)])
assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)])
assert F.sqf_list_include() == [(G, 1), (H, 2)]
raises(ComputationFailed, lambda: sqf_part(4))
assert sqf(1) == 1
assert sqf_list(1) == (1, [])
assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert sqf(f) == g*h**2
assert sqf(f, x) == g*h**2
assert sqf(f, (x,)) == g*h**2
d = x**2 + y**2
assert sqf(f/d) == (g*h**2)/d
assert sqf(f/d, x) == (g*h**2)/d
assert sqf(f/d, (x,)) == (g*h**2)/d
assert sqf(x - 1) == x - 1
assert sqf(-x - 1) == -x - 1
assert sqf(x - 1) == x - 1
assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2))
assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2
f = 3 + x - x*(1 + x) + x**2
assert sqf(f) == 3
f = (x**2 + 2*x + 1)**20000000000
assert sqf(f) == (x + 1)**40000000000
assert sqf_list(f) == (1, [(x + 1, 40000000000)])
def test_factor():
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
F, U, V, W = map(Poly, (f, u, v, w))
assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)])
assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)]
assert factor_list(1) == (1, [])
assert factor_list(6) == (6, [])
assert factor_list(sqrt(3), x) == (sqrt(3), [])
assert factor_list((-1)**x, x) == (1, [(-1, x)])
assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)])
assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)])
assert factor(6) == 6 and factor(6).is_Integer
assert factor_list(3*x) == (3, [(x, 1)])
assert factor_list(3*x**2) == (3, [(x, 2)])
assert factor(3*x) == 3*x
assert factor(3*x**2) == 3*x**2
assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert factor(f) == u*v**2*w
assert factor(f, x) == u*v**2*w
assert factor(f, (x,)) == u*v**2*w
g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1
assert factor(f/g) == (u*v**2*w)/(p*q)
assert factor(f/g, x) == (u*v**2*w)/(p*q)
assert factor(f/g, (x,)) == (u*v**2*w)/(p*q)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
r = Symbol('r', real=True)
assert factor(sqrt(x*y)).is_Pow is True
assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1))
assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1)
assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i
assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i
assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t
assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t
f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3))
g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1)
assert factor(f) == g
assert factor(g) == g
g = (x - 1)**5*(r**2 + 1)
f = sqrt(expand(g))
assert factor(f) == sqrt(g)
f = Poly(sin(1)*x + 1, x, domain=EX)
assert f.factor_list() == (1, [(f, 1)])
f = x**4 + 1
assert factor(f) == f
assert factor(f, extension=I) == (x**2 - I)*(x**2 + I)
assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I)
assert factor(
f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1)
assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2
f = x**2 + 2*I*x - 4
assert factor(f) == f
f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I
f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2
f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2
assert factor(f) == f_zzi
assert factor(f, domain=ZZ_I) == f_zzi
assert factor(f, domain=QQ_I) == f_qqi
f = x**2 + 2*sqrt(2)*x + 2
assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2
assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6
assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \
(x + sqrt(2)*y)*(x - sqrt(2)*y)
assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \
2*((x + sqrt(2)*y)*(x - sqrt(2)*y))
assert factor(x - 1) == x - 1
assert factor(-x - 1) == -x - 1
assert factor(x - 1) == x - 1
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \
(x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1)
assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \
(x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 +
x**3 + 65536*x** 2 + 1)
f = x/pi + x*sin(x)/pi
g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1)
assert factor(f) == x*(sin(x) + 1)/pi
assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2
assert factor(Eq(
x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1))
f = (x**2 - 1)/(x**2 + 4*x + 4)
assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2
assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2
f = 3 + x - x*(1 + x) + x**2
assert factor(f) == 3
assert factor(f, x) == 3
assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 +
x**3)/(1 + 2*x**2 + x**3))
assert factor(f, expand=False) == f
raises(PolynomialError, lambda: factor(f, x, expand=False))
raises(FlagError, lambda: factor(x**2 - 1, polys=True))
assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \
[x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))]
assert not isinstance(
Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert isinstance(
PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert factor(sqrt(-x)) == sqrt(-x)
# issue 5917
e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x -
1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) +
x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)))
assert factor(e) == 0
# deep option
assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x
assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x
assert factor(sqrt(x**2)) == sqrt(x**2)
# issue 13149
assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0,
0.5*y + 1.0, evaluate = False)
assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2
eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360
assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12)
# fraction option
f = 5*x + 3*exp(2 - 7*x)
assert factor(f, deep=True) == factor(f, deep=True, fraction=True)
assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x)
def test_factor_large():
f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567
g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + (
x**2 + 2*x + 1)**3000)
assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134
assert factor(g) == (x + 1)**6000*(y + 1)**2
assert factor_list(
f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)])
assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)])
f = (x**2 - y**2)**200000*(x**7 + 1)
g = (x**2 + y**2)**200000*(x**7 + 1)
assert factor(f) == \
(x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor(g, gaussian=True) == \
(x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor_list(f) == \
(1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 -
x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
assert factor_list(g, gaussian=True) == \
(1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), (
x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
def test_factor_noeval():
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2))
def test_intervals():
assert intervals(0) == []
assert intervals(1) == []
assert intervals(x, sqf=True) == [(0, 0)]
assert intervals(x) == [((0, 0), 1)]
assert intervals(x**128) == [((0, 0), 128)]
assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})]
f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)))
assert f.intervals(sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))
assert intervals(f, sqf=True) == [(-1, 0), (14, 15)]
assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)]
assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3)
assert f.intervals() == \
[((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1),
((-1, -1), 1), ((-1, 0), 3),
((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)]
assert intervals([x**5 - 200, x**5 - 201]) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**5 - 200, x**5 - 201], fast=True) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**2 - 200, x**2 - 201]) == \
[((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}),
((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})]
assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \
[((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2:
1, 5: 1, 6: 1}), ((2, 2), {7: 2})]
f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1
assert intervals(f, inf=Rational(7, 4), sqf=True) == []
assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))]
assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))]
assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)]
assert intervals(g, inf=Rational(7, 4)) == []
assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)]
assert intervals([g, h], inf=Rational(7, 4)) == []
assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})]
assert intervals([g, h], sup=S(
7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})]
assert intervals(
[g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})]
assert intervals([x + 2, x**2 - 2]) == \
[((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})]
assert intervals([x + 2, x**2 - 2], strict=True) == \
[((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})]
f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20
assert intervals(f) == []
real_part, complex_part = intervals(f, all=True, sqf=True)
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
assert complex_part == [(Rational(-40, 7) - I*Rational(40, 7), 0),
(Rational(-40, 7), I*Rational(40, 7)),
(I*Rational(-40, 7), Rational(40, 7)),
(0, Rational(40, 7) + I*Rational(40, 7))]
real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10))
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000))
raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000))
raises(
ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000))
def test_refine_root():
f = Poly(x**2 - 2)
assert f.refine_root(1, 2, steps=0) == (1, 2)
assert f.refine_root(-2, -1, steps=0) == (-2, -1)
assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True))
raises(RefinementFailed, lambda: (f**2).refine_root(1, 2))
raises(RefinementFailed, lambda: (f**2).refine_root(2, 3))
f = x**2 - 2
assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100)))
raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000))
raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000))
def test_count_roots():
assert count_roots(x**2 - 2) == 2
assert count_roots(x**2 - 2, inf=-oo) == 2
assert count_roots(x**2 - 2, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-2) == 2
assert count_roots(x**2 - 2, inf=-1) == 1
assert count_roots(x**2 - 2, sup=1) == 1
assert count_roots(x**2 - 2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 + 2) == 0
assert count_roots(x**2 + 2, inf=-2*I) == 2
assert count_roots(x**2 + 2, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=0) == 0
assert count_roots(x**2 + 2, sup=0) == 0
assert count_roots(x**2 + 2, inf=-I) == 1
assert count_roots(x**2 + 2, sup=+I) == 1
assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0
assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0
raises(PolynomialError, lambda: count_roots(1))
def test_Poly_root():
f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
assert f.root(0) == Rational(-1, 2)
assert f.root(1) == 2
assert f.root(2) == 2
raises(IndexError, lambda: f.root(3))
assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0)
def test_real_roots():
assert real_roots(x) == [0]
assert real_roots(x, multiple=False) == [(0, 1)]
assert real_roots(x**3) == [0, 0, 0]
assert real_roots(x**3, multiple=False) == [(0, 3)]
assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0]
assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 1)]
assert real_roots(
x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0]
assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 3)]
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).real_roots() == [rootof(g, 0)]
def test_all_roots():
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)]
def test_nroots():
assert Poly(0, x).nroots() == []
assert Poly(1, x).nroots() == []
assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0]
assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I]
roots = Poly(x**2 - 1, x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2 + 1, x).nroots()
assert roots == [-1.0*I, 1.0*I]
roots = Poly(x**2/3 - Rational(1, 3), x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2/3 + Rational(1, 3), x).nroots()
assert roots == [-1.0*I, 1.0*I]
assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(
x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(0.2*x + 0.1).nroots() == [-0.5]
roots = nroots(x**5 + x + 1, n=5)
eps = Float("1e-5")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true
eps = Float("1e-6")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false
raises(DomainError, lambda: Poly(x + y, x).nroots())
raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots())
assert nroots(x**2 - 1) == [-1.0, 1.0]
roots = nroots(x**2 - 1)
assert roots == [-1.0, 1.0]
assert nroots(x + I) == [-1.0*I]
assert nroots(x + 2*I) == [-2.0*I]
raises(PolynomialError, lambda: nroots(0))
# issue 8296
f = Poly(x**4 - 1)
assert f.nroots(2) == [w.n(2) for w in f.all_roots()]
assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 +
39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 +
877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 '
'- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, '
'2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, '
'1.7 + 2.5*I]')
def test_ground_roots():
f = x**6 - 4*x**4 + 4*x**3 - x**2
assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2}
assert ground_roots(f) == {S.One: 2, S.Zero: 2}
def test_nth_power_roots_poly():
f = x**4 - x**2 + 1
f_2 = (x**2 - x + 1)**2
f_3 = (x**2 + 1)**2
f_4 = (x**2 + x + 1)**2
f_12 = (x - 1)**4
assert nth_power_roots_poly(f, 1) == f
raises(ValueError, lambda: nth_power_roots_poly(f, 0))
raises(ValueError, lambda: nth_power_roots_poly(f, x))
assert factor(nth_power_roots_poly(f, 2)) == f_2
assert factor(nth_power_roots_poly(f, 3)) == f_3
assert factor(nth_power_roots_poly(f, 4)) == f_4
assert factor(nth_power_roots_poly(f, 12)) == f_12
raises(MultivariatePolynomialError, lambda: nth_power_roots_poly(
x + y, 2, x, y))
def test_torational_factor_list():
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
assert _torational_factor_list(p, x) == (-2, [
(-x*(1 + sqrt(2))/2 + 1, 1),
(-x*(1 + sqrt(2)) - 1, 1),
(-x*(1 + sqrt(2)) + 1, 1)])
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))}))
assert _torational_factor_list(p, x) is None
def test_cancel():
assert cancel(0) == 0
assert cancel(7) == 7
assert cancel(x) == x
assert cancel(oo) is oo
assert cancel((2, 3)) == (1, 2, 3)
assert cancel((1, 0), x) == (1, 1, 0)
assert cancel((0, 1), x) == (1, 0, 1)
f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1
F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ]
assert F.cancel(G) == (1, P, Q)
assert cancel((f, g)) == (1, p, q)
assert cancel((f, g), x) == (1, p, q)
assert cancel((f, g), (x,)) == (1, p, q)
assert cancel((F, G)) == (1, P, Q)
assert cancel((f, g), polys=True) == (1, P, Q)
assert cancel((F, G), polys=False) == (1, p, q)
f = (x**2 - 2)/(x + sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x - sqrt(2)
f = (x**2 - 2)/(x - sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x + sqrt(2)
assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2)
# assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1)
assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y)
assert cancel((x**2 - y**2)/(x - y), x) == x + y
assert cancel((x**2 - y**2)/(x - y), y) == x + y
assert cancel((x**2 - y**2)/(x - y)) == x + y
assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1)
assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2)
assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1
f = Poly(x**2 - a**2, x)
g = Poly(x - a, x)
F = Poly(x + a, x, domain='ZZ[a]')
G = Poly(1, x, domain='ZZ[a]')
assert cancel((f, g)) == (1, F, G)
f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2)
g = x**2 - 2
assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2))
f = Poly(-2*x + 3, x)
g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x)
assert cancel((f, g)) == (1, -f, -g)
f = Poly(y, y, domain='ZZ(x)')
g = Poly(1, y, domain='ZZ[x]')
assert f.cancel(
g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
assert f.cancel(g, include=True) == (
Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
f = Poly(5*x*y + x, y, domain='ZZ(x)')
g = Poly(2*x**2*y, y, domain='ZZ(x)')
assert f.cancel(g, include=True) == (
Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)'))
f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2))
assert cancel(f).is_Mul == True
P = tanh(x - 3.0)
Q = tanh(x + 3.0)
f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \
+ (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2))
assert cancel(f).is_Mul == True
# issue 7022
A = Symbol('A', commutative=False)
p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p2 = Piecewise((A*(x - 1), x > 1), (1/x, True))
assert cancel(p1) == p2
assert cancel(2*p1) == 2*p2
assert cancel(1 + p1) == 1 + p2
assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2
assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2
p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p4 = Piecewise(((x - 1), x > 1), (1/x, True))
assert cancel(p3) == p4
assert cancel(2*p3) == 2*p4
assert cancel(1 + p3) == 1 + p4
assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4
assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4
# issue 9363
M = MatrixSymbol('M', 5, 5)
assert cancel(M[0,0] + 7) == M[0,0] + 7
expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z
assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z
assert cancel((x**2 + 1)/(x - I)) == x + I
def test_reduced():
f = 2*x**4 + y**2 - x**2 + y**3
G = [x**3 - x, y**3 - y]
Q = [2*x, 1]
r = x**2 + y**2 + y
assert reduced(f, G) == (Q, r)
assert reduced(f, G, x, y) == (Q, r)
H = groebner(G)
assert H.reduce(f) == (Q, r)
Q = [Poly(2*x, x, y), Poly(1, x, y)]
r = Poly(x**2 + y**2 + y, x, y)
assert _strict_eq(reduced(f, G, polys=True), (Q, r))
assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r))
H = groebner(G, polys=True)
assert _strict_eq(H.reduce(f), (Q, r))
f = 2*x**3 + y**3 + 3*y
G = groebner([x**2 + y**2 - 1, x*y - 2])
Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)]
r = 0
assert reduced(f, G) == (Q, r)
assert G.reduce(f) == (Q, r)
assert reduced(f, G, auto=False)[1] != 0
assert G.reduce(f, auto=False)[1] != 0
assert G.contains(f) is True
assert G.contains(f + 1) is False
assert reduced(1, [1], x) == ([1], 0)
raises(ComputationFailed, lambda: reduced(1, [1]))
def test_groebner():
assert groebner([], x, y, z) == []
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2]
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \
[Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \
[Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)]
assert groebner([x**3 - 1, x**2 - 1]) == [x - 1]
assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1]
F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2]
f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5
G = groebner(F, x, y, z, modulus=7, symmetric=False)
assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5,
1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6,
1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6,
6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7]
Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True)
assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7)
F = [x*y - 2*y, 2*y**2 - x**2]
assert groebner(F, x, y, order='grevlex') == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner(F, y, x, order='grevlex') == \
[x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y]
assert groebner(F, order='grevlex', field=True) == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner([1], x) == [1]
assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y]
raises(ComputationFailed, lambda: groebner([1]))
assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1]
assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1]
raises(ValueError, lambda: groebner([x, y], method='unknown'))
def test_fglm():
F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1]
G = groebner(F, a, b, c, d, order=grlex)
B = [
4*a + 3*d**9 - 4*d**5 - 3*d,
4*b + 4*c - 3*d**9 + 4*d**5 + 7*d,
4*c**2 + 3*d**10 - 4*d**6 - 3*d**2,
4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d,
d**12 - d**8 - d**4 + 1,
]
assert groebner(F, a, b, c, d, order=lex) == B
assert G.fglm(lex) == B
F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
-72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \
108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96]
G = groebner(F, t, x, order=grlex)
B = [
203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \
10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \
20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194,
9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
]
assert groebner(F, t, x, order=lex) == B
assert G.fglm(lex) == B
F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1]
G = groebner(F, x, y, order=lex)
B = [
x**2 - x - 3*y + 1,
y**2 - 2*x + y - 1,
]
assert groebner(F, x, y, order=grlex) == B
assert G.fglm(grlex) == B
def test_is_zero_dimensional():
assert is_zero_dimensional([x, y], x, y) is True
assert is_zero_dimensional([x**3 + y**2], x, y) is False
assert is_zero_dimensional([x, y, z], x, y, z) is True
assert is_zero_dimensional([x, y, z], x, y, z, t) is False
F = [x*y - z, y*z - x, x*y - y]
assert is_zero_dimensional(F, x, y, z) is True
F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2]
assert is_zero_dimensional(F, x, y, z) is True
def test_GroebnerBasis():
F = [x*y - 2*y, 2*y**2 - x**2]
G = groebner(F, x, y, order='grevlex')
H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
P = [ Poly(h, x, y) for h in H ]
assert groebner(F + [0], x, y, order='grevlex') == G
assert isinstance(G, GroebnerBasis) is True
assert len(G) == 3
assert G[0] == H[0] and not G[0].is_Poly
assert G[1] == H[1] and not G[1].is_Poly
assert G[2] == H[2] and not G[2].is_Poly
assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:])
assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:])
assert G.exprs == H
assert G.polys == P
assert G.gens == (x, y)
assert G.domain == ZZ
assert G.order == grevlex
assert G == H
assert G == tuple(H)
assert G == P
assert G == tuple(P)
assert G != []
G = groebner(F, x, y, order='grevlex', polys=True)
assert G[0] == P[0] and G[0].is_Poly
assert G[1] == P[1] and G[1].is_Poly
assert G[2] == P[2] and G[2].is_Poly
assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:])
assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:])
def test_poly():
assert poly(x) == Poly(x, x)
assert poly(y) == Poly(y, y)
assert poly(x + y) == Poly(x + y, x, y)
assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x))
assert poly(x + y, wrt=y) == Poly(x + y, y, x)
assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x)
assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z)
assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z)
assert poly(
x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z)
assert poly(2*x*(
y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z)
assert poly(2*(
y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z)
assert poly(x*(
y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z)
assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*
x*z**2 - x - 1, x, y, z)
assert poly(x*y + (x + y)**2 + (x + z)**2) == \
Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z)
assert poly(x*y*(x + y)*(x + z)**2) == \
Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2*
y**2 + 2*y*z*x**3 + y*x**4, x, y, z)
assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z)
assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y])
assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x])
assert poly(1, x) == Poly(1, x)
raises(GeneratorsNeeded, lambda: poly(1))
# issue 6184
assert poly(x + y, x, y) == Poly(x + y, x, y)
assert poly(x + y, y, x) == Poly(x + y, y, x)
def test_keep_coeff():
u = Mul(2, x + 1, evaluate=False)
assert _keep_coeff(S.One, x) == x
assert _keep_coeff(S.NegativeOne, x) == -x
assert _keep_coeff(S(1.0), x) == 1.0*x
assert _keep_coeff(S(-1.0), x) == -1.0*x
assert _keep_coeff(S.One, 2*x) == 2*x
assert _keep_coeff(S(2), x/2) == x
assert _keep_coeff(S(2), sin(x)) == 2*sin(x)
assert _keep_coeff(S(2), x + 1) == u
assert _keep_coeff(x, 1/x) == 1
assert _keep_coeff(x + 1, S(2)) == u
def test_poly_matching_consistency():
# Test for this issue:
# https://github.com/sympy/sympy/issues/5514
assert I * Poly(x, x) == Poly(I*x, x)
assert Poly(x, x) * I == Poly(I*x, x)
def test_issue_5786():
assert expand(factor(expand(
(x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z
def test_noncommutative():
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/( 1 + y)
assert cancel(foo(e)) == foo(c)
assert cancel(e + foo(e)) == c + foo(c)
assert cancel(e*foo(c)) == c*foo(c)
def test_to_rational_coeffs():
assert to_rational_coeffs(
Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None
def test_factor_terms():
# issue 7067
assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)])
def test_as_list():
# issue 14496
assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2]
assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]]
assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \
[[[1]], [[]], [[1], [1]]]
def test_issue_11198():
assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)])
assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)])
def test_Poly_precision():
# Make sure Poly doesn't lose precision
p = Poly(pi.evalf(100)*x)
assert p.as_expr() == pi.evalf(100)*x
def test_issue_12400():
# Correction of check for negative exponents
assert poly(1/(1+sqrt(2)), x) == \
Poly(1/(1+sqrt(2)), x , domain='EX')
def test_issue_14364():
assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3))
assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21)
assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3
assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3)
assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3))
assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18
assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14
# gcd_list and lcm_list
assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35)
assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455)
assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15)
assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7))
def test_issue_15669():
x = Symbol("x", positive=True)
expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 -
2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x)
assert factor(expr, deep=True) == x*(x**2 + 2)
def test_issue_17988():
x = Symbol('x')
p = poly(x - 1)
M = Matrix([[poly(x + 1), poly(x + 1)]])
assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]])
def test_issue_18205():
assert cancel((2 + I)*(3 - I)) == 7 + I
assert cancel((2 + I)*(2 - I)) == 5
def test_issue_8695():
p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3
result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)])
assert sqf_list(p) == result
def test_issue_19113():
eq = sin(x)**3 - sin(x) + 1
raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2))
raises(PolynomialError, lambda: count_roots(eq, -1, 1))
raises(PolynomialError, lambda: real_roots(eq))
raises(PolynomialError, lambda: nroots(eq))
raises(PolynomialError, lambda: ground_roots(eq))
raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2))
def test_issue_19360():
f = 2*x**2 - 2*sqrt(2)*x*y + y**2
assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2
f = -I*t*x - t*y + x*z - I*y*z
assert factor(f, extension=I) == (x - I*y)*(-I*t + z)
def test_poly_copy_equals_original():
poly = Poly(x + y, x, y, z)
copy = poly.copy()
assert poly == copy, (
"Copied polynomial not equal to original.")
assert poly.gens == copy.gens, (
"Copied polynomial has different generators than original.")
def test_deserialized_poly_equals_original():
poly = Poly(x + y, x, y, z)
deserialized = pickle.loads(pickle.dumps(poly))
assert poly == deserialized, (
"Deserialized polynomial not equal to original.")
assert poly.gens == deserialized.gens, (
"Deserialized polynomial has different generators than original.")
def test_issue_20389():
result = degree(x * (x + 1) - x ** 2 - x, x)
assert result == -oo
|
3694386f4cc3e0b32b7261ade43abed6148614fa621c9bc313782a3fc9ce6183 | from sympy.core.compatibility import HAS_GMPY
from sympy.core.numbers import Rational
from sympy.functions import sqrt
from sympy.matrices.common import (NonInvertibleMatrixError,
NonSquareMatrixError, ShapeError)
from sympy.matrices.dense import Matrix
from sympy.polys import ZZ, QQ
from sympy.polys.domainmatrix import (
DDM,
DDMBadInputError, DDMDomainError, DDMShapeError,
DomainMatrix,
ddm_iadd, ddm_isub, ddm_ineg, ddm_imatmul, ddm_imul,
ddm_irref, ddm_idet, ddm_iinv, ddm_ilu, ddm_ilu_split, ddm_ilu_solve,
ddm_berk,
)
from sympy.testing.pytest import raises
def test_DDM_init():
items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]]
shape = (2, 3)
ddm = DDM(items, shape, ZZ)
assert ddm.shape == shape
assert ddm.rows == 2
assert ddm.cols == 3
assert ddm.domain == ZZ
raises(DDMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ))
raises(DDMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ))
def test_DDM_getsetitem():
ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ)
assert ddm[0][0] == ZZ(2)
assert ddm[0][1] == ZZ(3)
assert ddm[1][0] == ZZ(4)
assert ddm[1][1] == ZZ(5)
raises(IndexError, lambda: ddm[2][0])
raises(IndexError, lambda: ddm[0][2])
ddm[0][0] = ZZ(-1)
assert ddm[0][0] == ZZ(-1)
def test_DDM_str():
ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)
if HAS_GMPY:
assert str(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)'
else:
assert str(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)'
def test_DDM_eq():
items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]]
ddm1 = DDM(items, (2, 2), ZZ)
ddm2 = DDM(items, (2, 2), ZZ)
assert (ddm1 == ddm1) is True
assert (ddm1 == items) is False
assert (items == ddm1) is False
assert (ddm1 == ddm2) is True
assert (ddm2 == ddm1) is True
assert (ddm1 != ddm1) is False
assert (ddm1 != items) is True
assert (items != ddm1) is True
assert (ddm1 != ddm2) is False
assert (ddm2 != ddm1) is False
ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ)
ddm3 = DDM(items, (2, 2), QQ)
assert (ddm1 == ddm3) is False
assert (ddm3 == ddm1) is False
assert (ddm1 != ddm3) is True
assert (ddm3 != ddm1) is True
def test_DDM_zeros():
ddmz = DDM.zeros((3, 4), QQ)
assert list(ddmz) == [[QQ(0)] * 4] * 3
assert ddmz.shape == (3, 4)
assert ddmz.domain == QQ
def test_DDM_eye():
ddmz = DDM.eye(3, QQ)
f = lambda i, j: QQ(1) if i == j else QQ(0)
assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)]
assert ddmz.shape == (3, 3)
assert ddmz.domain == QQ
def test_DDM_copy():
ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
ddm2 = ddm1.copy()
assert (ddm1 == ddm2) is True
ddm1[0][0] = QQ(-1)
assert (ddm1 == ddm2) is False
ddm2[0][0] = QQ(-1)
assert (ddm1 == ddm2) is True
def test_DDM_add():
A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ)
AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
assert A + B == A.add(B) == C
raises(DDMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ))
raises(TypeError, lambda: A + ZZ(1))
raises(TypeError, lambda: ZZ(1) + A)
raises(DDMDomainError, lambda: A + AQ)
raises(DDMDomainError, lambda: AQ + A)
def test_DDM_sub():
A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ)
AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
D = DDM([[ZZ(5)]], (1, 1), ZZ)
assert A - B == A.sub(B) == C
raises(TypeError, lambda: A - ZZ(1))
raises(TypeError, lambda: ZZ(1) - A)
raises(DDMShapeError, lambda: A - D)
raises(DDMShapeError, lambda: D - A)
raises(DDMShapeError, lambda: A.sub(D))
raises(DDMShapeError, lambda: D.sub(A))
raises(DDMDomainError, lambda: A - AQ)
raises(DDMDomainError, lambda: AQ - A)
raises(DDMDomainError, lambda: A.sub(AQ))
raises(DDMDomainError, lambda: AQ.sub(A))
def test_DDM_neg():
A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ)
assert -A == A.neg() == An
assert -An == An.neg() == A
def test_DDM_mul():
A = DDM([[ZZ(1)]], (1, 1), ZZ)
raises(TypeError, lambda: [[1]] * A)
raises(TypeError, lambda: A * [[1]])
def test_DDM_matmul():
A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ)
AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
BA = DDM([[ZZ(11)]], (1, 1), ZZ)
assert A @ B == A.matmul(B) == AB
assert B @ A == B.matmul(A) == BA
raises(TypeError, lambda: A @ 1)
raises(TypeError, lambda: A @ [[3, 4]])
Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ)
raises(DDMDomainError, lambda: A @ Bq)
raises(DDMDomainError, lambda: Bq @ A)
C = DDM([[ZZ(1)]], (1, 1), ZZ)
assert A @ C == A.matmul(C) == A
raises(DDMShapeError, lambda: C @ A)
raises(DDMShapeError, lambda: C.matmul(A))
Z04 = DDM([], (0, 4), ZZ)
Z40 = DDM([[]]*4, (4, 0), ZZ)
Z50 = DDM([[]]*5, (5, 0), ZZ)
Z05 = DDM([], (0, 5), ZZ)
Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ)
Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ)
Z00 = DDM([], (0, 0), ZZ)
assert Z04 @ Z45 == Z04.matmul(Z45) == Z05
assert Z45 @ Z50 == Z45.matmul(Z50) == Z40
assert Z00 @ Z04 == Z00.matmul(Z04) == Z04
assert Z50 @ Z00 == Z50.matmul(Z00) == Z50
assert Z00 @ Z00 == Z00.matmul(Z00) == Z00
assert Z50 @ Z04 == Z50.matmul(Z04) == Z54
raises(DDMShapeError, lambda: Z05 @ Z40)
raises(DDMShapeError, lambda: Z05.matmul(Z40))
def test_DDM_rref():
A = DDM([], (0, 4), QQ)
assert A.rref() == (A, [])
A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
pivots = [0, 1]
assert A.rref() == (Ar, pivots)
A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ)
Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
pivots = [0, 1]
assert A.rref() == (Ar, pivots)
A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ)
Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
pivots = [0, 1]
assert A.rref() == (Ar, pivots)
A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ)
Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ)
pivots = [0, 1]
assert A.rref() == (Ar, pivots)
A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ)
Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ)
pivots = [0, 2]
assert A.rref() == (Ar, pivots)
def test_DDM_det():
# 0x0 case
A = DDM([], (0, 0), ZZ)
assert A.det() == ZZ(1)
# 1x1 case
A = DDM([[ZZ(2)]], (1, 1), ZZ)
assert A.det() == ZZ(2)
# 2x2 case
A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.det() == ZZ(-2)
# 3x3 with swap
A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
assert A.det() == ZZ(0)
# 2x2 QQ case
A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ)
assert A.det() == QQ(-1, 24)
# Nonsquare error
A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
raises(DDMShapeError, lambda: A.det())
# Nonsquare error with empty matrix
A = DDM([], (0, 1), ZZ)
raises(DDMShapeError, lambda: A.det())
def test_DDM_inv():
A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ)
Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
assert A.inv() == Ainv
A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
raises(DDMShapeError, lambda: A.inv())
A = DDM([[ZZ(2)]], (1, 1), ZZ)
raises(ValueError, lambda: A.inv())
A = DDM([], (0, 0), QQ)
assert A.inv() == A
A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
raises(NonInvertibleMatrixError, lambda: A.inv())
def test_DDM_lu():
A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
L, U, swaps = A.lu()
assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
assert swaps == []
A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
A = DDM(to_dom(A, QQ), (4, 4), QQ)
Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ)
Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ)
L, U, swaps = A.lu()
assert L == Lexp
assert U == Uexp
assert swaps == []
def test_DDM_lu_solve():
# Basic example
A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
assert A.lu_solve(b) == x
# Example with swaps
A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
assert A.lu_solve(b) == x
# Overdetermined, consistent
A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
assert A.lu_solve(b) == x
# Overdetermined, inconsistent
b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
raises(NonInvertibleMatrixError, lambda: A.lu_solve(b))
# Square, noninvertible
A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
raises(NonInvertibleMatrixError, lambda: A.lu_solve(b))
# Underdetermined
A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
b = DDM([[QQ(3)]], (1, 1), QQ)
raises(NotImplementedError, lambda: A.lu_solve(b))
# Domain mismatch
bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
raises(DDMDomainError, lambda: A.lu_solve(bz))
# Shape mismatch
b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
raises(DDMShapeError, lambda: A.lu_solve(b3))
def test_DDM_charpoly():
A = DDM([], (0, 0), ZZ)
assert A.charpoly() == [ZZ(1)]
A = DDM([
[ZZ(1), ZZ(2), ZZ(3)],
[ZZ(4), ZZ(5), ZZ(6)],
[ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
assert A.charpoly() == Avec
A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
raises(DDMShapeError, lambda: A.charpoly())
def test_ddm_iadd():
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
ddm_iadd(a, b)
assert a == [[6, 8], [10, 12]]
def test_ddm_isub():
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
ddm_isub(a, b)
assert a == [[-4, -4], [-4, -4]]
def test_ddm_ineg():
a = [[1, 2], [3, 4]]
ddm_ineg(a)
assert a == [[-1, -2], [-3, -4]]
def test_ddm_matmul():
a = [[1, 2], [3, 4]]
ddm_imul(a, 2)
assert a == [[2, 4], [6, 8]]
a = [[1, 2], [3, 4]]
ddm_imul(a, 0)
assert a == [[0, 0], [0, 0]]
def test_ddm_imatmul():
a = [[1, 2, 3], [4, 5, 6]]
b = [[1, 2], [3, 4], [5, 6]]
c1 = [[0, 0], [0, 0]]
ddm_imatmul(c1, a, b)
assert c1 == [[22, 28], [49, 64]]
c2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
ddm_imatmul(c2, b, a)
assert c2 == [[9, 12, 15], [19, 26, 33], [29, 40, 51]]
b3 = [[1], [2], [3]]
c3 = [[0], [0]]
ddm_imatmul(c3, a, b3)
assert c3 == [[14], [32]]
def test_ddm_irref():
# Empty matrix
A = []
Ar = []
pivots = []
assert ddm_irref(A) == pivots
assert A == Ar
# Standard square case
A = [[QQ(0), QQ(1)], [QQ(1), QQ(1)]]
Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
pivots = [0, 1]
assert ddm_irref(A) == pivots
assert A == Ar
# m < n case
A = [[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]]
Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
pivots = [0, 1]
assert ddm_irref(A) == pivots
assert A == Ar
# same m < n but reversed
A = [[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]]
Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
pivots = [0, 1]
assert ddm_irref(A) == pivots
assert A == Ar
# m > n case
A = [[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]]
Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
pivots = [0, 1]
assert ddm_irref(A) == pivots
assert A == Ar
# Example with missing pivot
A = [[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]]
Ar = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
pivots = [0, 2]
assert ddm_irref(A) == pivots
assert A == Ar
# Example with missing pivot and no replacement
A = [[QQ(0), QQ(1)], [QQ(0), QQ(2)], [QQ(1), QQ(0)]]
Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
pivots = [0, 1]
assert ddm_irref(A) == pivots
assert A == Ar
def test_ddm_idet():
A = []
assert ddm_idet(A, ZZ) == ZZ(1)
A = [[ZZ(2)]]
assert ddm_idet(A, ZZ) == ZZ(2)
A = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
assert ddm_idet(A, ZZ) == ZZ(-2)
A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]]
assert ddm_idet(A, ZZ) == ZZ(-1)
A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]]
assert ddm_idet(A, ZZ) == ZZ(0)
A = [[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]]
assert ddm_idet(A, QQ) == QQ(-1, 24)
def test_ddm_inv():
A = []
Ainv = []
ddm_iinv(Ainv, A, QQ)
assert Ainv == A
A = []
Ainv = []
raises(ValueError, lambda: ddm_iinv(Ainv, A, ZZ))
A = [[QQ(1), QQ(2)]]
Ainv = [[QQ(0), QQ(0)]]
raises(NonSquareMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
A = [[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]]
Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
Ainv_expected = [[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]]
ddm_iinv(Ainv, A, QQ)
assert Ainv == Ainv_expected
A = [[QQ(1, 1), QQ(2, 1)], [QQ(2, 1), QQ(4, 1)]]
Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
raises(NonInvertibleMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
def test_ddm_ilu():
A = []
Alu = []
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
A = [[]]
Alu = [[]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
Alu = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == [(0, 1)]
A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)], [QQ(7), QQ(8), QQ(9)]]
Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)], [QQ(7), QQ(2), QQ(0)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
A = [[QQ(0), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(1), QQ(1), QQ(2)]]
Alu = [[QQ(1), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(0), QQ(1), QQ(-1)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == [(0, 2)]
A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)], [QQ(5), QQ(2)]]
swaps = ddm_ilu(A)
assert A == Alu
assert swaps == []
def test_ddm_ilu_split():
U = []
L = []
Uexp = []
Lexp = []
swaps = ddm_ilu_split(L, U, QQ)
assert U == Uexp
assert L == Lexp
assert swaps == []
U = [[]]
L = [[QQ(1)]]
Uexp = [[]]
Lexp = [[QQ(1)]]
swaps = ddm_ilu_split(L, U, QQ)
assert U == Uexp
assert L == Lexp
assert swaps == []
U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
Lexp = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
swaps = ddm_ilu_split(L, U, QQ)
assert U == Uexp
assert L == Lexp
assert swaps == []
U = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
Uexp = [[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]]
Lexp = [[QQ(1), QQ(0)], [QQ(4), QQ(1)]]
swaps = ddm_ilu_split(L, U, QQ)
assert U == Uexp
assert L == Lexp
assert swaps == []
U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
L = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(1), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
Lexp = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
swaps = ddm_ilu_split(L, U, QQ)
assert U == Uexp
assert L == Lexp
assert swaps == []
def test_ddm_ilu_solve():
# Basic example
# A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
L = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
swaps = []
b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
ddm_ilu_solve(x, L, U, swaps, b)
assert x == xexp
# Example with swaps
# A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
U = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
swaps = [(0, 1)]
b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
ddm_ilu_solve(x, L, U, swaps, b)
assert x == xexp
# Overdetermined, consistent
# A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
L = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
swaps = []
b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
ddm_ilu_solve(x, L, U, swaps, b)
assert x == xexp
# Overdetermined, inconsistent
b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
raises(NonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
# Square, noninvertible
# A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
U = [[QQ(1), QQ(2)], [QQ(0), QQ(0)]]
L = [[QQ(1), QQ(0)], [QQ(1), QQ(1)]]
swaps = []
b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
raises(NonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
# Underdetermined
# A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
U = [[QQ(1), QQ(2)]]
L = [[QQ(1)]]
swaps = []
b = DDM([[QQ(3)]], (1, 1), QQ)
raises(NotImplementedError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
# Shape mismatch
b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
raises(DDMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b3))
# Empty shape mismatch
U = [[QQ(1)]]
L = [[QQ(1)]]
swaps = []
x = [[QQ(1)]]
b = []
raises(DDMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
# Empty system
U = []
L = []
swaps = []
b = []
x = []
ddm_ilu_solve(x, L, U, swaps, b)
assert x == []
def test_ddm_charpoly():
A = []
assert ddm_berk(A, ZZ) == [[ZZ(1)]]
A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]]
Avec = [[ZZ(1)], [ZZ(-15)], [ZZ(-18)], [ZZ(0)]]
assert ddm_berk(A, ZZ) == Avec
A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
raises(DDMShapeError, lambda: ddm_berk(A, ZZ))
def test_DomainMatrix_init():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.rep == DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.shape == (2, 2)
assert A.domain == ZZ
raises(DDMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ))
def test_DomainMatrix_from_ddm():
ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A = DomainMatrix.from_ddm(ddm)
assert A.rep == ddm
assert A.shape == (2, 2)
assert A.domain == ZZ
def test_DomainMatrix_from_list_sympy():
ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]])
assert A.rep == ddm
assert A.shape == (2, 2)
assert A.domain == ZZ
K = QQ.algebraic_field(sqrt(2))
ddm = DDM(
[[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))],
[K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]],
(2, 2),
K
)
A = DomainMatrix.from_list_sympy(
2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]],
extension=True)
assert A.rep == ddm
assert A.shape == (2, 2)
assert A.domain == K
def test_DomainMatrix_from_Matrix():
ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
assert A.rep == ddm
assert A.shape == (2, 2)
assert A.domain == ZZ
K = QQ.algebraic_field(sqrt(2))
ddm = DDM(
[[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))],
[K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]],
(2, 2),
K
)
A = DomainMatrix.from_Matrix(
Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]),
extension=True)
assert A.rep == ddm
assert A.shape == (2, 2)
assert A.domain == K
def test_DomainMatrix_eq():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A == A
B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ)
assert A != B
C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
assert A != C
def test_DomainMatrix_get_domain():
K, items = DomainMatrix.get_domain([1, 2, 3, 4])
assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
assert K == ZZ
K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)])
assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)]
assert K == QQ
def test_DomainMatrix_convert_to():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = A.convert_to(QQ)
assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
def test_DomainMatrix_to_field():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = A.to_field()
assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
def test_DomainMatrix_unify():
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
assert Az.unify(Az) == (Az, Az)
assert Az.unify(Aq) == (Aq, Aq)
assert Aq.unify(Az) == (Aq, Aq)
assert Aq.unify(Aq) == (Aq, Aq)
def test_DomainMatrix_to_Matrix():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.to_Matrix() == Matrix([[1, 2], [3, 4]])
def test_DomainMatrix_repr():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)'
def test_DomainMatrix_add():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
assert A + A == A.add(A) == B
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
L = [[2, 3], [3, 4]]
raises(TypeError, lambda: A + L)
raises(TypeError, lambda: L + A)
A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
raises(ShapeError, lambda: A1 + A2)
raises(ShapeError, lambda: A2 + A1)
raises(ShapeError, lambda: A1.add(A2))
raises(ShapeError, lambda: A2.add(A1))
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
raises(ValueError, lambda: Az + Aq)
raises(ValueError, lambda: Aq + Az)
raises(ValueError, lambda: Az.add(Aq))
raises(ValueError, lambda: Aq.add(Az))
def test_DomainMatrix_sub():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
assert A - A == A.sub(A) == B
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
L = [[2, 3], [3, 4]]
raises(TypeError, lambda: A - L)
raises(TypeError, lambda: L - A)
A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
raises(ShapeError, lambda: A1 - A2)
raises(ShapeError, lambda: A2 - A1)
raises(ShapeError, lambda: A1.sub(A2))
raises(ShapeError, lambda: A2.sub(A1))
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
raises(ValueError, lambda: Az - Aq)
raises(ValueError, lambda: Aq - Az)
raises(ValueError, lambda: Az.sub(Aq))
raises(ValueError, lambda: Aq.sub(Az))
def test_DomainMatrix_neg():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ)
assert -A == A.neg() == Aneg
def test_DomainMatrix_mul():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
assert A*A == A.matmul(A) == A2
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
L = [[1, 2], [3, 4]]
raises(TypeError, lambda: A * L)
raises(TypeError, lambda: L * A)
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
raises(DDMDomainError, lambda: Az * Aq)
raises(DDMDomainError, lambda: Aq * Az)
raises(DDMDomainError, lambda: Az.matmul(Aq))
raises(DDMDomainError, lambda: Aq.matmul(Az))
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
x = ZZ(2)
assert A * x == x * A == A.mul(x) == AA
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
AA = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
x = ZZ(0)
assert A * x == x * A == A.mul(x) == AA
def test_DomainMatrix_pow():
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ)
eye = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)
assert A**0 == A.pow(0) == eye
assert A**1 == A.pow(1) == A
assert A**2 == A.pow(2) == A2
assert A**3 == A.pow(3) == A3
raises(TypeError, lambda: A ** Rational(1, 2))
raises(NotImplementedError, lambda: A ** -1)
raises(NotImplementedError, lambda: A.pow(-1))
def test_DomainMatrix_rref():
A = DomainMatrix([], (0, 1), QQ)
assert A.rref() == (A, ())
A = DomainMatrix([[QQ(1)]], (1, 1), QQ)
assert A.rref() == (A, (0,))
A = DomainMatrix([[QQ(0)]], (1, 1), QQ)
assert A.rref() == (A, ())
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
Ar, pivots = A.rref()
assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
assert pivots == (0, 1)
A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
Ar, pivots = A.rref()
assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
assert pivots == (0, 1)
A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
Ar, pivots = A.rref()
assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ)
assert pivots == (1,)
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
raises(ValueError, lambda: Az.rref())
def test_DomainMatrix_inv():
A = DomainMatrix([], (0, 0), QQ)
assert A.inv() == A
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
assert A.inv() == Ainv
Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
raises(ValueError, lambda: Az.inv())
Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
raises(NonSquareMatrixError, lambda: Ans.inv())
Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ)
raises(NonInvertibleMatrixError, lambda: Aninv.inv())
def test_DomainMatrix_det():
A = DomainMatrix([], (0, 0), ZZ)
assert A.det() == 1
A = DomainMatrix([[1]], (1, 1), ZZ)
assert A.det() == 1
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.det() == ZZ(-2)
A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ)
assert A.det() == ZZ(-1)
A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
assert A.det() == ZZ(0)
Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
raises(NonSquareMatrixError, lambda: Ans.det())
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
assert A.det() == QQ(-2)
def test_DomainMatrix_lu():
A = DomainMatrix([], (0, 0), QQ)
assert A.lu() == (A, A, [])
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
swaps = []
assert A.lu() == (L, U, swaps)
A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ)
swaps = [(0, 1)]
assert A.lu() == (L, U, swaps)
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ)
U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ)
swaps = []
assert A.lu() == (L, U, swaps)
A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
swaps = []
assert A.lu() == (L, U, swaps)
A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ)
U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ)
swaps = []
assert A.lu() == (L, U, swaps)
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
L = DomainMatrix([
[QQ(1), QQ(0), QQ(0)],
[QQ(3), QQ(1), QQ(0)],
[QQ(5), QQ(2), QQ(1)]], (3, 3), QQ)
U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ)
swaps = []
assert A.lu() == (L, U, swaps)
A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ)
L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ)
U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ)
assert A.lu() == (L, U, [])
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
raises(ValueError, lambda: A.lu())
def test_DomainMatrix_lu_solve():
# Base case
A = b = x = DomainMatrix([], (0, 0), QQ)
assert A.lu_solve(b) == x
# Basic example
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
assert A.lu_solve(b) == x
# Example with swaps
A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
assert A.lu_solve(b) == x
# Non-invertible
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
raises(NonInvertibleMatrixError, lambda: A.lu_solve(b))
# Overdetermined, consistent
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
assert A.lu_solve(b) == x
# Overdetermined, inconsistent
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
raises(NonInvertibleMatrixError, lambda: A.lu_solve(b))
# Underdetermined
A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
b = DomainMatrix([[QQ(1)]], (1, 1), QQ)
raises(NotImplementedError, lambda: A.lu_solve(b))
# Non-field
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
raises(ValueError, lambda: A.lu_solve(b))
# Shape mismatch
A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
raises(ShapeError, lambda: A.lu_solve(b))
def test_DomainMatrix_charpoly():
A = DomainMatrix([], (0, 0), ZZ)
assert A.charpoly() == [ZZ(1)]
A = DomainMatrix([[1]], (1, 1), ZZ)
assert A.charpoly() == [ZZ(1), ZZ(-1)]
A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)]
A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
assert A.charpoly() == [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
raises(NonSquareMatrixError, lambda: Ans.charpoly())
def test_DomainMatrix_eye():
A = DomainMatrix.eye(3, QQ)
assert A.rep == DDM.eye(3, QQ)
assert A.shape == (3, 3)
assert A.domain == QQ
|
b088423c6d10fff6c8f44400662caa8dcdc709996dc4ca66d32f2f20ee71f3db | """Computations with ideals of polynomial rings."""
from functools import reduce
from sympy.polys.polyerrors import CoercionFailed
class Ideal:
"""
Abstract base class for ideals.
Do not instantiate - use explicit constructors in the ring class instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> QQ.old_poly_ring(x).ideal(x+1)
<x + 1>
Attributes
- ring - the ring this ideal belongs to
Non-implemented methods:
- _contains_elem
- _contains_ideal
- _quotient
- _intersect
- _union
- _product
- is_whole_ring
- is_zero
- is_prime, is_maximal, is_primary, is_radical
- is_principal
- height, depth
- radical
Methods that likely should be overridden in subclasses:
- reduce_element
"""
def _contains_elem(self, x):
"""Implementation of element containment."""
raise NotImplementedError
def _contains_ideal(self, I):
"""Implementation of ideal containment."""
raise NotImplementedError
def _quotient(self, J):
"""Implementation of ideal quotient."""
raise NotImplementedError
def _intersect(self, J):
"""Implementation of ideal intersection."""
raise NotImplementedError
def is_whole_ring(self):
"""Return True if ``self`` is the whole ring."""
raise NotImplementedError
def is_zero(self):
"""Return True if ``self`` is the zero ideal."""
raise NotImplementedError
def _equals(self, J):
"""Implementation of ideal equality."""
return self._contains_ideal(J) and J._contains_ideal(self)
def is_prime(self):
"""Return True if ``self`` is a prime ideal."""
raise NotImplementedError
def is_maximal(self):
"""Return True if ``self`` is a maximal ideal."""
raise NotImplementedError
def is_radical(self):
"""Return True if ``self`` is a radical ideal."""
raise NotImplementedError
def is_primary(self):
"""Return True if ``self`` is a primary ideal."""
raise NotImplementedError
def is_principal(self):
"""Return True if ``self`` is a principal ideal."""
raise NotImplementedError
def radical(self):
"""Compute the radical of ``self``."""
raise NotImplementedError
def depth(self):
"""Compute the depth of ``self``."""
raise NotImplementedError
def height(self):
"""Compute the height of ``self``."""
raise NotImplementedError
# TODO more
# non-implemented methods end here
def __init__(self, ring):
self.ring = ring
def _check_ideal(self, J):
"""Helper to check ``J`` is an ideal of our ring."""
if not isinstance(J, Ideal) or J.ring != self.ring:
raise ValueError(
'J must be an ideal of %s, got %s' % (self.ring, J))
def contains(self, elem):
"""
Return True if ``elem`` is an element of this ideal.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x+1, x-1).contains(3)
True
>>> QQ.old_poly_ring(x).ideal(x**2, x**3).contains(x)
False
"""
return self._contains_elem(self.ring.convert(elem))
def subset(self, other):
"""
Returns True if ``other`` is is a subset of ``self``.
Here ``other`` may be an ideal.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x+1)
>>> I.subset([x**2 - 1, x**2 + 2*x + 1])
True
>>> I.subset([x**2 + 1, x + 1])
False
>>> I.subset(QQ.old_poly_ring(x).ideal(x**2 - 1))
True
"""
if isinstance(other, Ideal):
return self._contains_ideal(other)
return all(self._contains_elem(x) for x in other)
def quotient(self, J, **opts):
r"""
Compute the ideal quotient of ``self`` by ``J``.
That is, if ``self`` is the ideal `I`, compute the set
`I : J = \{x \in R | xJ \subset I \}`.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> R = QQ.old_poly_ring(x, y)
>>> R.ideal(x*y).quotient(R.ideal(x))
<y>
"""
self._check_ideal(J)
return self._quotient(J, **opts)
def intersect(self, J):
"""
Compute the intersection of self with ideal J.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> R = QQ.old_poly_ring(x, y)
>>> R.ideal(x).intersect(R.ideal(y))
<x*y>
"""
self._check_ideal(J)
return self._intersect(J)
def saturate(self, J):
r"""
Compute the ideal saturation of ``self`` by ``J``.
That is, if ``self`` is the ideal `I`, compute the set
`I : J^\infty = \{x \in R | xJ^n \subset I \text{ for some } n\}`.
"""
raise NotImplementedError
# Note this can be implemented using repeated quotient
def union(self, J):
"""
Compute the ideal generated by the union of ``self`` and ``J``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x**2 - 1).union(QQ.old_poly_ring(x).ideal((x+1)**2)) == QQ.old_poly_ring(x).ideal(x+1)
True
"""
self._check_ideal(J)
return self._union(J)
def product(self, J):
r"""
Compute the ideal product of ``self`` and ``J``.
That is, compute the ideal generated by products `xy`, for `x` an element
of ``self`` and `y \in J`.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> QQ.old_poly_ring(x, y).ideal(x).product(QQ.old_poly_ring(x, y).ideal(y))
<x*y>
"""
self._check_ideal(J)
return self._product(J)
def reduce_element(self, x):
"""
Reduce the element ``x`` of our ring modulo the ideal ``self``.
Here "reduce" has no specific meaning: it could return a unique normal
form, simplify the expression a bit, or just do nothing.
"""
return x
def __add__(self, e):
if not isinstance(e, Ideal):
R = self.ring.quotient_ring(self)
if isinstance(e, R.dtype):
return e
if isinstance(e, R.ring.dtype):
return R(e)
return R.convert(e)
self._check_ideal(e)
return self.union(e)
__radd__ = __add__
def __mul__(self, e):
if not isinstance(e, Ideal):
try:
e = self.ring.ideal(e)
except CoercionFailed:
return NotImplemented
self._check_ideal(e)
return self.product(e)
__rmul__ = __mul__
def __pow__(self, exp):
if exp < 0:
raise NotImplementedError
# TODO exponentiate by squaring
return reduce(lambda x, y: x*y, [self]*exp, self.ring.ideal(1))
def __eq__(self, e):
if not isinstance(e, Ideal) or e.ring != self.ring:
return False
return self._equals(e)
def __ne__(self, e):
return not (self == e)
class ModuleImplementedIdeal(Ideal):
"""
Ideal implementation relying on the modules code.
Attributes:
- _module - the underlying module
"""
def __init__(self, ring, module):
Ideal.__init__(self, ring)
self._module = module
def _contains_elem(self, x):
return self._module.contains([x])
def _contains_ideal(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self._module.is_submodule(J._module)
def _intersect(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.intersect(J._module))
def _quotient(self, J, **opts):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self._module.module_quotient(J._module, **opts)
def _union(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.union(J._module))
@property
def gens(self):
"""
Return generators for ``self``.
Examples
========
>>> from sympy import QQ
>>> from sympy.abc import x, y
>>> list(QQ.old_poly_ring(x, y).ideal(x, y, x**2 + y).gens)
[x, y, x**2 + y]
"""
return (x[0] for x in self._module.gens)
def is_zero(self):
"""
Return True if ``self`` is the zero ideal.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x).is_zero()
False
>>> QQ.old_poly_ring(x).ideal().is_zero()
True
"""
return self._module.is_zero()
def is_whole_ring(self):
"""
Return True if ``self`` is the whole ring, i.e. one generator is a unit.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ, ilex
>>> QQ.old_poly_ring(x).ideal(x).is_whole_ring()
False
>>> QQ.old_poly_ring(x).ideal(3).is_whole_ring()
True
>>> QQ.old_poly_ring(x, order=ilex).ideal(2 + x).is_whole_ring()
True
"""
return self._module.is_full_module()
def __repr__(self):
from sympy import sstr
return '<' + ','.join(sstr(x) for [x] in self._module.gens) + '>'
# NOTE this is the only method using the fact that the module is a SubModule
def _product(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.submodule(
*[[x*y] for [x] in self._module.gens for [y] in J._module.gens]))
def in_terms_of_generators(self, e):
"""
Express ``e`` in terms of the generators of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**2 + 1, x)
>>> I.in_terms_of_generators(1)
[1, -x]
"""
return self._module.in_terms_of_generators([e])
def reduce_element(self, x, **options):
return self._module.reduce_element([x], **options)[0]
|
acbea65b10e3d3577751f7b8df3929cd80e7703cf6327eb84f5040a2463b13c1 | """
Computations with modules over polynomial rings.
This module implements various classes that encapsulate groebner basis
computations for modules. Most of them should not be instantiated by hand.
Instead, use the constructing routines on objects you already have.
For example, to construct a free module over ``QQ[x, y]``, call
``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor.
In fact ``FreeModule`` is an abstract base class that should not be
instantiated, the ``free_module`` method instead returns the implementing class
``FreeModulePolyRing``.
In general, the abstract base classes implement most functionality in terms of
a few non-implemented methods. The concrete base classes supply only these
non-implemented methods. They may also supply new implementations of the
convenience methods, for example if there are faster algorithms available.
"""
from copy import copy
from functools import reduce
from sympy.core.compatibility import iterable
from sympy.polys.agca.ideals import Ideal
from sympy.polys.domains.field import Field
from sympy.polys.orderings import ProductOrder, monomial_key
from sympy.polys.polyerrors import CoercionFailed
from sympy.core.basic import _aresame
# TODO
# - module saturation
# - module quotient/intersection for quotient rings
# - free resoltutions / syzygies
# - finding small/minimal generating sets
# - ...
##########################################################################
## Abstract base classes #################################################
##########################################################################
class Module:
"""
Abstract base class for modules.
Do not instantiate - use ring explicit constructors instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
Attributes:
- dtype - type of elements
- ring - containing ring
Non-implemented methods:
- submodule
- quotient_module
- is_zero
- is_submodule
- multiply_ideal
The method convert likely needs to be changed in subclasses.
"""
def __init__(self, ring):
self.ring = ring
def convert(self, elem, M=None):
"""
Convert ``elem`` into internal representation of this module.
If ``M`` is not None, it should be a module containing it.
"""
if not isinstance(elem, self.dtype):
raise CoercionFailed
return elem
def submodule(self, *gens):
"""Generate a submodule."""
raise NotImplementedError
def quotient_module(self, other):
"""Generate a quotient module."""
raise NotImplementedError
def __truediv__(self, e):
if not isinstance(e, Module):
e = self.submodule(*e)
return self.quotient_module(e)
def contains(self, elem):
"""Return True if ``elem`` is an element of this module."""
try:
self.convert(elem)
return True
except CoercionFailed:
return False
def __contains__(self, elem):
return self.contains(elem)
def subset(self, other):
"""
Returns True if ``other`` is is a subset of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.subset([(1, x), (x, 2)])
True
>>> F.subset([(1/x, x), (x, 2)])
False
"""
return all(self.contains(x) for x in other)
def __eq__(self, other):
return self.is_submodule(other) and other.is_submodule(self)
def __ne__(self, other):
return not (self == other)
def is_zero(self):
"""Returns True if ``self`` is a zero module."""
raise NotImplementedError
def is_submodule(self, other):
"""Returns True if ``other`` is a submodule of ``self``."""
raise NotImplementedError
def multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
"""
raise NotImplementedError
def __mul__(self, e):
if not isinstance(e, Ideal):
try:
e = self.ring.ideal(e)
except (CoercionFailed, NotImplementedError):
return NotImplemented
return self.multiply_ideal(e)
__rmul__ = __mul__
def identity_hom(self):
"""Return the identity homomorphism on ``self``."""
raise NotImplementedError
class ModuleElement:
"""
Base class for module element wrappers.
Use this class to wrap primitive data types as module elements. It stores
a reference to the containing module, and implements all the arithmetic
operators.
Attributes:
- module - containing module
- data - internal data
Methods that likely need change in subclasses:
- add
- mul
- div
- eq
"""
def __init__(self, module, data):
self.module = module
self.data = data
def add(self, d1, d2):
"""Add data ``d1`` and ``d2``."""
return d1 + d2
def mul(self, m, d):
"""Multiply module data ``m`` by coefficient d."""
return m * d
def div(self, m, d):
"""Divide module data ``m`` by coefficient d."""
return m / d
def eq(self, d1, d2):
"""Return true if d1 and d2 represent the same element."""
return d1 == d2
def __add__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.add(self.data, om.data))
__radd__ = __add__
def __neg__(self):
return self.__class__(self.module, self.mul(self.data,
self.module.ring.convert(-1)))
def __sub__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__add__(-om)
def __rsub__(self, om):
return (-self).__add__(om)
def __mul__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.mul(self.data, o))
__rmul__ = __mul__
def __truediv__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.div(self.data, o))
def __eq__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return False
return self.eq(self.data, om.data)
def __ne__(self, om):
return not self == om
##########################################################################
## Free Modules ##########################################################
##########################################################################
class FreeModuleElement(ModuleElement):
"""Element of a free module. Data stored as a tuple."""
def add(self, d1, d2):
return tuple(x + y for x, y in zip(d1, d2))
def mul(self, d, p):
return tuple(x * p for x in d)
def div(self, d, p):
return tuple(x / p for x in d)
def __repr__(self):
from sympy import sstr
return '[' + ', '.join(sstr(x) for x in self.data) + ']'
def __iter__(self):
return self.data.__iter__()
def __getitem__(self, idx):
return self.data[idx]
class FreeModule(Module):
"""
Abstract base class for free modules.
Additional attributes:
- rank - rank of the free module
Non-implemented methods:
- submodule
"""
dtype = FreeModuleElement
def __init__(self, ring, rank):
Module.__init__(self, ring)
self.rank = rank
def __repr__(self):
return repr(self.ring) + "**" + repr(self.rank)
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> F.is_submodule(F)
True
>>> F.is_submodule(M)
True
>>> M.is_submodule(F)
False
"""
if isinstance(other, SubModule):
return other.container == self
if isinstance(other, FreeModule):
return other.ring == self.ring and other.rank == self.rank
return False
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.convert([1, 0])
[1, 0]
"""
if isinstance(elem, FreeModuleElement):
if elem.module is self:
return elem
if elem.module.rank != self.rank:
raise CoercionFailed
return FreeModuleElement(self,
tuple(self.ring.convert(x, elem.module.ring) for x in elem.data))
elif iterable(elem):
tpl = tuple(self.ring.convert(x) for x in elem)
if len(tpl) != self.rank:
raise CoercionFailed
return FreeModuleElement(self, tpl)
elif _aresame(elem, 0):
return FreeModuleElement(self, (self.ring.convert(0),)*self.rank)
else:
raise CoercionFailed
def is_zero(self):
"""
Returns True if ``self`` is a zero module.
(If, as this implementation assumes, the coefficient ring is not the
zero ring, then this is equivalent to the rank being zero.)
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(0).is_zero()
True
>>> QQ.old_poly_ring(x).free_module(1).is_zero()
False
"""
return self.rank == 0
def basis(self):
"""
Return a set of basis elements.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(3).basis()
([1, 0, 0], [0, 1, 0], [0, 0, 1])
"""
from sympy.matrices import eye
M = eye(self.rank)
return tuple(self.convert(M.row(i)) for i in range(self.rank))
def quotient_module(self, submodule):
"""
Return a quotient module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2)
>>> M.quotient_module(M.submodule([1, x], [x, 2]))
QQ[x]**2/<[1, x], [x, 2]>
Or more conicisely, using the overloaded division operator:
>>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]]
QQ[x]**2/<[1, x], [x, 2]>
"""
return QuotientModule(self.ring, self, submodule)
def multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x)
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.multiply_ideal(I)
<[x, 0], [0, x]>
"""
return self.submodule(*self.basis()).multiply_ideal(other)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).identity_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2
[0, 1]])
"""
from sympy.polys.agca.homomorphisms import homomorphism
return homomorphism(self, self, self.basis())
class FreeModulePolyRing(FreeModule):
"""
Free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of the ring instead:
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(3)
>>> F
QQ[x]**3
>>> F.contains([x, 1, 0])
True
>>> F.contains([1/x, 0, 1])
False
"""
def __init__(self, ring, rank):
from sympy.polys.domains.old_polynomialring import PolynomialRingBase
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, PolynomialRingBase):
raise NotImplementedError('This implementation only works over '
+ 'polynomial rings, got %s' % ring)
if not isinstance(ring.dom, Field):
raise NotImplementedError('Ground domain must be a field, '
+ 'got %s' % ring.dom)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y])
>>> M
<[x, x + y]>
>>> M.contains([2*x, 2*x + 2*y])
True
>>> M.contains([x, y])
False
"""
return SubModulePolyRing(gens, self, **opts)
class FreeModuleQuotientRing(FreeModule):
"""
Free module over a quotient ring.
Do not instantiate this, use the constructor method of the ring instead:
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3)
>>> F
(QQ[x]/<x**2 + 1>)**3
Attributes
- quot - the quotient module `R^n / IR^n`, where `R/I` is our ring
"""
def __init__(self, ring, rank):
from sympy.polys.domains.quotientring import QuotientRing
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, QuotientRing):
raise NotImplementedError('This implementation only works over '
+ 'quotient rings, got %s' % ring)
F = self.ring.ring.free_module(self.rank)
self.quot = F / (self.ring.base_ideal*F)
def __repr__(self):
return "(" + repr(self.ring) + ")" + "**" + repr(self.rank)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
"""
return SubModuleQuotientRing(gens, self, **opts)
def lift(self, elem):
"""
Lift the element ``elem`` of self to the module self.quot.
Note that self.quot is the same set as self, just as an R-module
and not as an R/I-module, so this makes sense.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> e
[1 + <x**2 + 1>, 0 + <x**2 + 1>]
>>> L = F.quot
>>> l = F.lift(e)
>>> l
[1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]>
>>> L.contains(l)
True
"""
return self.quot.convert([x.data for x in elem])
def unlift(self, elem):
"""
Push down an element of self.quot to self.
This undoes ``lift``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> l = F.lift(e)
>>> e == l
False
>>> e == F.unlift(l)
True
"""
return self.convert(elem.data)
##########################################################################
## Submodules and subquotients ###########################################
##########################################################################
class SubModule(Module):
"""
Base class for submodules.
Attributes:
- container - containing module
- gens - generators (subset of containing module)
- rank - rank of containing module
Non-implemented methods:
- _contains
- _syzygies
- _in_terms_of_generators
- _intersect
- _module_quotient
Methods that likely need change in subclasses:
- reduce_element
"""
def __init__(self, gens, container):
Module.__init__(self, container.ring)
self.gens = tuple(container.convert(x) for x in gens)
self.container = container
self.rank = container.rank
self.ring = container.ring
self.dtype = container.dtype
def __repr__(self):
return "<" + ", ".join(repr(x) for x in self.gens) + ">"
def _contains(self, other):
"""Implementation of containment.
Other is guaranteed to be FreeModuleElement."""
raise NotImplementedError
def _syzygies(self):
"""Implementation of syzygy computation wrt self generators."""
raise NotImplementedError
def _in_terms_of_generators(self, e):
"""Implementation of expression in terms of generators."""
raise NotImplementedError
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal represantition.
Mostly called implicitly.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x])
>>> M.convert([2, 2*x])
[2, 2*x]
"""
if isinstance(elem, self.container.dtype) and elem.module is self:
return elem
r = copy(self.container.convert(elem, M))
r.module = self
if not self._contains(r):
raise CoercionFailed
return r
def _intersect(self, other):
"""Implementation of intersection.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def _module_quotient(self, other):
"""Implementation of quotient.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def intersect(self, other, **options):
"""
Returns the intersection of ``self`` with submodule ``other``.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, x]).intersect(F.submodule([y, y]))
<[x*y, x*y]>
Some implementation allow further options to be passed. Currently, to
only one implemented is ``relations=True``, in which case the function
will return a triple ``(res, rela, relb)``, where ``res`` is the
intersection module, and ``rela`` and ``relb`` are lists of coefficient
vectors, expressing the generators of ``res`` in terms of the
generators of ``self`` (``rela``) and ``other`` (``relb``).
>>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True)
(<[x*y, x*y]>, [(y,)], [(x,)])
The above result says: the intersection module is generated by the
single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where
`(x, x)` and `(y, y)` respectively are the unique generators of
the two modules being intersected.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._intersect(other, **options)
def module_quotient(self, other, **options):
r"""
Returns the module quotient of ``self`` by submodule ``other``.
That is, if ``self`` is the module `M` and ``other`` is `N`, then
return the ideal `\{f \in R | fN \subset M\}`.
Examples
========
>>> from sympy import QQ
>>> from sympy.abc import x, y
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> S = F.submodule([x*y, x*y])
>>> T = F.submodule([x, x])
>>> S.module_quotient(T)
<y>
Some implementations allow further options to be passed. Currently, the
only one implemented is ``relations=True``, which may only be passed
if ``other`` is principal. In this case the function
will return a pair ``(res, rel)`` where ``res`` is the ideal, and
``rel`` is a list of coefficient vectors, expressing the generators of
the ideal, multiplied by the generator of ``other`` in terms of
generators of ``self``.
>>> S.module_quotient(T, relations=True)
(<y>, [[1]])
This means that the quotient ideal is generated by the single element
`y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being
the generators of `T` and `S`, respectively.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._module_quotient(other, **options)
def union(self, other):
"""
Returns the module generated by the union of ``self`` and ``other``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(1)
>>> M = F.submodule([x**2 + x]) # <x(x+1)>
>>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)>
>>> M.union(N) == F.submodule([x+1])
True
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self.__class__(self.gens + other.gens, self.container)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_zero()
False
>>> F.submodule([0, 0]).is_zero()
True
"""
return all(x == 0 for x in self.gens)
def submodule(self, *gens):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1])
>>> M.submodule([x**2, x])
<[x**2, x]>
"""
if not self.subset(gens):
raise ValueError('%s not a subset of %s' % (gens, self))
return self.__class__(gens, self.container)
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return all(self.contains(x) for x in self.container.basis())
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> N = M.submodule([2*x, x**2])
>>> M.is_submodule(M)
True
>>> M.is_submodule(N)
True
>>> N.is_submodule(M)
False
"""
if isinstance(other, SubModule):
return self.container == other.container and \
all(self.contains(x) for x in other.gens)
if isinstance(other, (FreeModule, QuotientModule)):
return self.container == other and self.is_full_module()
return False
def syzygy_module(self, **opts):
r"""
Compute the syzygy module of the generators of ``self``.
Suppose `M` is generated by `f_1, \ldots, f_n` over the ring
`R`. Consider the homomorphism `\phi: R^n \to M`, given by
sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`.
The syzygy module is defined to be the kernel of `\phi`.
Examples
========
The syzygy module is zero iff the generators generate freely a free
submodule:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero()
True
A slightly more interesting example:
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y])
>>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x])
>>> M.syzygy_module() == S
True
"""
F = self.ring.free_module(len(self.gens))
# NOTE we filter out zero syzygies. This is for convenience of the
# _syzygies function and not meant to replace any real "generating set
# reduction" algorithm
return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0],
**opts)
def in_terms_of_generators(self, e):
"""
Express element ``e`` of ``self`` in terms of the generators.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([1, 0], [1, 1])
>>> M.in_terms_of_generators([x, x**2])
[-x**2 + x, x**2]
"""
try:
e = self.convert(e)
except CoercionFailed:
raise ValueError('%s is not an element of %s' % (e, self))
return self._in_terms_of_generators(e)
def reduce_element(self, x):
"""
Reduce the element ``x`` of our ring modulo the ideal ``self``.
Here "reduce" has no specific meaning, it could return a unique normal
form, simplify the expression a bit, or just do nothing.
"""
return x
def quotient_module(self, other, **opts):
"""
Return a quotient module.
This is the same as taking a submodule of a quotient of the containing
module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S1 = F.submodule([x, 1])
>>> S2 = F.submodule([x**2, x])
>>> S1.quotient_module(S2)
<[x, 1] + <[x**2, x]>>
Or more coincisely, using the overloaded division operator:
>>> F.submodule([x, 1]) / [(x**2, x)]
<[x, 1] + <[x**2, x]>>
"""
if not self.is_submodule(other):
raise ValueError('%s not a submodule of %s' % (other, self))
return SubQuotientModule(self.gens,
self.container.quotient_module(other), **opts)
def __add__(self, oth):
return self.container.quotient_module(self).convert(oth)
__radd__ = __add__
def multiply_ideal(self, I):
"""
Multiply ``self`` by the ideal ``I``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**2)
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1])
>>> I*M
<[x**2, x**2]>
"""
return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens])
def inclusion_hom(self):
"""
Return a homomorphism representing the inclusion map of ``self``.
That is, the natural map from ``self`` to ``self.container``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom()
Matrix([
[1, 0], : <[x, x]> -> QQ[x]**2
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(self)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom()
Matrix([
[1, 0], : <[x, x]> -> <[x, x]>
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(
self).restrict_codomain(self)
class SubQuotientModule(SubModule):
"""
Submodule of a quotient module.
Equivalently, quotient module of a submodule.
Do not instantiate this, instead use the submodule or quotient_module
constructing methods:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S = F.submodule([1, 0], [1, x])
>>> Q = F/[(1, 0)]
>>> S/[(1, 0)] == Q.submodule([5, x])
True
Attributes:
- base - base module we are quotient of
- killed_module - submodule used to form the quotient
"""
def __init__(self, gens, container, **opts):
SubModule.__init__(self, gens, container)
self.killed_module = self.container.killed_module
# XXX it is important for some code below that the generators of base
# are in this particular order!
self.base = self.container.base.submodule(
*[x.data for x in self.gens], **opts).union(self.killed_module)
def _contains(self, elem):
return self.base.contains(elem.data)
def _syzygies(self):
# let N = self.killed_module be generated by e_1, ..., e_r
# let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r
# Then self = F/N.
# Let phi: R**s --> self be the evident surjection.
# Similarly psi: R**(s + r) --> F.
# We need to find generators for ker(phi). Let chi: R**s --> F be the
# evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is
# contained in N, iff there exists Y in R**r such that
# psi(X, Y) = 0.
# Hence if alpha: R**(s + r) --> R**s is the projection map, then
# ker(phi) = alpha ker(psi).
return [X[:len(self.gens)] for X in self.base._syzygies()]
def _in_terms_of_generators(self, e):
return self.base._in_terms_of_generators(e.data)[:len(self.gens)]
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return self.base.is_full_module()
def quotient_hom(self):
"""
Return the quotient homomorphism to self.
That is, return the natural map from ``self.base`` to ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0])
>>> M.quotient_hom()
Matrix([
[1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(self.killed_module)
_subs0 = lambda x: x[0]
_subs1 = lambda x: x[1:]
class ModuleOrder(ProductOrder):
"""A product monomial order with a zeroth term as module index."""
def __init__(self, o1, o2, TOP):
if TOP:
ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0))
else:
ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1))
class SubModulePolyRing(SubModule):
"""
Submodule of a free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of FreeModule instead:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, y], [1, 0])
<[x, y], [1, 0]>
Attributes:
- order - monomial order used
"""
#self._gb - cached groebner basis
#self._gbe - cached groebner basis relations
def __init__(self, gens, container, order="lex", TOP=True):
SubModule.__init__(self, gens, container)
if not isinstance(container, FreeModulePolyRing):
raise NotImplementedError('This implementation is for submodules of '
+ 'FreeModulePolyRing, got %s' % container)
self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP)
self._gb = None
self._gbe = None
def __eq__(self, other):
if isinstance(other, SubModulePolyRing) and self.order != other.order:
return False
return SubModule.__eq__(self, other)
def _groebner(self, extended=False):
"""Returns a standard basis in sdm form."""
from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora
if self._gbe is None and extended:
gb, gbe = sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom, extended=True)
self._gb, self._gbe = tuple(gb), tuple(gbe)
if self._gb is None:
self._gb = tuple(sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom))
if extended:
return self._gb, self._gbe
else:
return self._gb
def _groebner_vec(self, extended=False):
"""Returns a standard basis in element form."""
if not extended:
return [self.convert(self.ring._sdm_to_vector(x, self.rank))
for x in self._groebner()]
gb, gbe = self._groebner(extended=True)
return ([self.convert(self.ring._sdm_to_vector(x, self.rank))
for x in gb],
[self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe])
def _contains(self, x):
from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora
return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order),
self._groebner(), self.order, self.ring.dom) == \
sdm_zero()
def _syzygies(self):
"""Compute syzygies. See [SCA, algorithm 2.5.4]."""
# NOTE if self.gens is a standard basis, this can be done more
# efficiently using Schreyer's theorem
from sympy.matrices import eye
# First bullet point
k = len(self.gens)
r = self.rank
im = eye(k)
Rkr = self.ring.free_module(r + k)
newgens = []
for j, f in enumerate(self.gens):
m = [0]*(r + k)
for i, v in enumerate(f):
m[i] = f[i]
for i in range(k):
m[r + i] = im[j, i]
newgens.append(Rkr.convert(m))
# Note: we need *descending* order on module index, and TOP=False to
# get an elimination order
F = Rkr.submodule(*newgens, order='ilex', TOP=False)
# Second bullet point: standard basis of F
G = F._groebner_vec()
# Third bullet point: G0 = G intersect the new k components
G0 = [x[r:] for x in G if all(y == self.ring.convert(0)
for y in x[:r])]
# Fourth and fifth bullet points: we are done
return G0
def _in_terms_of_generators(self, e):
"""Expression in terms of generators. See [SCA, 2.8.1]."""
# NOTE: if gens is a standard basis, this can be done more efficiently
M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens))
S = M.syzygy_module(
order="ilex", TOP=False) # We want decreasing order!
G = S._groebner_vec()
# This list cannot not be empty since e is an element
e = [x for x in G if self.ring.is_unit(x[0])][0]
return [-x/e[0] for x in e[1:]]
def reduce_element(self, x, NF=None):
"""
Reduce the element ``x`` of our container modulo ``self``.
This applies the normal form ``NF`` to ``x``. If ``NF`` is passed
as none, the default Mora normal form is used (which is not unique!).
"""
from sympy.polys.distributedmodules import sdm_nf_mora
if NF is None:
NF = sdm_nf_mora
return self.container.convert(self.ring._sdm_to_vector(NF(
self.ring._vector_to_sdm(x, self.order), self._groebner(),
self.order, self.ring.dom),
self.rank))
def _intersect(self, other, relations=False):
# See: [SCA, section 2.8.2]
fi = self.gens
hi = other.gens
r = self.rank
ci = [[0]*(2*r) for _ in range(r)]
for k in range(r):
ci[k][k] = 1
ci[k][r + k] = 1
di = [list(f) + [0]*r for f in fi]
ei = [[0]*r + list(h) for h in hi]
syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies()
nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])]
res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero))
reln1 = [x[r:r + len(fi)] for x in nonzero]
reln2 = [x[r + len(fi):] for x in nonzero]
if relations:
return res, reln1, reln2
return res
def _module_quotient(self, other, relations=False):
# See: [SCA, section 2.8.4]
if relations and len(other.gens) != 1:
raise NotImplementedError
if len(other.gens) == 0:
return self.ring.ideal(1)
elif len(other.gens) == 1:
# We do some trickery. Let f be the (vector!) generating ``other``
# and f1, .., fn be the (vectors) generating self.
# Consider the submodule of R^{r+1} generated by (f, 1) and
# {(fi, 0) | i}. Then the intersection with the last module
# component yields the quotient.
g1 = list(other.gens[0]) + [1]
gi = [list(x) + [0] for x in self.gens]
# NOTE: We *need* to use an elimination order
M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi),
order='ilex', TOP=False)
if not relations:
return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if
all(y == self.ring.zero for y in x[:-1])])
else:
G, R = M._groebner_vec(extended=True)
indices = [i for i, x in enumerate(G) if
all(y == self.ring.zero for y in x[:-1])]
return (self.ring.ideal(*[G[i][-1] for i in indices]),
[[-x for x in R[i][1:]] for i in indices])
# For more generators, we use I : <h1, .., hn> = intersection of
# {I : <hi> | i}
# TODO this can be done more efficiently
return reduce(lambda x, y: x.intersect(y),
(self._module_quotient(self.container.submodule(x)) for x in other.gens))
class SubModuleQuotientRing(SubModule):
"""
Class for submodules of free modules over quotient rings.
Do not instantiate this. Instead use the submodule methods.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
Attributes:
- quot - the subquotient of `R^n/IR^n` generated by lifts of our generators
"""
def __init__(self, gens, container):
SubModule.__init__(self, gens, container)
self.quot = self.container.quot.submodule(
*[self.container.lift(x) for x in self.gens])
def _contains(self, elem):
return self.quot._contains(self.container.lift(elem))
def _syzygies(self):
return [tuple(self.ring.convert(y, self.quot.ring) for y in x)
for x in self.quot._syzygies()]
def _in_terms_of_generators(self, elem):
return [self.ring.convert(x, self.quot.ring) for x in
self.quot._in_terms_of_generators(self.container.lift(elem))]
##########################################################################
## Quotient Modules ######################################################
##########################################################################
class QuotientModuleElement(ModuleElement):
"""Element of a quotient module."""
def eq(self, d1, d2):
"""Equality comparison."""
return self.module.killed_module.contains(d1 - d2)
def __repr__(self):
return repr(self.data) + " + " + repr(self.module.killed_module)
class QuotientModule(Module):
"""
Class for quotient modules.
Do not instantiate this directly. For subquotients, see the
SubQuotientModule class.
Attributes:
- base - the base module we are a quotient of
- killed_module - the submodule used to form the quotient
- rank of the base
"""
dtype = QuotientModuleElement
def __init__(self, ring, base, submodule):
Module.__init__(self, ring)
if not base.is_submodule(submodule):
raise ValueError('%s is not a submodule of %s' % (submodule, base))
self.base = base
self.killed_module = submodule
self.rank = base.rank
def __repr__(self):
return repr(self.base) + "/" + repr(self.killed_module)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
This happens if and only if the base module is the same as the
submodule being killed.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> (F/[(1, 0)]).is_zero()
False
>>> (F/[(1, 0), (0, 1)]).is_zero()
True
"""
return self.base == self.killed_module
def is_submodule(self, other):
"""
Return True if ``other`` is a submodule of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False
"""
if isinstance(other, QuotientModule):
return self.killed_module == other.killed_module and \
self.base.is_submodule(other.base)
if isinstance(other, SubQuotientModule):
return other.container == self
return False
def submodule(self, *gens, **opts):
"""
Generate a submodule.
This is the same as taking a quotient of a submodule of the base
module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> Q.submodule([x, 0])
<[x, 0] + <[x, x]>>
"""
return SubQuotientModule(gens, self, **opts)
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> F.convert([1, 0])
[1, 0] + <[1, 2], [1, x]>
"""
if isinstance(elem, QuotientModuleElement):
if elem.module is self:
return elem
if self.killed_module.is_submodule(elem.module.killed_module):
return QuotientModuleElement(self, self.base.convert(elem.data))
raise CoercionFailed
return QuotientModuleElement(self, self.base.convert(elem))
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.identity_hom()
Matrix([
[1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module).quotient_domain(self.killed_module)
def quotient_hom(self):
"""
Return the quotient homomorphism to ``self``.
That is, return a homomorphism representing the natural map from
``self.base`` to ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.quotient_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module)
|
a8362c239475bdb79f1d24a28ccffd20b3786934ae26281e9d0373bbe60b016d | """Finite extensions of ring domains."""
from sympy.polys.polyerrors import CoercionFailed, NotInvertible
from sympy.polys.polytools import Poly
from sympy.printing.defaults import DefaultPrinting
class ExtensionElement(DefaultPrinting):
"""
Element of a finite extension.
A class of univariate polynomials modulo the ``modulus``
of the extension ``ext``. It is represented by the
unique polynomial ``rep`` of lowest degree. Both
``rep`` and the representation ``mod`` of ``modulus``
are of class DMP.
"""
__slots__ = ('rep', 'ext')
def __init__(self, rep, ext):
self.rep = rep
self.ext = ext
def __bool__(f):
return bool(f.rep)
def __neg__(f):
return ExtElem(-f.rep, f.ext)
def _get_rep(f, g):
if isinstance(g, ExtElem):
if g.ext == f.ext:
return g.rep
else:
return None
else:
try:
g = f.ext.convert(g)
return g.rep
except CoercionFailed:
return None
def __add__(f, g):
rep = f._get_rep(g)
if rep is not None:
return ExtElem(f.rep + rep, f.ext)
else:
return NotImplemented
__radd__ = __add__
def __sub__(f, g):
rep = f._get_rep(g)
if rep is not None:
return ExtElem(f.rep - rep, f.ext)
else:
return NotImplemented
def __rsub__(f, g):
rep = f._get_rep(g)
if rep is not None:
return ExtElem(rep - f.rep, f.ext)
else:
return NotImplemented
def __mul__(f, g):
rep = f._get_rep(g)
if rep is not None:
return ExtElem((f.rep*rep) % f.ext.mod, f.ext)
else:
return NotImplemented
__rmul__ = __mul__
def inverse(f):
"""Multiplicative inverse.
Raises
======
NotInvertible
If the element is a zero divisor.
"""
if not f.ext.domain.is_Field:
raise NotImplementedError("base field expected")
return ExtElem(f.rep.invert(f.ext.mod), f.ext)
def _invrep(f, g):
rep = f._get_rep(g)
if rep is not None:
return rep.invert(f.ext.mod)
else:
return None
def __truediv__(f, g):
if not f.ext.domain.is_Field:
return NotImplemented
try:
rep = f._invrep(g)
except NotInvertible:
raise ZeroDivisionError
if rep is not None:
return f*ExtElem(rep, f.ext)
else:
return NotImplemented
__floordiv__ = __truediv__
def __rtruediv__(f, g):
try:
return f.ext.convert(g)/f
except CoercionFailed:
return NotImplemented
__rfloordiv__ = __rtruediv__
def __pow__(f, n):
if not isinstance(n, int):
raise TypeError("exponent of type 'int' expected")
if n < 0:
try:
f, n = f.inverse(), -n
except NotImplementedError:
raise ValueError("negative powers are not defined")
b = f.rep
m = f.ext.mod
r = f.ext.one.rep
while n > 0:
if n % 2:
r = (r*b) % m
b = (b*b) % m
n //= 2
return ExtElem(r, f.ext)
def __eq__(f, g):
if isinstance(g, ExtElem):
return f.rep == g.rep and f.ext == g.ext
else:
return NotImplemented
def __ne__(f, g):
return not f == g
def __hash__(f):
return hash((f.rep, f.ext))
def __str__(f):
from sympy.printing.str import sstr
return sstr(f.rep)
__repr__ = __str__
ExtElem = ExtensionElement
class MonogenicFiniteExtension:
r"""
Finite extension generated by an integral element.
The generator is defined by a monic univariate
polynomial derived from the argument ``mod``.
A shorter alias is ``FiniteExtension``.
Examples
========
Quadratic integer ring $\mathbb{Z}[\sqrt2]$:
>>> from sympy import Symbol, Poly
>>> from sympy.polys.agca.extensions import FiniteExtension
>>> x = Symbol('x')
>>> R = FiniteExtension(Poly(x**2 - 2)); R
ZZ[x]/(x**2 - 2)
>>> R.rank
2
>>> R(1 + x)*(3 - 2*x)
x - 1
Finite field $GF(5^3)$ defined by the primitive
polynomial $x^3 + x^2 + 2$ (over $\mathbb{Z}_5$).
>>> F = FiniteExtension(Poly(x**3 + x**2 + 2, modulus=5)); F
GF(5)[x]/(x**3 + x**2 + 2)
>>> F.basis
(1, x, x**2)
>>> F(x + 3)/(x**2 + 2)
-2*x**2 + x + 2
Function field of an elliptic curve:
>>> t = Symbol('t')
>>> FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True))
ZZ(x)[t]/(t**2 - x**3 - x + 1)
Notes
=====
``FiniteExtension`` is not a subclass of :class:`~.Domain`. Consequently,
a ``FiniteExtension`` can't currently be used as ``domain`` for the
:class:`~.Poly` class.
"""
def __init__(self, mod):
if not (isinstance(mod, Poly) and mod.is_univariate):
raise TypeError("modulus must be a univariate Poly")
mod, rem = mod.div(mod.LC())
if not rem.is_zero:
raise ValueError("modulus could not be made monic")
self.rank = mod.degree()
self.modulus = mod
self.mod = mod.rep # DMP representation
self.domain = dom = mod.domain
self.ring = mod.rep.ring or dom.old_poly_ring(*mod.gens)
self.zero = self.convert(self.ring.zero)
self.one = self.convert(self.ring.one)
gen = self.ring.gens[0]
self.generator = self.convert(gen)
self.basis = tuple(self.convert(gen**i)
for i in range(self.rank))
def convert(self, f):
rep = self.ring.convert(f)
return ExtElem(rep % self.mod, self)
def to_sympy(self, f):
return self.ring.to_sympy(f.rep)
__call__ = convert
def __str__(self):
return "%s/(%s)" % (self.ring, self.modulus.as_expr())
__repr__ = __str__
FiniteExtension = MonogenicFiniteExtension
|
3a520ea80915dce601d0695ef99ed4f2caf2cbc4fe8dc3043b60b262e0293ca6 | #!/usr/bin/env python
"""
Import diagnostics. Run bin/diagnose_imports.py --help for details.
"""
from typing import Dict
if __name__ == "__main__":
import sys
import inspect
import builtins
import optparse
from os.path import abspath, dirname, join, normpath
this_file = abspath(__file__)
sympy_dir = join(dirname(this_file), '..', '..', '..')
sympy_dir = normpath(sympy_dir)
sys.path.insert(0, sympy_dir)
option_parser = optparse.OptionParser(
usage=
"Usage: %prog option [options]\n"
"\n"
"Import analysis for imports between SymPy modules.")
option_group = optparse.OptionGroup(
option_parser,
'Analysis options',
'Options that define what to do. Exactly one of these must be given.')
option_group.add_option(
'--problems',
help=
'Print all import problems, that is: '
'If an import pulls in a package instead of a module '
'(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE##
'if it imports a symbol that is already present; ' # see ##DUPLICATE##
'if it imports a symbol '
'from somewhere other than the defining module.', # see ##ORIGIN##
action='count')
option_group.add_option(
'--origins',
help=
'For each imported symbol in each module, '
'print the module that defined it. '
'(This is useful for import refactoring.)',
action='count')
option_parser.add_option_group(option_group)
option_group = optparse.OptionGroup(
option_parser,
'Sort options',
'These options define the sort order for output lines. '
'At most one of these options is allowed. '
'Unsorted output will reflect the order in which imports happened.')
option_group.add_option(
'--by-importer',
help='Sort output lines by name of importing module.',
action='count')
option_group.add_option(
'--by-origin',
help='Sort output lines by name of imported module.',
action='count')
option_parser.add_option_group(option_group)
(options, args) = option_parser.parse_args()
if args:
option_parser.error(
'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0]))
if options.problems > 1:
option_parser.error('--problems must not be given more than once.')
if options.origins > 1:
option_parser.error('--origins must not be given more than once.')
if options.by_importer > 1:
option_parser.error('--by-importer must not be given more than once.')
if options.by_origin > 1:
option_parser.error('--by-origin must not be given more than once.')
options.problems = options.problems == 1
options.origins = options.origins == 1
options.by_importer = options.by_importer == 1
options.by_origin = options.by_origin == 1
if not options.problems and not options.origins:
option_parser.error(
'At least one of --problems and --origins is required')
if options.problems and options.origins:
option_parser.error(
'At most one of --problems and --origins is allowed')
if options.by_importer and options.by_origin:
option_parser.error(
'At most one of --by-importer and --by-origin is allowed')
options.by_process = not options.by_importer and not options.by_origin
builtin_import = builtins.__import__
class Definition:
"""Information about a symbol's definition."""
def __init__(self, name, value, definer):
self.name = name
self.value = value
self.definer = definer
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name and self.value == other.value
def __ne__(self, other):
return not (self == other)
def __repr__(self):
return 'Definition(%s, ..., %s)' % (
repr(self.name), repr(self.definer))
# Maps each function/variable to name of module to define it
symbol_definers = {} # type: Dict[Definition, str]
def in_module(a, b):
"""Is a the same module as or a submodule of b?"""
return a == b or a != None and b != None and a.startswith(b + '.')
def relevant(module):
"""Is module relevant for import checking?
Only imports between relevant modules will be checked."""
return in_module(module, 'sympy')
sorted_messages = []
def msg(msg, *args):
global options, sorted_messages
if options.by_process:
print(msg % args)
else:
sorted_messages.append(msg % args)
def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1):
"""__import__ wrapper - does not change imports at all, but tracks them.
Default order is implemented by doing output directly.
All other orders are implemented by collecting output information into
a sorted list that will be emitted after all imports are processed.
Indirect imports can only occur after the requested symbol has been
imported directly (because the indirect import would not have a module
to pick the symbol up from).
So this code detects indirect imports by checking whether the symbol in
question was already imported.
Keeps the semantics of __import__ unchanged."""
global options, symbol_definers
caller_frame = inspect.getframeinfo(sys._getframe(1))
importer_filename = caller_frame.filename
importer_module = globals['__name__']
if importer_filename == caller_frame.filename:
importer_reference = '%s line %s' % (
importer_filename, str(caller_frame.lineno))
else:
importer_reference = importer_filename
result = builtin_import(module, globals, locals, fromlist, level)
importee_module = result.__name__
# We're only interested if importer and importee are in SymPy
if relevant(importer_module) and relevant(importee_module):
for symbol in result.__dict__.iterkeys():
definition = Definition(
symbol, result.__dict__[symbol], importer_module)
if not definition in symbol_definers:
symbol_definers[definition] = importee_module
if hasattr(result, '__path__'):
##PACKAGE##
# The existence of __path__ is documented in the tutorial on modules.
# Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html
if options.by_origin:
msg('Error: %s (a package) is imported by %s',
module, importer_reference)
else:
msg('Error: %s contains package import %s',
importer_reference, module)
if fromlist != None:
symbol_list = fromlist
if '*' in symbol_list:
if (importer_filename.endswith('__init__.py')
or importer_filename.endswith('__init__.pyc')
or importer_filename.endswith('__init__.pyo')):
# We do not check starred imports inside __init__
# That's the normal "please copy over its imports to my namespace"
symbol_list = []
else:
symbol_list = result.__dict__.iterkeys()
for symbol in symbol_list:
if not symbol in result.__dict__:
if options.by_origin:
msg('Error: %s.%s is not defined (yet), but %s tries to import it',
importee_module, symbol, importer_reference)
else:
msg('Error: %s tries to import %s.%s, which did not define it (yet)',
importer_reference, importee_module, symbol)
else:
definition = Definition(
symbol, result.__dict__[symbol], importer_module)
symbol_definer = symbol_definers[definition]
if symbol_definer == importee_module:
##DUPLICATE##
if options.by_origin:
msg('Error: %s.%s is imported again into %s',
importee_module, symbol, importer_reference)
else:
msg('Error: %s imports %s.%s again',
importer_reference, importee_module, symbol)
else:
##ORIGIN##
if options.by_origin:
msg('Error: %s.%s is imported by %s, which should import %s.%s instead',
importee_module, symbol, importer_reference, symbol_definer, symbol)
else:
msg('Error: %s imports %s.%s but should import %s.%s instead',
importer_reference, importee_module, symbol, symbol_definer, symbol)
return result
builtins.__import__ = tracking_import
__import__('sympy')
sorted_messages.sort()
for message in sorted_messages:
print(message)
|
2452330ae26a084a8154a71fdf82a1b57b424801c487b9f53f6b85385d5ac7c6 | from sympy import Symbol, Rational, S
from sympy.geometry import Circle, Ellipse, Line, Point, Polygon, Ray, RegularPolygon, Segment, Triangle
from sympy.geometry.entity import scale, GeometryEntity
from sympy.testing.pytest import raises
from random import random
def test_entity():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert GeometryEntity(x, y) in GeometryEntity(x, y)
raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y))
assert GeometryEntity(x, y) == GeometryEntity(x, y)
assert GeometryEntity(x, y).equals(GeometryEntity(x, y))
c = Circle((0, 0), 5)
assert GeometryEntity.encloses(c, Point(0, 0))
assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1)))
assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False
assert GeometryEntity.encloses(c, Circle((0, 0), 4))
assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1)))
assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False
def test_svg():
a = Symbol('a')
b = Symbol('b')
d = Symbol('d')
entity = Circle(Point(a, b), d)
assert entity._repr_svg_() is None
entity = Circle(Point(0, 0), S.Infinity)
assert entity._repr_svg_() is None
def test_subs():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
p = Point(x, 2)
q = Point(1, 1)
r = Point(3, 4)
for o in [p,
Segment(p, q),
Ray(p, q),
Line(p, q),
Triangle(p, q, r),
RegularPolygon(p, 3, 6),
Polygon(p, q, r, Point(5, 4)),
Circle(p, 3),
Ellipse(p, 3, 4)]:
assert 'y' in str(o.subs(x, y))
assert p.subs({x: 1}) == Point(1, 2)
assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4)
assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
assert Point(1, 2).subs({(1, 2)}) == Point(2, 2)
raises(ValueError, lambda: Point(1, 2).subs(1))
raises(ValueError, lambda: Point(1, 1).subs((Point(1, 1), Point(1,
2)), 1, 2))
def test_transform():
assert scale(1, 2, (3, 4)).tolist() == \
[[1, 0, 0], [0, 2, 0], [0, -4, 1]]
def test_reflect_entity_overrides():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
b = Symbol('b')
m = Symbol('m')
l = Line((0, b), slope=m)
p = Point(x, y)
r = p.reflect(l)
c = Circle((x, y), 3)
cr = c.reflect(l)
assert cr == Circle(r, -3)
assert c.area == -cr.area
pent = RegularPolygon((1, 2), 1, 5)
l = Line(pent.vertices[1],
slope=Rational(random() - .5, random() - .5))
rpent = pent.reflect(l)
assert rpent.center == pent.center.reflect(l)
rvert = [i.reflect(l) for i in pent.vertices]
for v in rpent.vertices:
for i in range(len(rvert)):
ri = rvert[i]
if ri.equals(v):
rvert.remove(ri)
break
assert not rvert
assert pent.area.equals(-rpent.area)
|
9f6d4842c41c2738e523873c0c700500b342a9981ffd44d6da8e98d7cc0f25d9 | from sympy.testing.pytest import raises, XFAIL
from sympy.external import import_module
from sympy import (
Symbol, Mul, Add, Abs, sin, asin, cos, Pow,
csc, sec, Limit, oo, Derivative, Integral, factorial,
sqrt, root, StrictLessThan, LessThan, StrictGreaterThan,
GreaterThan, Sum, Product, E, log, tan, Function, binomial, exp,
floor, ceiling, Unequality
)
from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge
from sympy.physics.quantum.state import Bra, Ket
from sympy.abc import x, y, z, a, b, c, t, k, n
antlr4 = import_module("antlr4")
# disable tests if antlr4-python*-runtime is not present
if not antlr4:
disabled = True
theta = Symbol('theta')
f = Function('f')
# shorthand definitions
def _Add(a, b):
return Add(a, b, evaluate=False)
def _Mul(a, b):
return Mul(a, b, evaluate=False)
def _Pow(a, b):
return Pow(a, b, evaluate=False)
def _Sqrt(a):
return sqrt(a, evaluate=False)
def _Abs(a):
return Abs(a, evaluate=False)
def _factorial(a):
return factorial(a, evaluate=False)
def _exp(a):
return exp(a, evaluate=False)
def _log(a, b):
return log(a, b, evaluate=False)
def _binomial(n, k):
return binomial(n, k, evaluate=False)
def test_import():
from sympy.parsing.latex._build_latex_antlr import (
build_parser,
check_antlr_version,
dir_latex_antlr
)
# XXX: It would be better to come up with a test for these...
del build_parser, check_antlr_version, dir_latex_antlr
# These LaTeX strings should parse to the corresponding SymPy expression
GOOD_PAIRS = [
("0", 0),
("1", 1),
("-3.14", _Mul(-1, 3.14)),
("(-7.13)(1.5)", _Mul(_Mul(-1, 7.13), 1.5)),
("x", x),
("2x", 2*x),
("x^2", x**2),
("x^{3 + 1}", x**_Add(3, 1)),
("-c", -c),
("a \\cdot b", a * b),
("a / b", a / b),
("a \\div b", a / b),
("a + b", a + b),
("a + b - a", _Add(a+b, -a)),
("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
("(x + y) z", _Mul(_Add(x, y), z)),
("\\left(x + y\\right) z", _Mul(_Add(x, y), z)),
("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)),
("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)),
("\\left[x + y\\right] z", _Mul(_Add(x, y), z)),
("\\left\\{x + y\\right\\} z", _Mul(_Add(x, y), z)),
("1+1", _Add(1, 1)),
("0+1", _Add(0, 1)),
("1*2", _Mul(1, 2)),
("0*1", _Mul(0, 1)),
("x = y", Eq(x, y)),
("x \\neq y", Ne(x, y)),
("x < y", Lt(x, y)),
("x > y", Gt(x, y)),
("x \\leq y", Le(x, y)),
("x \\geq y", Ge(x, y)),
("x \\le y", Le(x, y)),
("x \\ge y", Ge(x, y)),
("\\lfloor x \\rfloor", floor(x)),
("\\lceil x \\rceil", ceiling(x)),
("\\langle x |", Bra('x')),
("| x \\rangle", Ket('x')),
("\\sin \\theta", sin(theta)),
("\\sin(\\theta)", sin(theta)),
("\\sin^{-1} a", asin(a)),
("\\sin a \\cos b", _Mul(sin(a), cos(b))),
("\\sin \\cos \\theta", sin(cos(theta))),
("\\sin(\\cos \\theta)", sin(cos(theta))),
("\\frac{a}{b}", a / b),
("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
("\\frac{7}{3}", _Mul(7, _Pow(3, -1))),
("(\\csc x)(\\sec y)", csc(x)*sec(y)),
("\\lim_{x \\to 3} a", Limit(a, x, 3)),
("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)),
("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)),
("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)),
("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)),
("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')),
("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')),
("\\infty", oo),
("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Pow(x, -1), x, oo)),
("\\frac{d}{dx} x", Derivative(x, x)),
("\\frac{d}{dt} x", Derivative(x, t)),
("f(x)", f(x)),
("f(x, y)", f(x, y)),
("f(x, y, z)", f(x, y, z)),
("\\frac{d f(x)}{dx}", Derivative(f(x), x)),
("\\frac{d\\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
("x \\neq y", Unequality(x, y)),
("|x|", _Abs(x)),
("||x||", _Abs(Abs(x))),
("|x||y|", _Abs(x)*_Abs(y)),
("||x||y||", _Abs(_Abs(x)*_Abs(y))),
("\\pi^{|xy|}", Symbol('pi')**_Abs(x*y)),
("\\int x dx", Integral(x, x)),
("\\int x d\\theta", Integral(x, theta)),
("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
("\\int x + a dx", Integral(_Add(x, a), x)),
("\\int da", Integral(1, a)),
("\\int_0^7 dx", Integral(1, (x, 0, 7))),
("\\int_a^b x dx", Integral(x, (x, a, b))),
("\\int^b_a x dx", Integral(x, (x, a, b))),
("\\int_{a}^b x dx", Integral(x, (x, a, b))),
("\\int^{b}_a x dx", Integral(x, (x, a, b))),
("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
("\\int (x+a)", Integral(_Add(x, a), x)),
("\\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
("\\int \\frac{3 dz}{z}", Integral(3*Pow(z, -1), z)),
("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
("\\int \\frac{1}{a} + \\frac{1}{b} dx",
Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
("\\int \\frac{3 \\cdot d\\theta}{\\theta}",
Integral(3*_Pow(theta, -1), theta)),
("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
("x_0", Symbol('x_{0}')),
("x_{1}", Symbol('x_{1}')),
("x_a", Symbol('x_{a}')),
("x_{b}", Symbol('x_{b}')),
("h_\\theta", Symbol('h_{theta}')),
("h_{\\theta}", Symbol('h_{theta}')),
("h_{\\theta}(x_0, x_1)",
Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
("x!", _factorial(x)),
("100!", _factorial(100)),
("\\theta!", _factorial(theta)),
("(x + 1)!", _factorial(_Add(x, 1))),
("(x!)!", _factorial(_factorial(x))),
("x!!!", _factorial(_factorial(_factorial(x)))),
("5!7!", _Mul(_factorial(5), _factorial(7))),
("\\sqrt{x}", sqrt(x)),
("\\sqrt{x + b}", sqrt(_Add(x, b))),
("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
("\\sqrt[y]{\\sin x}", root(sin(x), y)),
("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
("\\sqrt{\\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))),
("x < y", StrictLessThan(x, y)),
("x \\leq y", LessThan(x, y)),
("x > y", StrictGreaterThan(x, y)),
("x \\geq y", GreaterThan(x, y)),
("\\mathit{x}", Symbol('x')),
("\\mathit{test}", Symbol('test')),
("\\mathit{TEST}", Symbol('TEST')),
("\\mathit{HELLO world}", Symbol('HELLO world')),
("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}",
Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
("\\prod_{a = b}^{c} x", Product(x, (a, b, c))),
("\\prod_{a = b}^c x", Product(x, (a, b, c))),
("\\prod^{c}_{a = b} x", Product(x, (a, b, c))),
("\\prod^c_{a = b} x", Product(x, (a, b, c))),
("\\exp x", _exp(x)),
("\\exp(x)", _exp(x)),
("\\ln x", _log(x, E)),
("\\ln xy", _log(x*y, E)),
("\\log x", _log(x, 10)),
("\\log xy", _log(x*y, 10)),
("\\log_{2} x", _log(x, 2)),
("\\log_{a} x", _log(x, a)),
("\\log_{11} x", _log(x, 11)),
("\\log_{a^2} x", _log(x, _Pow(a, 2))),
("[x]", x),
("[a + b]", _Add(a, b)),
("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)),
("\\binom{n}{k}", _binomial(n, k)),
("\\tbinom{n}{k}", _binomial(n, k)),
("\\dbinom{n}{k}", _binomial(n, k)),
("\\binom{n}{0}", _binomial(n, 0)),
("a \\, b", _Mul(a, b)),
("a \\thinspace b", _Mul(a, b)),
("a \\: b", _Mul(a, b)),
("a \\medspace b", _Mul(a, b)),
("a \\; b", _Mul(a, b)),
("a \\thickspace b", _Mul(a, b)),
("a \\quad b", _Mul(a, b)),
("a \\qquad b", _Mul(a, b)),
("a \\! b", _Mul(a, b)),
("a \\negthinspace b", _Mul(a, b)),
("a \\negmedspace b", _Mul(a, b)),
("a \\negthickspace b", _Mul(a, b)),
("\\int x \\, dx", Integral(x, x)),
]
def test_parseable():
from sympy.parsing.latex import parse_latex
for latex_str, sympy_expr in GOOD_PAIRS:
assert parse_latex(latex_str) == sympy_expr
# At time of migration from latex2sympy, should work but doesn't
FAILING_PAIRS = [
("\\log_2 x", _log(x, 2)),
("\\log_a x", _log(x, a)),
]
def test_failing_parseable():
from sympy.parsing.latex import parse_latex
for latex_str, sympy_expr in FAILING_PAIRS:
with raises(Exception):
assert parse_latex(latex_str) == sympy_expr
# These bad LaTeX strings should raise a LaTeXParsingError when parsed
BAD_STRINGS = [
"(",
")",
"\\frac{d}{dx}",
"(\\frac{d}{dx})"
"\\sqrt{}",
"\\sqrt",
"{",
"}",
"\\mathit{x + y}",
"\\mathit{21}",
"\\frac{2}{}",
"\\frac{}{2}",
"\\int",
"!",
"!0",
"_",
"^",
"|",
"||x|",
"()",
"((((((((((((((((()))))))))))))))))",
"-",
"\\frac{d}{dx} + \\frac{d}{dt}",
"f(x,,y)",
"f(x,y,",
"\\sin^x",
"\\cos^2",
"@",
"#",
"$",
"%",
"&",
"*",
"\\",
"~",
"\\frac{(2 + x}{1 - x)}"
]
def test_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
# At time of migration from latex2sympy, should fail but doesn't
FAILING_BAD_STRINGS = [
"\\cos 1 \\cos",
"f(,",
"f()",
"a \\div \\div b",
"a \\cdot \\cdot b",
"a // b",
"a +",
"1.1.1",
"1 +",
"a / b /",
]
@XFAIL
def test_failing_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in FAILING_BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
|
456198e310bb593c508068f6a996975880911824f0e6ea6a95c5dabbfdb8b62f | import os
import subprocess
import glob
from sympy.utilities.misc import debug
here = os.path.dirname(__file__)
grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))
dir_latex_antlr = os.path.join(here, "_antlr")
header = '''
# encoding: utf-8
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated from ../LaTeX.g4, derived from latex2sympy
# latex2sympy is licensed under the MIT license
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
'''
def check_antlr_version():
debug("Checking antlr4 version...")
try:
debug(subprocess.check_output(["antlr4"])
.decode('utf-8').split("\n")[0])
return True
except (subprocess.CalledProcessError, FileNotFoundError):
debug("The 'antlr4' command line tool is not installed, "
"or not on your PATH.\n"
"> Please refer to the README.md file for more information.")
return False
def build_parser(output_dir=dir_latex_antlr):
check_antlr_version()
debug("Updating ANTLR-generated code in {}".format(output_dir))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
fp.write(header)
args = [
"antlr4",
grammar_file,
"-o", output_dir,
# for now, not generating these as latex2sympy did not use them
"-no-visitor",
"-no-listener",
]
debug("Running code generation...\n\t$ {}".format(" ".join(args)))
subprocess.check_output(args, cwd=output_dir)
debug("Applying headers, removing unnecessary files and renaming...")
# Handle case insensitive file systems. If the files are already
# generated, they will be written to latex* but LaTeX*.* won't match them.
for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) +
glob.glob(os.path.join(output_dir, "latex*.*"))):
# Remove files ending in .interp or .tokens as they are not needed.
if not path.endswith(".py"):
os.unlink(path)
continue
new_path = os.path.join(output_dir, os.path.basename(path).lower())
with open(path, 'r') as f:
lines = [line.rstrip() + '\n' for line in f.readlines()]
os.unlink(path)
with open(new_path, "w") as out_file:
offset = 2
out_file.write(header)
out_file.writelines(lines[offset:])
debug("\t{}".format(new_path))
return True
if __name__ == "__main__":
build_parser()
|
0c81381c17d2eef7ce6d0c78f59cd4ed37e0786908eed491d83b6b08f1b419bc | # Ported from latex2sympy by @augustt198
# https://github.com/augustt198/latex2sympy
# See license in LICENSE.txt
import sympy
from sympy.external import import_module
from sympy.printing.str import StrPrinter
from sympy.physics.quantum.state import Bra, Ket
from .errors import LaTeXParsingError
LaTeXParser = LaTeXLexer = MathErrorListener = None
try:
LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
except Exception:
pass
ErrorListener = import_module('antlr4.error.ErrorListener',
warn_not_installed=True,
import_kwargs={'fromlist': ['ErrorListener']}
)
if ErrorListener:
class MathErrorListener(ErrorListener.ErrorListener): # type: ignore
def __init__(self, src):
super(ErrorListener.ErrorListener, self).__init__()
self.src = src
def syntaxError(self, recog, symbol, line, col, msg, e):
fmt = "%s\n%s\n%s"
marker = "~" * col + "^"
if msg.startswith("missing"):
err = fmt % (msg, self.src, marker)
elif msg.startswith("no viable"):
err = fmt % ("I expected something else here", self.src, marker)
elif msg.startswith("mismatched"):
names = LaTeXParser.literalNames
expected = [
names[i] for i in e.getExpectedTokens() if i < len(names)
]
if len(expected) < 10:
expected = " ".join(expected)
err = (fmt % ("I expected one of these: " + expected, self.src,
marker))
else:
err = (fmt % ("I expected something else here", self.src,
marker))
else:
err = fmt % ("I don't understand this", self.src, marker)
raise LaTeXParsingError(err)
def parse_latex(sympy):
antlr4 = import_module('antlr4', warn_not_installed=True)
if None in [antlr4, MathErrorListener]:
raise ImportError("LaTeX parsing requires the antlr4 python package,"
" provided by pip (antlr4-python2-runtime or"
" antlr4-python3-runtime) or"
" conda (antlr-python-runtime)")
matherror = MathErrorListener(sympy)
stream = antlr4.InputStream(sympy)
lex = LaTeXLexer(stream)
lex.removeErrorListeners()
lex.addErrorListener(matherror)
tokens = antlr4.CommonTokenStream(lex)
parser = LaTeXParser(tokens)
# remove default console error listener
parser.removeErrorListeners()
parser.addErrorListener(matherror)
relation = parser.math().relation()
expr = convert_relation(relation)
return expr
def convert_relation(rel):
if rel.expr():
return convert_expr(rel.expr())
lh = convert_relation(rel.relation(0))
rh = convert_relation(rel.relation(1))
if rel.LT():
return sympy.StrictLessThan(lh, rh)
elif rel.LTE():
return sympy.LessThan(lh, rh)
elif rel.GT():
return sympy.StrictGreaterThan(lh, rh)
elif rel.GTE():
return sympy.GreaterThan(lh, rh)
elif rel.EQUAL():
return sympy.Eq(lh, rh)
elif rel.NEQ():
return sympy.Ne(lh, rh)
def convert_expr(expr):
return convert_add(expr.additive())
def convert_add(add):
if add.ADD():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, rh, evaluate=False)
elif add.SUB():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, -1 * rh, evaluate=False)
else:
return convert_mp(add.mp())
def convert_mp(mp):
if hasattr(mp, 'mp'):
mp_left = mp.mp(0)
mp_right = mp.mp(1)
else:
mp_left = mp.mp_nofunc(0)
mp_right = mp.mp_nofunc(1)
if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, rh, evaluate=False)
elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
else:
if hasattr(mp, 'unary'):
return convert_unary(mp.unary())
else:
return convert_unary(mp.unary_nofunc())
def convert_unary(unary):
if hasattr(unary, 'unary'):
nested_unary = unary.unary()
else:
nested_unary = unary.unary_nofunc()
if hasattr(unary, 'postfix_nofunc'):
first = unary.postfix()
tail = unary.postfix_nofunc()
postfix = [first] + tail
else:
postfix = unary.postfix()
if unary.ADD():
return convert_unary(nested_unary)
elif unary.SUB():
numabs = convert_unary(nested_unary)
if numabs == 1:
# Use Integer(-1) instead of Mul(-1, 1)
return -numabs
else:
return sympy.Mul(-1, convert_unary(nested_unary), evaluate=False)
elif postfix:
return convert_postfix_list(postfix)
def convert_postfix_list(arr, i=0):
if i >= len(arr):
raise LaTeXParsingError("Index out of bounds")
res = convert_postfix(arr[i])
if isinstance(res, sympy.Expr):
if i == len(arr) - 1:
return res # nothing to multiply by
else:
if i > 0:
left = convert_postfix(arr[i - 1])
right = convert_postfix(arr[i + 1])
if isinstance(left, sympy.Expr) and isinstance(
right, sympy.Expr):
left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
right_syms = convert_postfix(arr[i + 1]).atoms(
sympy.Symbol)
# if the left and right sides contain no variables and the
# symbol in between is 'x', treat as multiplication.
if len(left_syms) == 0 and len(right_syms) == 0 and str(
res) == "x":
return convert_postfix_list(arr, i + 1)
# multiply by next
return sympy.Mul(
res, convert_postfix_list(arr, i + 1), evaluate=False)
else: # must be derivative
wrt = res[0]
if i == len(arr) - 1:
raise LaTeXParsingError("Expected expression for derivative")
else:
expr = convert_postfix_list(arr, i + 1)
return sympy.Derivative(expr, wrt)
def do_subs(expr, at):
if at.expr():
at_expr = convert_expr(at.expr())
syms = at_expr.atoms(sympy.Symbol)
if len(syms) == 0:
return expr
elif len(syms) > 0:
sym = next(iter(syms))
return expr.subs(sym, at_expr)
elif at.equality():
lh = convert_expr(at.equality().expr(0))
rh = convert_expr(at.equality().expr(1))
return expr.subs(lh, rh)
def convert_postfix(postfix):
if hasattr(postfix, 'exp'):
exp_nested = postfix.exp()
else:
exp_nested = postfix.exp_nofunc()
exp = convert_exp(exp_nested)
for op in postfix.postfix_op():
if op.BANG():
if isinstance(exp, list):
raise LaTeXParsingError("Cannot apply postfix to derivative")
exp = sympy.factorial(exp, evaluate=False)
elif op.eval_at():
ev = op.eval_at()
at_b = None
at_a = None
if ev.eval_at_sup():
at_b = do_subs(exp, ev.eval_at_sup())
if ev.eval_at_sub():
at_a = do_subs(exp, ev.eval_at_sub())
if at_b is not None and at_a is not None:
exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
elif at_b is not None:
exp = at_b
elif at_a is not None:
exp = at_a
return exp
def convert_exp(exp):
if hasattr(exp, 'exp'):
exp_nested = exp.exp()
else:
exp_nested = exp.exp_nofunc()
if exp_nested:
base = convert_exp(exp_nested)
if isinstance(base, list):
raise LaTeXParsingError("Cannot raise derivative to power")
if exp.atom():
exponent = convert_atom(exp.atom())
elif exp.expr():
exponent = convert_expr(exp.expr())
return sympy.Pow(base, exponent, evaluate=False)
else:
if hasattr(exp, 'comp'):
return convert_comp(exp.comp())
else:
return convert_comp(exp.comp_nofunc())
def convert_comp(comp):
if comp.group():
return convert_expr(comp.group().expr())
elif comp.abs_group():
return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
elif comp.atom():
return convert_atom(comp.atom())
elif comp.frac():
return convert_frac(comp.frac())
elif comp.binom():
return convert_binom(comp.binom())
elif comp.floor():
return convert_floor(comp.floor())
elif comp.ceil():
return convert_ceil(comp.ceil())
elif comp.func():
return convert_func(comp.func())
def convert_atom(atom):
if atom.LETTER():
subscriptName = ''
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = '_{' + StrPrinter().doprint(subscript) + '}'
return sympy.Symbol(atom.LETTER().getText() + subscriptName)
elif atom.SYMBOL():
s = atom.SYMBOL().getText()[1:]
if s == "infty":
return sympy.oo
else:
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
s += '_{' + subscriptName + '}'
return sympy.Symbol(s)
elif atom.NUMBER():
s = atom.NUMBER().getText().replace(",", "")
return sympy.Number(s)
elif atom.DIFFERENTIAL():
var = get_differential_var(atom.DIFFERENTIAL())
return sympy.Symbol('d' + var.name)
elif atom.mathit():
text = rule2text(atom.mathit().mathit_text())
return sympy.Symbol(text)
elif atom.bra():
val = convert_expr(atom.bra().expr())
return Bra(val)
elif atom.ket():
val = convert_expr(atom.ket().expr())
return Ket(val)
def rule2text(ctx):
stream = ctx.start.getInputStream()
# starting index of starting token
startIdx = ctx.start.start
# stopping index of stopping token
stopIdx = ctx.stop.stop
return stream.getText(startIdx, stopIdx)
def convert_frac(frac):
diff_op = False
partial_op = False
lower_itv = frac.lower.getSourceInterval()
lower_itv_len = lower_itv[1] - lower_itv[0] + 1
if (frac.lower.start == frac.lower.stop
and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
wrt = get_differential_var_str(frac.lower.start.text)
diff_op = True
elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
and frac.lower.start.text == '\\partial'
and (frac.lower.stop.type == LaTeXLexer.LETTER
or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
partial_op = True
wrt = frac.lower.stop.text
if frac.lower.stop.type == LaTeXLexer.SYMBOL:
wrt = wrt[1:]
if diff_op or partial_op:
wrt = sympy.Symbol(wrt)
if (diff_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.LETTER
and frac.upper.start.text == 'd'):
return [wrt]
elif (partial_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.SYMBOL
and frac.upper.start.text == '\\partial'):
return [wrt]
upper_text = rule2text(frac.upper)
expr_top = None
if diff_op and upper_text.startswith('d'):
expr_top = parse_latex(upper_text[1:])
elif partial_op and frac.upper.start.text == '\\partial':
expr_top = parse_latex(upper_text[len('\\partial'):])
if expr_top:
return sympy.Derivative(expr_top, wrt)
expr_top = convert_expr(frac.upper)
expr_bot = convert_expr(frac.lower)
inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
if expr_top == 1:
return inverse_denom
else:
return sympy.Mul(expr_top, inverse_denom, evaluate=False)
def convert_binom(binom):
expr_n = convert_expr(binom.n)
expr_k = convert_expr(binom.k)
return sympy.binomial(expr_n, expr_k, evaluate=False)
def convert_floor(floor):
val = convert_expr(floor.val)
return sympy.floor(val, evaluate=False)
def convert_ceil(ceil):
val = convert_expr(ceil.val)
return sympy.ceiling(val, evaluate=False)
def convert_func(func):
if func.func_normal():
if func.L_PAREN(): # function called with parenthesis
arg = convert_func_arg(func.func_arg())
else:
arg = convert_func_arg(func.func_arg_noparens())
name = func.func_normal().start.text[1:]
# change arc<trig> -> a<trig>
if name in [
"arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
]:
name = "a" + name[3:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name in ["arsinh", "arcosh", "artanh"]:
name = "a" + name[2:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name == "exp":
expr = sympy.exp(arg, evaluate=False)
if (name == "log" or name == "ln"):
if func.subexpr():
base = convert_expr(func.subexpr().expr())
elif name == "log":
base = 10
elif name == "ln":
base = sympy.E
expr = sympy.log(arg, base, evaluate=False)
func_pow = None
should_pow = True
if func.supexpr():
if func.supexpr().expr():
func_pow = convert_expr(func.supexpr().expr())
else:
func_pow = convert_atom(func.supexpr().atom())
if name in [
"sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
"tanh"
]:
if func_pow == -1:
name = "a" + name
should_pow = False
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if func_pow and should_pow:
expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr
elif func.LETTER() or func.SYMBOL():
if func.LETTER():
fname = func.LETTER().getText()
elif func.SYMBOL():
fname = func.SYMBOL().getText()[1:]
fname = str(fname) # can't be unicode
if func.subexpr():
subscript = None
if func.subexpr().expr(): # subscript is expr
subscript = convert_expr(func.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(func.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
fname += '_{' + subscriptName + '}'
input_args = func.args()
output_args = []
while input_args.args(): # handle multiple arguments to function
output_args.append(convert_expr(input_args.expr()))
input_args = input_args.args()
output_args.append(convert_expr(input_args.expr()))
return sympy.Function(fname)(*output_args)
elif func.FUNC_INT():
return handle_integral(func)
elif func.FUNC_SQRT():
expr = convert_expr(func.base)
if func.root:
r = convert_expr(func.root)
return sympy.root(expr, r, evaluate=False)
else:
return sympy.sqrt(expr, evaluate=False)
elif func.FUNC_SUM():
return handle_sum_or_prod(func, "summation")
elif func.FUNC_PROD():
return handle_sum_or_prod(func, "product")
elif func.FUNC_LIM():
return handle_limit(func)
def convert_func_arg(arg):
if hasattr(arg, 'expr'):
return convert_expr(arg.expr())
else:
return convert_mp(arg.mp_nofunc())
def handle_integral(func):
if func.additive():
integrand = convert_add(func.additive())
elif func.frac():
integrand = convert_frac(func.frac())
else:
integrand = 1
int_var = None
if func.DIFFERENTIAL():
int_var = get_differential_var(func.DIFFERENTIAL())
else:
for sym in integrand.atoms(sympy.Symbol):
s = str(sym)
if len(s) > 1 and s[0] == 'd':
if s[1] == '\\':
int_var = sympy.Symbol(s[2:])
else:
int_var = sympy.Symbol(s[1:])
int_sym = sym
if int_var:
integrand = integrand.subs(int_sym, 1)
else:
# Assume dx by default
int_var = sympy.Symbol('x')
if func.subexpr():
if func.subexpr().atom():
lower = convert_atom(func.subexpr().atom())
else:
lower = convert_expr(func.subexpr().expr())
if func.supexpr().atom():
upper = convert_atom(func.supexpr().atom())
else:
upper = convert_expr(func.supexpr().expr())
return sympy.Integral(integrand, (int_var, lower, upper))
else:
return sympy.Integral(integrand, int_var)
def handle_sum_or_prod(func, name):
val = convert_mp(func.mp())
iter_var = convert_expr(func.subeq().equality().expr(0))
start = convert_expr(func.subeq().equality().expr(1))
if func.supexpr().expr(): # ^{expr}
end = convert_expr(func.supexpr().expr())
else: # ^atom
end = convert_atom(func.supexpr().atom())
if name == "summation":
return sympy.Sum(val, (iter_var, start, end))
elif name == "product":
return sympy.Product(val, (iter_var, start, end))
def handle_limit(func):
sub = func.limit_sub()
if sub.LETTER():
var = sympy.Symbol(sub.LETTER().getText())
elif sub.SYMBOL():
var = sympy.Symbol(sub.SYMBOL().getText()[1:])
else:
var = sympy.Symbol('x')
if sub.SUB():
direction = "-"
else:
direction = "+"
approaching = convert_expr(sub.expr())
content = convert_mp(func.mp())
return sympy.Limit(content, var, approaching, direction)
def get_differential_var(d):
text = get_differential_var_str(d.getText())
return sympy.Symbol(text)
def get_differential_var_str(text):
for i in range(1, len(text)):
c = text[i]
if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
idx = i
break
text = text[idx:]
if text[0] == "\\":
text = text[1:]
return text
|
f323d5f7de73cda2844ef30b76000b889cad9f1267769117408d5cf4c4cc3bc6 | """Hermitian conjugation."""
from sympy.core import Expr, Mul
from sympy.functions.elementary.complexes import adjoint
__all__ = [
'Dagger'
]
class Dagger(adjoint):
"""General Hermitian conjugate operation.
Explanation
===========
Take the Hermetian conjugate of an argument [1]_. For matrices this
operation is equivalent to transpose and complex conjugate [2]_.
Parameters
==========
arg : Expr
The sympy expression that we want to take the dagger of.
Examples
========
Daggering various quantum objects:
>>> from sympy.physics.quantum.dagger import Dagger
>>> from sympy.physics.quantum.state import Ket, Bra
>>> from sympy.physics.quantum.operator import Operator
>>> Dagger(Ket('psi'))
<psi|
>>> Dagger(Bra('phi'))
|phi>
>>> Dagger(Operator('A'))
Dagger(A)
Inner and outer products::
>>> from sympy.physics.quantum import InnerProduct, OuterProduct
>>> Dagger(InnerProduct(Bra('a'), Ket('b')))
<b|a>
>>> Dagger(OuterProduct(Ket('a'), Bra('b')))
|b><a|
Powers, sums and products::
>>> A = Operator('A')
>>> B = Operator('B')
>>> Dagger(A*B)
Dagger(B)*Dagger(A)
>>> Dagger(A+B)
Dagger(A) + Dagger(B)
>>> Dagger(A**2)
Dagger(A)**2
Dagger also seamlessly handles complex numbers and matrices::
>>> from sympy import Matrix, I
>>> m = Matrix([[1,I],[2,I]])
>>> m
Matrix([
[1, I],
[2, I]])
>>> Dagger(m)
Matrix([
[ 1, 2],
[-I, -I]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
.. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
"""
def __new__(cls, arg):
if hasattr(arg, 'adjoint'):
obj = arg.adjoint()
elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'):
obj = arg.conjugate().transpose()
if obj is not None:
return obj
return Expr.__new__(cls, arg)
def __mul__(self, other):
from sympy.physics.quantum import IdentityOperator
if isinstance(other, IdentityOperator):
return self
return Mul(self, other)
adjoint.__name__ = "Dagger"
adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
|
cd4d542c635f01acd8679014d52058e3620e7fe803ac7c57360d5e8333d40bef | """The anti-commutator: ``{A,B} = A*B + B*A``."""
from sympy import S, Expr, Mul, Integer
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.dagger import Dagger
__all__ = [
'AntiCommutator'
]
#-----------------------------------------------------------------------------
# Anti-commutator
#-----------------------------------------------------------------------------
class AntiCommutator(Expr):
"""The standard anticommutator, in an unevaluated state.
Explanation
===========
Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
This class returns the anticommutator in an unevaluated form. To evaluate
the anticommutator, use the ``.doit()`` method.
Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
arguments of the anticommutator are put into canonical order using
``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
Parameters
==========
A : Expr
The first argument of the anticommutator {A,B}.
B : Expr
The second argument of the anticommutator {A,B}.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.quantum import AntiCommutator
>>> from sympy.physics.quantum import Operator, Dagger
>>> x, y = symbols('x,y')
>>> A = Operator('A')
>>> B = Operator('B')
Create an anticommutator and use ``doit()`` to multiply them out.
>>> ac = AntiCommutator(A,B); ac
{A,B}
>>> ac.doit()
A*B + B*A
The commutator orders it arguments in canonical order:
>>> ac = AntiCommutator(B,A); ac
{A,B}
Commutative constants are factored out:
>>> AntiCommutator(3*x*A,x*y*B)
3*x**2*y*{A,B}
Adjoint operations applied to the anticommutator are properly applied to
the arguments:
>>> Dagger(AntiCommutator(A,B))
{Dagger(A),Dagger(B)}
References
==========
.. [1] https://en.wikipedia.org/wiki/Commutator
"""
is_commutative = False
def __new__(cls, A, B):
r = cls.eval(A, B)
if r is not None:
return r
obj = Expr.__new__(cls, A, B)
return obj
@classmethod
def eval(cls, a, b):
if not (a and b):
return S.Zero
if a == b:
return Integer(2)*a**2
if a.is_commutative or b.is_commutative:
return Integer(2)*a*b
# [xA,yB] -> xy*[A,B]
ca, nca = a.args_cnc()
cb, ncb = b.args_cnc()
c_part = ca + cb
if c_part:
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
# Canonical ordering of arguments
#The Commutator [A,B] is on canonical form if A < B.
if a.compare(b) == 1:
return cls(b, a)
def doit(self, **hints):
""" Evaluate anticommutator """
A = self.args[0]
B = self.args[1]
if isinstance(A, Operator) and isinstance(B, Operator):
try:
comm = A._eval_anticommutator(B, **hints)
except NotImplementedError:
try:
comm = B._eval_anticommutator(A, **hints)
except NotImplementedError:
comm = None
if comm is not None:
return comm.doit(**hints)
return (A*B + B*A).doit(**hints)
def _eval_adjoint(self):
return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
def _sympyrepr(self, printer, *args):
return "%s(%s,%s)" % (
self.__class__.__name__, printer._print(
self.args[0]), printer._print(self.args[1])
)
def _sympystr(self, printer, *args):
return "{%s,%s}" % (
printer._print(self.args[0]), printer._print(self.args[1]))
def _pretty(self, printer, *args):
pform = printer._print(self.args[0], *args)
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
pform = prettyForm(*pform.parens(left='{', right='}'))
return pform
def _latex(self, printer, *args):
return "\\left\\{%s,%s\\right\\}" % tuple([
printer._print(arg, *args) for arg in self.args])
|
cef625a310706076d1b1a8d781f5cf23293cae4f057dd43a97239aac82e92bd3 | """The commutator: [A,B] = A*B - B*A."""
from sympy import S, Expr, Mul, Add, Pow
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.operator import Operator
__all__ = [
'Commutator'
]
#-----------------------------------------------------------------------------
# Commutator
#-----------------------------------------------------------------------------
class Commutator(Expr):
"""The standard commutator, in an unevaluated state.
Explanation
===========
Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
class returns the commutator in an unevaluated form. To evaluate the
commutator, use the ``.doit()`` method.
Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
arguments of the commutator are put into canonical order using ``__cmp__``.
If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
Parameters
==========
A : Expr
The first argument of the commutator [A,B].
B : Expr
The second argument of the commutator [A,B].
Examples
========
>>> from sympy.physics.quantum import Commutator, Dagger, Operator
>>> from sympy.abc import x, y
>>> A = Operator('A')
>>> B = Operator('B')
>>> C = Operator('C')
Create a commutator and use ``.doit()`` to evaluate it:
>>> comm = Commutator(A, B)
>>> comm
[A,B]
>>> comm.doit()
A*B - B*A
The commutator orders it arguments in canonical order:
>>> comm = Commutator(B, A); comm
-[A,B]
Commutative constants are factored out:
>>> Commutator(3*x*A, x*y*B)
3*x**2*y*[A,B]
Using ``.expand(commutator=True)``, the standard commutator expansion rules
can be applied:
>>> Commutator(A+B, C).expand(commutator=True)
[A,C] + [B,C]
>>> Commutator(A, B+C).expand(commutator=True)
[A,B] + [A,C]
>>> Commutator(A*B, C).expand(commutator=True)
[A,C]*B + A*[B,C]
>>> Commutator(A, B*C).expand(commutator=True)
[A,B]*C + B*[A,C]
Adjoint operations applied to the commutator are properly applied to the
arguments:
>>> Dagger(Commutator(A, B))
-[Dagger(A),Dagger(B)]
References
==========
.. [1] https://en.wikipedia.org/wiki/Commutator
"""
is_commutative = False
def __new__(cls, A, B):
r = cls.eval(A, B)
if r is not None:
return r
obj = Expr.__new__(cls, A, B)
return obj
@classmethod
def eval(cls, a, b):
if not (a and b):
return S.Zero
if a == b:
return S.Zero
if a.is_commutative or b.is_commutative:
return S.Zero
# [xA,yB] -> xy*[A,B]
ca, nca = a.args_cnc()
cb, ncb = b.args_cnc()
c_part = ca + cb
if c_part:
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
# Canonical ordering of arguments
# The Commutator [A, B] is in canonical form if A < B.
if a.compare(b) == 1:
return S.NegativeOne*cls(b, a)
def _expand_pow(self, A, B, sign):
exp = A.exp
if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
# nothing to do
return self
base = A.base
if exp.is_negative:
base = A.base**-1
exp = -exp
comm = Commutator(base, B).expand(commutator=True)
result = base**(exp - 1) * comm
for i in range(1, exp):
result += base**(exp - 1 - i) * comm * base**i
return sign*result.expand()
def _eval_expand_commutator(self, **hints):
A = self.args[0]
B = self.args[1]
if isinstance(A, Add):
# [A + B, C] -> [A, C] + [B, C]
sargs = []
for term in A.args:
comm = Commutator(term, B)
if isinstance(comm, Commutator):
comm = comm._eval_expand_commutator()
sargs.append(comm)
return Add(*sargs)
elif isinstance(B, Add):
# [A, B + C] -> [A, B] + [A, C]
sargs = []
for term in B.args:
comm = Commutator(A, term)
if isinstance(comm, Commutator):
comm = comm._eval_expand_commutator()
sargs.append(comm)
return Add(*sargs)
elif isinstance(A, Mul):
# [A*B, C] -> A*[B, C] + [A, C]*B
a = A.args[0]
b = Mul(*A.args[1:])
c = B
comm1 = Commutator(b, c)
comm2 = Commutator(a, c)
if isinstance(comm1, Commutator):
comm1 = comm1._eval_expand_commutator()
if isinstance(comm2, Commutator):
comm2 = comm2._eval_expand_commutator()
first = Mul(a, comm1)
second = Mul(comm2, b)
return Add(first, second)
elif isinstance(B, Mul):
# [A, B*C] -> [A, B]*C + B*[A, C]
a = A
b = B.args[0]
c = Mul(*B.args[1:])
comm1 = Commutator(a, b)
comm2 = Commutator(a, c)
if isinstance(comm1, Commutator):
comm1 = comm1._eval_expand_commutator()
if isinstance(comm2, Commutator):
comm2 = comm2._eval_expand_commutator()
first = Mul(comm1, c)
second = Mul(b, comm2)
return Add(first, second)
elif isinstance(A, Pow):
# [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
return self._expand_pow(A, B, 1)
elif isinstance(B, Pow):
# [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
return self._expand_pow(B, A, -1)
# No changes, so return self
return self
def doit(self, **hints):
""" Evaluate commutator """
A = self.args[0]
B = self.args[1]
if isinstance(A, Operator) and isinstance(B, Operator):
try:
comm = A._eval_commutator(B, **hints)
except NotImplementedError:
try:
comm = -1*B._eval_commutator(A, **hints)
except NotImplementedError:
comm = None
if comm is not None:
return comm.doit(**hints)
return (A*B - B*A).doit(**hints)
def _eval_adjoint(self):
return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
def _sympyrepr(self, printer, *args):
return "%s(%s,%s)" % (
self.__class__.__name__, printer._print(
self.args[0]), printer._print(self.args[1])
)
def _sympystr(self, printer, *args):
return "[%s,%s]" % (
printer._print(self.args[0]), printer._print(self.args[1]))
def _pretty(self, printer, *args):
pform = printer._print(self.args[0], *args)
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
pform = prettyForm(*pform.parens(left='[', right=']'))
return pform
def _latex(self, printer, *args):
return "\\left[%s,%s\\right]" % tuple([
printer._print(arg, *args) for arg in self.args])
|
9491caf527eec0daff50709992efe2a828d075c74f4988d181cffad12736eaf7 | """Matplotlib based plotting of quantum circuits.
Todo:
* Optimize printing of large circuits.
* Get this to work with single gates.
* Do a better job checking the form of circuits to make sure it is a Mul of
Gates.
* Get multi-target gates plotting.
* Get initial and final states to plot.
* Get measurements to plot. Might need to rethink measurement as a gate
issue.
* Get scale and figsize to be handled in a better way.
* Write some tests/examples!
"""
from typing import List, Dict
from sympy import Mul
from sympy.external import import_module
from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
from sympy.core.core import BasicMeta
from sympy.core.assumptions import ManagedProperties
__all__ = [
'CircuitPlot',
'circuit_plot',
'labeller',
'Mz',
'Mx',
'CreateOneQubitGate',
'CreateCGate',
]
np = import_module('numpy')
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,)) # This is raised in environments that have no display.
if np and matplotlib:
pyplot = matplotlib.pyplot
Line2D = matplotlib.lines.Line2D
Circle = matplotlib.patches.Circle
#from matplotlib import rc
#rc('text',usetex=True)
class CircuitPlot:
"""A class for managing a circuit plot."""
scale = 1.0
fontsize = 20.0
linewidth = 1.0
control_radius = 0.05
not_radius = 0.15
swap_delta = 0.05
labels = [] # type: List[str]
inits = {} # type: Dict[str, str]
label_buffer = 0.5
def __init__(self, c, nqubits, **kwargs):
if not np or not matplotlib:
raise ImportError('numpy or matplotlib not available.')
self.circuit = c
self.ngates = len(self.circuit.args)
self.nqubits = nqubits
self.update(kwargs)
self._create_grid()
self._create_figure()
self._plot_wires()
self._plot_gates()
self._finish()
def update(self, kwargs):
"""Load the kwargs into the instance dict."""
self.__dict__.update(kwargs)
def _create_grid(self):
"""Create the grid of wires."""
scale = self.scale
wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
self._wire_grid = wire_grid
self._gate_grid = gate_grid
def _create_figure(self):
"""Create the main matplotlib figure."""
self._figure = pyplot.figure(
figsize=(self.ngates*self.scale, self.nqubits*self.scale),
facecolor='w',
edgecolor='w'
)
ax = self._figure.add_subplot(
1, 1, 1,
frameon=True
)
ax.set_axis_off()
offset = 0.5*self.scale
ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
ax.set_aspect('equal')
self._axes = ax
def _plot_wires(self):
"""Plot the wires of the circuit diagram."""
xstart = self._gate_grid[0]
xstop = self._gate_grid[-1]
xdata = (xstart - self.scale, xstop + self.scale)
for i in range(self.nqubits):
ydata = (self._wire_grid[i], self._wire_grid[i])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
if self.labels:
init_label_buffer = 0
if self.inits.get(self.labels[i]): init_label_buffer = 0.25
self._axes.text(
xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
render_label(self.labels[i],self.inits),
size=self.fontsize,
color='k',ha='center',va='center')
self._plot_measured_wires()
def _plot_measured_wires(self):
ismeasured = self._measurements()
xstop = self._gate_grid[-1]
dy = 0.04 # amount to shift wires when doubled
# Plot doubled wires after they are measured
for im in ismeasured:
xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
# Also double any controlled lines off these wires
for i,g in enumerate(self._gates()):
if isinstance(g, CGate) or isinstance(g, CGateS):
wires = g.controls + g.targets
for wire in wires:
if wire in ismeasured and \
self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
ydata = min(wires), max(wires)
xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def _gates(self):
"""Create a list of all gates in the circuit plot."""
gates = []
if isinstance(self.circuit, Mul):
for g in reversed(self.circuit.args):
if isinstance(g, Gate):
gates.append(g)
elif isinstance(self.circuit, Gate):
gates.append(self.circuit)
return gates
def _plot_gates(self):
"""Iterate through the gates and plot each of them."""
for i, gate in enumerate(self._gates()):
gate.plot_gate(self, i)
def _measurements(self):
"""Return a dict {i:j} where i is the index of the wire that has
been measured, and j is the gate where the wire is measured.
"""
ismeasured = {}
for i,g in enumerate(self._gates()):
if getattr(g,'measurement',False):
for target in g.targets:
if target in ismeasured:
if ismeasured[target] > i:
ismeasured[target] = i
else:
ismeasured[target] = i
return ismeasured
def _finish(self):
# Disable clipping to make panning work well for large circuits.
for o in self._figure.findobj():
o.set_clip_on(False)
def one_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a single qubit gate."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
self._axes.text(
x, y, t,
color='k',
ha='center',
va='center',
bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
size=self.fontsize
)
def two_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a two qubit gate. Doesn't work yet.
"""
# x = self._gate_grid[gate_idx]
# y = self._wire_grid[wire_idx]+0.5
print(self._gate_grid)
print(self._wire_grid)
# unused:
# obj = self._axes.text(
# x, y, t,
# color='k',
# ha='center',
# va='center',
# bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
# size=self.fontsize
# )
def control_line(self, gate_idx, min_wire, max_wire):
"""Draw a vertical control line."""
xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def control_point(self, gate_idx, wire_idx):
"""Draw a control point."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.control_radius
c = Circle(
(x, y),
radius*self.scale,
ec='k',
fc='k',
fill=True,
lw=self.linewidth
)
self._axes.add_patch(c)
def not_point(self, gate_idx, wire_idx):
"""Draw a NOT gates as the circle with plus in the middle."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.not_radius
c = Circle(
(x, y),
radius,
ec='k',
fc='w',
fill=False,
lw=self.linewidth
)
self._axes.add_patch(c)
l = Line2D(
(x, x), (y - radius, y + radius),
color='k',
lw=self.linewidth
)
self._axes.add_line(l)
def swap_point(self, gate_idx, wire_idx):
"""Draw a swap point as a cross."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
d = self.swap_delta
l1 = Line2D(
(x - d, x + d),
(y - d, y + d),
color='k',
lw=self.linewidth
)
l2 = Line2D(
(x - d, x + d),
(y + d, y - d),
color='k',
lw=self.linewidth
)
self._axes.add_line(l1)
self._axes.add_line(l2)
def circuit_plot(c, nqubits, **kwargs):
"""Draw the circuit diagram for the circuit with nqubits.
Parameters
==========
c : circuit
The circuit to plot. Should be a product of Gate instances.
nqubits : int
The number of qubits to include in the circuit. Must be at least
as big as the largest `min_qubits`` of the gates.
"""
return CircuitPlot(c, nqubits, **kwargs)
def render_label(label, inits={}):
"""Slightly more flexible way to render labels.
>>> from sympy.physics.quantum.circuitplot import render_label
>>> render_label('q0')
'$\\\\left|q0\\\\right\\\\rangle$'
>>> render_label('q0', {'q0':'0'})
'$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
"""
init = inits.get(label)
if init:
return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
return r'$\left|%s\right\rangle$' % label
def labeller(n, symbol='q'):
"""Autogenerate labels for wires of quantum circuits.
Parameters
==========
n : int
number of qubits in the circuit.
symbol : string
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
>>> from sympy.physics.quantum.circuitplot import labeller
>>> labeller(2)
['q_1', 'q_0']
>>> labeller(3,'j')
['j_2', 'j_1', 'j_0']
"""
return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
class Mz(OneQubitGate):
"""Mock-up of a z measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mz'
gate_name_latex='M_z'
class Mx(OneQubitGate):
"""Mock-up of an x measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mx'
gate_name_latex='M_x'
class CreateOneQubitGate(ManagedProperties):
def __new__(mcl, name, latexname=None):
if not latexname:
latexname = name
return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,),
{'gate_name': name, 'gate_name_latex': latexname})
def CreateCGate(name, latexname=None):
"""Use a lexical closure to make a controlled gate.
"""
if not latexname:
latexname = name
onequbitgate = CreateOneQubitGate(name, latexname)
def ControlledGate(ctrls,target):
return CGate(tuple(ctrls),onequbitgate(target))
return ControlledGate
|
cef0ec91f669ce669fa3dc5872999c02c79ed6d5f9d7534570b950a25c24194d | #TODO:
# -Implement Clebsch-Gordan symmetries
# -Improve simplification method
# -Implement new simpifications
"""Clebsch-Gordon Coefficients."""
from sympy import (Add, expand, Eq, Expr, Mul, Piecewise, Pow, sqrt, Sum,
symbols, sympify, Wild)
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
__all__ = [
'CG',
'Wigner3j',
'Wigner6j',
'Wigner9j',
'cg_simp'
]
#-----------------------------------------------------------------------------
# CG Coefficients
#-----------------------------------------------------------------------------
class Wigner3j(Expr):
"""Class for the Wigner-3j symbols.
Explanation
===========
Wigner 3j-symbols are coefficients determined by the coupling of
two angular momenta. When created, they are expressed as symbolic
quantities that, for numerical parameters, can be evaluated using the
``.doit()`` method [1]_.
Parameters
==========
j1, m1, j2, m2, j3, m3 : Number, Symbol
Terms determining the angular momentum of coupled angular momentum
systems.
Examples
========
Declare a Wigner-3j coefficient and calculate its value
>>> from sympy.physics.quantum.cg import Wigner3j
>>> w3j = Wigner3j(6,0,4,0,2,0)
>>> w3j
Wigner3j(6, 0, 4, 0, 2, 0)
>>> w3j.doit()
sqrt(715)/143
See Also
========
CG: Clebsch-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, j1, m1, j2, m2, j3, m3):
args = map(sympify, (j1, m1, j2, m2, j3, m3))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def m1(self):
return self.args[1]
@property
def j2(self):
return self.args[2]
@property
def m2(self):
return self.args[3]
@property
def j3(self):
return self.args[4]
@property
def m3(self):
return self.args[5]
@property
def is_symbolic(self):
return not all([arg.is_number for arg in self.args])
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.m1)),
(printer._print(self.j2), printer._print(self.m2)),
(printer._print(self.j3), printer._print(self.m3)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens())
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j3,
self.m1, self.m2, self.m3))
return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
class CG(Wigner3j):
r"""Class for Clebsch-Gordan coefficient.
Explanation
===========
Clebsch-Gordan coefficients describe the angular momentum coupling between
two systems. The coefficients give the expansion of a coupled total angular
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
coefficients are defined as [1]_:
.. math ::
C^{j_1,m_1}_{j_2,m_2,j_3,m_3} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
Parameters
==========
j1, m1, j2, m2, j3, m3 : Number, Symbol
Terms determining the angular momentum of coupled angular momentum
systems.
Examples
========
Define a Clebsch-Gordan coefficient and evaluate its value
>>> from sympy.physics.quantum.cg import CG
>>> from sympy import S
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
>>> cg
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
>>> cg.doit()
sqrt(3)/2
See Also
========
Wigner3j: Wigner-3j symbols
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
def _pretty(self, printer, *args):
bot = printer._print_seq(
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
top = printer._print_seq((self.j3, self.m3), delimiter=',')
pad = max(top.width(), bot.width())
bot = prettyForm(*bot.left(' '))
top = prettyForm(*top.left(' '))
if not pad == bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if not pad == top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
s = stringPict('C' + ' '*pad)
s = prettyForm(*s.below(bot))
s = prettyForm(*s.above(top))
return s
def _latex(self, printer, *args):
label = map(printer._print, (self.j3, self.m3, self.j1,
self.m1, self.j2, self.m2))
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
class Wigner6j(Expr):
"""Class for the Wigner-6j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j, j23):
args = map(sympify, (j1, j2, j12, j3, j, j23))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j(self):
return self.args[4]
@property
def j23(self):
return self.args[5]
@property
def is_symbolic(self):
return not all([arg.is_number for arg in self.args])
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.j3)),
(printer._print(self.j2), printer._print(self.j)),
(printer._print(self.j12), printer._print(self.j23)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12,
self.j3, self.j, self.j23))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
class Wigner9j(Expr):
"""Class for the Wigner-9j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j4(self):
return self.args[4]
@property
def j34(self):
return self.args[5]
@property
def j13(self):
return self.args[6]
@property
def j24(self):
return self.args[7]
@property
def j(self):
return self.args[8]
@property
def is_symbolic(self):
return not all([arg.is_number for arg in self.args])
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = (
(printer._print(
self.j1), printer._print(self.j3), printer._print(self.j13)),
(printer._print(
self.j2), printer._print(self.j4), printer._print(self.j24)),
(printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(3) ])
D = None
for i in range(3):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
self.j4, self.j34, self.j13, self.j24, self.j))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
def cg_simp(e):
"""Simplify and combine CG coefficients.
Explanation
===========
This function uses various symmetry and properties of sums and
products of Clebsch-Gordan coefficients to simplify statements
involving these terms [1]_.
Examples
========
Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
2*a+1
>>> from sympy.physics.quantum.cg import CG, cg_simp
>>> a = CG(1,1,0,0,1,1)
>>> b = CG(1,0,0,0,1,0)
>>> c = CG(1,-1,0,0,1,-1)
>>> cg_simp(a+b+c)
3
See Also
========
CG: Clebsh-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
if isinstance(e, Add):
return _cg_simp_add(e)
elif isinstance(e, Sum):
return _cg_simp_sum(e)
elif isinstance(e, Mul):
return Mul(*[cg_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
return Pow(cg_simp(e.base), e.exp)
else:
return e
def _cg_simp_add(e):
#TODO: Improve simplification method
"""Takes a sum of terms involving Clebsch-Gordan coefficients and
simplifies the terms.
Explanation
===========
First, we create two lists, cg_part, which is all the terms involving CG
coefficients, and other_part, which is all other terms. The cg_part list
is then passed to the simplification methods, which return the new cg_part
and any additional terms that are added to other_part
"""
cg_part = []
other_part = []
e = expand(e)
for arg in e.args:
if arg.has(CG):
if isinstance(arg, Sum):
other_part.append(_cg_simp_sum(arg))
elif isinstance(arg, Mul):
terms = 1
for term in arg.args:
if isinstance(term, Sum):
terms *= _cg_simp_sum(term)
else:
terms *= term
if terms.has(CG):
cg_part.append(terms)
else:
other_part.append(terms)
else:
cg_part.append(arg)
else:
other_part.append(arg)
cg_part, other = _check_varsh_871_1(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_871_2(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_872_9(cg_part)
other_part.append(other)
return Add(*cg_part) + Add(*other_part)
def _check_varsh_871_1(term_list):
# Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
expr = lt*CG(a, alpha, b, 0, a, alpha)
simp = (2*a + 1)*KroneckerDelta(b, 0)
sign = lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
def _check_varsh_871_2(term_list):
# Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
expr = lt*CG(a, alpha, a, -alpha, c, 0)
simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
sign = (-1)**(a - alpha)*lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
def _check_varsh_872_9(term_list):
# Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
# Case alpha==alphap, beta==betap
# For numerical alpha,beta
expr = lt*CG(a, alpha, b, beta, c, gamma)**2
simp = 1
sign = lt/abs(lt)
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# For symbolic alpha,beta
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# Case alpha!=alphap or beta!=betap
# Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
# For numerical alpha,alphap,beta,betap
expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
sign = sympify(1)
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other3 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
# For symbolic alpha,alphap,beta,betap
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other4 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
return term_list, other1 + other2 + other4
def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
""" Checks for simplifications that can be made, returning a tuple of the
simplified list of terms and any terms generated by simplification.
Parameters
==========
expr: expression
The expression with Wild terms that will be matched to the terms in
the sum
simp: expression
The expression with Wild terms that is substituted in place of the CG
terms in the case of simplification
sign: expression
The expression with Wild terms denoting the sign that is on expr that
must match
lt: expression
The expression with Wild terms that gives the leading term of the
matched expr
term_list: list
A list of all of the terms is the sum to be simplified
variables: list
A list of all the variables that appears in expr
dep_variables: list
A list of the variables that must match for all the terms in the sum,
i.e. the dependent variables
build_index_expr: expression
Expression with Wild terms giving the number of elements in cg_index
index_expr: expression
Expression with Wild terms giving the index terms have when storing
them to cg_index
"""
other_part = 0
i = 0
while i < len(term_list):
sub_1 = _check_cg(term_list[i], expr, len(variables))
if sub_1 is None:
i += 1
continue
if not sympify(build_index_expr.subs(sub_1)).is_number:
i += 1
continue
sub_dep = [(x, sub_1[x]) for x in dep_variables]
cg_index = [None]*build_index_expr.subs(sub_1)
for j in range(i, len(term_list)):
sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
if sub_2 is None:
continue
if not sympify(index_expr.subs(sub_dep).subs(sub_2)).is_number:
continue
cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
if all(i is not None for i in cg_index):
min_lt = min(*[ abs(term[2]) for term in cg_index ])
indices = [ term[0] for term in cg_index]
indices.sort()
indices.reverse()
[ term_list.pop(j) for j in indices ]
for term in cg_index:
if abs(term[2]) > min_lt:
term_list.append( (term[2] - min_lt*term[3])*term[1] )
other_part += min_lt*(sign*simp).subs(sub_1)
else:
i += 1
return term_list, other_part
def _check_cg(cg_term, expr, length, sign=None):
"""Checks whether a term matches the given expression"""
# TODO: Check for symmetries
matches = cg_term.match(expr)
if matches is None:
return
if sign is not None:
if not isinstance(sign, tuple):
raise TypeError('sign must be a tuple')
if not sign[0] == (sign[1]).subs(matches):
return
if len(matches) == length:
return matches
def _cg_simp_sum(e):
e = _check_varsh_sum_871_1(e)
e = _check_varsh_sum_871_2(e)
e = _check_varsh_sum_872_4(e)
return e
def _check_varsh_sum_871_1(e):
a = Wild('a')
alpha = symbols('alpha')
b = Wild('b')
match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
if match is not None and len(match) == 2:
return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
return e
def _check_varsh_sum_871_2(e):
a = Wild('a')
alpha = symbols('alpha')
c = Wild('c')
match = e.match(
Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
if match is not None and len(match) == 2:
return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
return e
def _check_varsh_sum_872_4(e):
alpha = symbols('alpha')
beta = symbols('beta')
a = Wild('a')
b = Wild('b')
c = Wild('c')
cp = Wild('cp')
gamma = Wild('gamma')
gammap = Wild('gammap')
cg1 = CG(a, alpha, b, beta, c, gamma)
cg2 = CG(a, alpha, b, beta, cp, gammap)
match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
if match1 is not None and len(match1) == 6:
return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
if match2 is not None and len(match2) == 4:
return 1
return e
def _cg_list(term):
if isinstance(term, CG):
return (term,), 1, 1
cg = []
coeff = 1
if not (isinstance(term, Mul) or isinstance(term, Pow)):
raise NotImplementedError('term must be CG, Add, Mul or Pow')
if isinstance(term, Pow) and sympify(term.exp).is_number:
if sympify(term.exp).is_number:
[ cg.append(term.base) for _ in range(term.exp) ]
else:
return (term,), 1, 1
if isinstance(term, Mul):
for arg in term.args:
if isinstance(arg, CG):
cg.append(arg)
else:
coeff *= arg
return cg, coeff, coeff/abs(coeff)
|
d874beffb103d9f8164ec0f27fe1b80d7e28f1afcc9d52601467b76c2213937c | """Primitive circuit operations on quantum circuits."""
from functools import reduce
from sympy import Symbol, Tuple, Mul, sympify, default_sort_key
from sympy.utilities import numbered_symbols
from sympy.physics.quantum.gate import Gate
__all__ = [
'kmp_table',
'find_subcircuit',
'replace_subcircuit',
'convert_to_symbolic_indices',
'convert_to_real_indices',
'random_reduce',
'random_insert'
]
def kmp_table(word):
"""Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
Note: This is applicable to strings or
quantum circuits represented as tuples.
"""
# Current position in subcircuit
pos = 2
# Beginning position of candidate substring that
# may reappear later in word
cnd = 0
# The 'partial match' table that helps one determine
# the next location to start substring search
table = list()
table.append(-1)
table.append(0)
while pos < len(word):
if word[pos - 1] == word[cnd]:
cnd = cnd + 1
table.append(cnd)
pos = pos + 1
elif cnd > 0:
cnd = table[cnd]
else:
table.append(0)
pos = pos + 1
return table
def find_subcircuit(circuit, subcircuit, start=0, end=0):
"""Finds the subcircuit in circuit, if it exists.
Explanation
===========
If the subcircuit exists, the index of the start of
the subcircuit in circuit is returned; otherwise,
-1 is returned. The algorithm that is implemented
is the Knuth-Morris-Pratt algorithm.
Parameters
==========
circuit : tuple, Gate or Mul
A tuple of Gates or Mul representing a quantum circuit
subcircuit : tuple, Gate or Mul
A tuple of Gates or Mul to find in circuit
start : int
The location to start looking for subcircuit.
If start is the same or past end, -1 is returned.
end : int
The last place to look for a subcircuit. If end
is less than 1 (one), then the length of circuit
is taken to be end.
Examples
========
Find the first instance of a subcircuit:
>>> from sympy.physics.quantum.circuitutils import find_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)
>>> subcircuit = Z(0)*Y(0)
>>> find_subcircuit(circuit, subcircuit)
1
Find the first instance starting at a specific position:
>>> find_subcircuit(circuit, subcircuit, start=1)
1
>>> find_subcircuit(circuit, subcircuit, start=2)
-1
>>> circuit = circuit*subcircuit
>>> find_subcircuit(circuit, subcircuit, start=2)
4
Find the subcircuit within some interval:
>>> find_subcircuit(circuit, subcircuit, start=2, end=2)
-1
"""
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
return -1
if end < 1:
end = len(circuit)
# Location in circuit
pos = start
# Location in the subcircuit
index = 0
# 'Partial match' table
table = kmp_table(subcircuit)
while (pos + index) < end:
if subcircuit[index] == circuit[pos + index]:
index = index + 1
else:
pos = pos + index - table[index]
index = table[index] if table[index] > -1 else 0
if index == len(subcircuit):
return pos
return -1
def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
"""Replaces a subcircuit with another subcircuit in circuit,
if it exists.
Explanation
===========
If multiple instances of subcircuit exists, the first instance is
replaced. The position to being searching from (if different from
0) may be optionally given. If subcircuit can't be found, circuit
is returned.
Parameters
==========
circuit : tuple, Gate or Mul
A quantum circuit.
subcircuit : tuple, Gate or Mul
The circuit to be replaced.
replace : tuple, Gate or Mul
The replacement circuit.
pos : int
The location to start search and replace
subcircuit, if it exists. This may be used
if it is known beforehand that multiple
instances exist, and it is desirable to
replace a specific instance. If a negative number
is given, pos will be defaulted to 0.
Examples
========
Find and remove the subcircuit:
>>> from sympy.physics.quantum.circuitutils import replace_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
>>> subcircuit = Z(0)*Y(0)
>>> replace_subcircuit(circuit, subcircuit)
(X(0), H(0), X(0), H(0), Y(0))
Remove the subcircuit given a starting search point:
>>> replace_subcircuit(circuit, subcircuit, pos=1)
(X(0), H(0), X(0), H(0), Y(0))
>>> replace_subcircuit(circuit, subcircuit, pos=2)
(X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
Replace the subcircuit:
>>> replacement = H(0)*Z(0)
>>> replace_subcircuit(circuit, subcircuit, replace=replacement)
(X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
"""
if pos < 0:
pos = 0
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if isinstance(replace, Mul):
replace = replace.args
elif replace is None:
replace = ()
# Look for the subcircuit starting at pos
loc = find_subcircuit(circuit, subcircuit, start=pos)
# If subcircuit was found
if loc > -1:
# Get the gates to the left of subcircuit
left = circuit[0:loc]
# Get the gates to the right of subcircuit
right = circuit[loc + len(subcircuit):len(circuit)]
# Recombine the left and right side gates into a circuit
circuit = left + replace + right
return circuit
def _sympify_qubit_map(mapping):
new_map = {}
for key in mapping:
new_map[key] = sympify(mapping[key])
return new_map
def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
"""Returns the circuit with symbolic indices and the
dictionary mapping symbolic indices to real indices.
The mapping is 1 to 1 and onto (bijective).
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects, or a Mul
start : Symbol
An optional starting symbolic index
gen : object
An optional numbered symbol generator
qubit_map : dict
An existing mapping of symbolic indices to real indices
All symbolic indices have the format 'i#', where # is
some number >= 0.
"""
if isinstance(seq, Mul):
seq = seq.args
# A numbered symbol generator
index_gen = numbered_symbols(prefix='i', start=-1)
cur_ndx = next(index_gen)
# keys are symbolic indices; values are real indices
ndx_map = {}
def create_inverse_map(symb_to_real_map):
rev_items = lambda item: tuple([item[1], item[0]])
return dict(map(rev_items, symb_to_real_map.items()))
if start is not None:
if not isinstance(start, Symbol):
msg = 'Expected Symbol for starting index, got %r.' % start
raise TypeError(msg)
cur_ndx = start
if gen is not None:
if not isinstance(gen, numbered_symbols().__class__):
msg = 'Expected a generator, got %r.' % gen
raise TypeError(msg)
index_gen = gen
if qubit_map is not None:
if not isinstance(qubit_map, dict):
msg = ('Expected dict for existing map, got ' +
'%r.' % qubit_map)
raise TypeError(msg)
ndx_map = qubit_map
ndx_map = _sympify_qubit_map(ndx_map)
# keys are real indices; keys are symbolic indices
inv_map = create_inverse_map(ndx_map)
sym_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
result = convert_to_symbolic_indices(item.args,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif isinstance(item, tuple) or isinstance(item, Tuple):
result = convert_to_symbolic_indices(item,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif item in inv_map:
sym_item = inv_map[item]
else:
cur_ndx = next(gen)
ndx_map[cur_ndx] = item
inv_map[item] = cur_ndx
sym_item = cur_ndx
if isinstance(item, Gate):
sym_item = item.__class__(*sym_item)
sym_seq = sym_seq + (sym_item,)
return sym_seq, ndx_map, cur_ndx, index_gen
def convert_to_real_indices(seq, qubit_map):
"""Returns the circuit with real indices.
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects or a Mul
qubit_map : dict
A dictionary mapping symbolic indices to real indices.
Examples
========
Change the symbolic indices to real integers:
>>> from sympy import symbols
>>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
>>> from sympy.physics.quantum.gate import X, Y, H
>>> i0, i1 = symbols('i:2')
>>> index_map = {i0 : 0, i1 : 1}
>>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
(X(0), Y(1), H(0), X(1))
"""
if isinstance(seq, Mul):
seq = seq.args
if not isinstance(qubit_map, dict):
msg = 'Expected dict for qubit_map, got %r.' % qubit_map
raise TypeError(msg)
qubit_map = _sympify_qubit_map(qubit_map)
real_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
real_item = convert_to_real_indices(item.args, qubit_map)
elif isinstance(item, tuple) or isinstance(item, Tuple):
real_item = convert_to_real_indices(item, qubit_map)
else:
real_item = qubit_map[item]
if isinstance(item, Gate):
real_item = item.__class__(*real_item)
real_seq = real_seq + (real_item,)
return real_seq
def random_reduce(circuit, gate_ids, seed=None):
"""Shorten the length of a quantum circuit.
Explanation
===========
random_reduce looks for circuit identities in circuit, randomly chooses
one to remove, and returns a shorter yet equivalent circuit. If no
identities are found, the same circuit is returned.
Parameters
==========
circuit : Gate tuple of Mul
A tuple of Gates representing a quantum circuit
gate_ids : list, GateIdentity
List of gate identities to find in circuit
seed : int or list
seed used for _randrange; to override the random selection, provide a
list of integers: the elements of gate_ids will be tested in the order
given by the list
"""
from sympy.testing.randtest import _randrange
if not gate_ids:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
ids = flatten_ids(gate_ids)
# Create the random integer generator with the seed
randrange = _randrange(seed)
# Look for an identity in the circuit
while ids:
i = randrange(len(ids))
id = ids.pop(i)
if find_subcircuit(circuit, id) != -1:
break
else:
# no identity was found
return circuit
# return circuit with the identity removed
return replace_subcircuit(circuit, id)
def random_insert(circuit, choices, seed=None):
"""Insert a circuit into another quantum circuit.
Explanation
===========
random_insert randomly chooses a location in the circuit to insert
a randomly selected circuit from amongst the given choices.
Parameters
==========
circuit : Gate tuple or Mul
A tuple or Mul of Gates representing a quantum circuit
choices : list
Set of circuit choices
seed : int or list
seed used for _randrange; to override the random selections, give
a list two integers, [i, j] where i is the circuit location where
choice[j] will be inserted.
Notes
=====
Indices for insertion should be [0, n] if n is the length of the
circuit.
"""
from sympy.testing.randtest import _randrange
if not choices:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
# get the location in the circuit and the element to insert from choices
randrange = _randrange(seed)
loc = randrange(len(circuit) + 1)
choice = choices[randrange(len(choices))]
circuit = list(circuit)
circuit[loc: loc] = choice
return tuple(circuit)
# Flatten the GateIdentity objects (with gate rules) into one single list
def flatten_ids(ids):
collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
key=default_sort_key)
ids = reduce(collapse, ids, [])
ids.sort(key=default_sort_key)
return ids
|
287185e577559233945ddcb43361f4b16729faffe77cd51f9d21045dcc78b54a | """Hilbert spaces for quantum mechanics.
Authors:
* Brian Granger
* Matt Curry
"""
from functools import reduce
from sympy import Basic, Interval, oo, sympify
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError
__all__ = [
'HilbertSpaceError',
'HilbertSpace',
'TensorProductHilbertSpace',
'TensorPowerHilbertSpace',
'DirectSumHilbertSpace',
'ComplexSpace',
'L2',
'FockSpace'
]
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpaceError(QuantumError):
pass
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpace(Basic):
"""An abstract Hilbert space for quantum mechanics.
In short, a Hilbert space is an abstract vector space that is complete
with inner products defined [1]_.
Examples
========
>>> from sympy.physics.quantum.hilbert import HilbertSpace
>>> hs = HilbertSpace()
>>> hs
H
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
"""Return the Hilbert dimension of the space."""
raise NotImplementedError('This Hilbert space has no dimension.')
def __add__(self, other):
return DirectSumHilbertSpace(self, other)
def __radd__(self, other):
return DirectSumHilbertSpace(other, self)
def __mul__(self, other):
return TensorProductHilbertSpace(self, other)
def __rmul__(self, other):
return TensorProductHilbertSpace(other, self)
def __pow__(self, other, mod=None):
if mod is not None:
raise ValueError('The third argument to __pow__ is not supported \
for Hilbert spaces.')
return TensorPowerHilbertSpace(self, other)
def __contains__(self, other):
"""Is the operator or state in this Hilbert space.
This is checked by comparing the classes of the Hilbert spaces, not
the instances. This is to allow Hilbert Spaces with symbolic
dimensions.
"""
if other.hilbert_space.__class__ == self.__class__:
return True
else:
return False
def _sympystr(self, printer, *args):
return 'H'
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER H}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{H}'
class ComplexSpace(HilbertSpace):
"""Finite dimensional Hilbert space of complex vectors.
The elements of this Hilbert space are n-dimensional complex valued
vectors with the usual inner product that takes the complex conjugate
of the vector on the right.
A classic example of this type of Hilbert space is spin-1/2, which is
``ComplexSpace(2)``. Generalizing to spin-s, the space is
``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
direct product space ``ComplexSpace(2)**N``.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.quantum.hilbert import ComplexSpace
>>> c1 = ComplexSpace(2)
>>> c1
C(2)
>>> c1.dimension
2
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> c2
C(n)
>>> c2.dimension
n
"""
def __new__(cls, dimension):
dimension = sympify(dimension)
r = cls.eval(dimension)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, dimension)
return obj
@classmethod
def eval(cls, dimension):
if len(dimension.atoms()) == 1:
if not (dimension.is_Integer and dimension > 0 or dimension is oo
or dimension.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
'be a positive integer, oo, or a Symbol: %r'
% dimension)
else:
for dim in dimension.atoms():
if not (dim.is_Integer or dim is oo or dim.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
' contain integers, oo, or a Symbol: %r'
% dim)
@property
def dimension(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "%s(%s)" % (self.__class__.__name__,
printer._print(self.dimension, *args))
def _sympystr(self, printer, *args):
return "C(%s)" % printer._print(self.dimension, *args)
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER C}'
pform_exp = printer._print(self.dimension, *args)
pform_base = prettyForm(ustr)
return pform_base**pform_exp
def _latex(self, printer, *args):
return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
class L2(HilbertSpace):
"""The Hilbert space of square integrable functions on an interval.
An L2 object takes in a single sympy Interval argument which represents
the interval its functions (vectors) are defined on.
Examples
========
>>> from sympy import Interval, oo
>>> from sympy.physics.quantum.hilbert import L2
>>> hs = L2(Interval(0,oo))
>>> hs
L2(Interval(0, oo))
>>> hs.dimension
oo
>>> hs.interval
Interval(0, oo)
"""
def __new__(cls, interval):
if not isinstance(interval, Interval):
raise TypeError('L2 interval must be an Interval instance: %r'
% interval)
obj = Basic.__new__(cls, interval)
return obj
@property
def dimension(self):
return oo
@property
def interval(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _sympystr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _pretty(self, printer, *args):
pform_exp = prettyForm('2')
pform_base = prettyForm('L')
return pform_base**pform_exp
def _latex(self, printer, *args):
interval = printer._print(self.interval, *args)
return r'{\mathcal{L}^2}\left( %s \right)' % interval
class FockSpace(HilbertSpace):
"""The Hilbert space for second quantization.
Technically, this Hilbert space is a infinite direct sum of direct
products of single particle Hilbert spaces [1]_. This is a mess, so we have
a class to represent it directly.
Examples
========
>>> from sympy.physics.quantum.hilbert import FockSpace
>>> hs = FockSpace()
>>> hs
F
>>> hs.dimension
oo
References
==========
.. [1] https://en.wikipedia.org/wiki/Fock_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
return oo
def _sympyrepr(self, printer, *args):
return "FockSpace()"
def _sympystr(self, printer, *args):
return "F"
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER F}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{F}'
class TensorProductHilbertSpace(HilbertSpace):
"""A tensor product of Hilbert spaces [1]_.
The tensor product between Hilbert spaces is represented by the
operator ``*`` Products of the same Hilbert space will be combined into
tensor powers.
A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. In addition, multiplication of
``HilbertSpace`` objects will automatically return this tensor product
object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c*f
>>> hs
C(2)*F
>>> hs.dimension
oo
>>> hs.spaces
(C(2), F)
>>> c1 = ComplexSpace(2)
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> hs = c1*c2
>>> hs
C(2)*C(n)
>>> hs.dimension
2*n
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, TensorProductHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be multiplied by \
other Hilbert spaces: %r' % arg)
#combine like arguments into direct powers
comb_args = []
prev_arg = None
for new_arg in new_args:
if prev_arg is not None:
if isinstance(new_arg, TensorPowerHilbertSpace) and \
isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg.base:
prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
elif isinstance(new_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg:
prev_arg = prev_arg**(new_arg.exp + 1)
elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg == prev_arg.base:
prev_arg = new_arg**(prev_arg.exp + 1)
elif new_arg == prev_arg:
prev_arg = new_arg**2
else:
comb_args.append(prev_arg)
prev_arg = new_arg
elif prev_arg is None:
prev_arg = new_arg
comb_args.append(prev_arg)
if recall:
return TensorProductHilbertSpace(*comb_args)
elif len(comb_args) == 1:
return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if oo in arg_list:
return oo
else:
return reduce(lambda x, y: x*y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this tensor product."""
return self.args
def _spaces_printer(self, printer, *args):
spaces_strs = []
for arg in self.args:
s = printer._print(arg, *args)
if isinstance(arg, DirectSumHilbertSpace):
s = '(%s)' % s
spaces_strs.append(s)
return spaces_strs
def _sympyrepr(self, printer, *args):
spaces_reprs = self._spaces_printer(printer, *args)
return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = self._spaces_printer(printer, *args)
return '*'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
else:
pform = prettyForm(*pform.right(' x '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\otimes '
return s
class DirectSumHilbertSpace(HilbertSpace):
"""A direct sum of Hilbert spaces [1]_.
This class uses the ``+`` operator to represent direct sums between
different Hilbert spaces.
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. Also, addition of
``HilbertSpace`` objects will automatically return a direct sum object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c+f
>>> hs
C(2)+F
>>> hs.dimension
oo
>>> list(hs.spaces)
[C(2), F]
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, DirectSumHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, HilbertSpace):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be summed with other \
Hilbert spaces: %r' % arg)
if recall:
return DirectSumHilbertSpace(*new_args)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if oo in arg_list:
return oo
else:
return reduce(lambda x, y: x + y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this direct sum."""
return self.args
def _sympyrepr(self, printer, *args):
spaces_reprs = [printer._print(arg, *args) for arg in self.args]
return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = [printer._print(arg, *args) for arg in self.args]
return '+'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
else:
pform = prettyForm(*pform.right(' + '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\oplus '
return s
class TensorPowerHilbertSpace(HilbertSpace):
"""An exponentiated Hilbert space [1]_.
Tensor powers (repeated tensor products) are represented by the
operator ``**`` Identical Hilbert spaces that are multiplied together
will be automatically combined into a single tensor power object.
Any Hilbert space, product, or sum may be raised to a tensor power. The
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
tensor power (number).
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> n = symbols('n')
>>> c = ComplexSpace(2)
>>> hs = c**n
>>> hs
C(2)**n
>>> hs.dimension
2**n
>>> c = ComplexSpace(2)
>>> c*c
C(2)**2
>>> f = FockSpace()
>>> c*f*f
C(2)*F**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
return Basic.__new__(cls, *r)
@classmethod
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp == 1:
return args[0]
#simplify hs**0 -> 1
if exp == 0:
return sympify(1)
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def dimension(self):
if self.base.dimension is oo:
return oo
else:
return self.base.dimension**self.exp
def _sympyrepr(self, printer, *args):
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
*args), printer._print(self.exp, *args))
def _sympystr(self, printer, *args):
return "%s**%s" % (printer._print(self.base, *args),
printer._print(self.exp, *args))
def _pretty(self, printer, *args):
pform_exp = printer._print(self.exp, *args)
if printer._use_unicode:
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
else:
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
pform_base = printer._print(self.base, *args)
return pform_base**pform_exp
def _latex(self, printer, *args):
base = printer._print(self.base, *args)
exp = printer._print(self.exp, *args)
return r'{%s}^{\otimes %s}' % (base, exp)
|
c65c64c8e8e4d1762fdeef6b35a4978b756a2c0e58ff14e45c2217e2a18c5770 | __all__ = ['Linearizer']
from sympy.core.backend import Matrix, eye, zeros
from sympy import Dummy
from sympy.utilities.iterables import flatten
from sympy.physics.vector import dynamicsymbols
from sympy.physics.mechanics.functions import msubs
from collections import namedtuple
from collections.abc import Iterable
class Linearizer:
"""This object holds the general model form for a dynamic system.
This model is used for computing the linearized form of the system,
while properly dealing with constraints leading to dependent
coordinates and speeds.
Attributes
==========
f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
Matrices holding the general system form.
q, u, r : Matrix
Matrices holding the generalized coordinates, speeds, and
input vectors.
q_i, u_i : Matrix
Matrices of the independent generalized coordinates and speeds.
q_d, u_d : Matrix
Matrices of the dependent generalized coordinates and speeds.
perm_mat : Matrix
Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
"""
def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u,
q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None):
"""
Parameters
==========
f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
System of equations holding the general system form.
Supply empty array or Matrix if the parameter
doesn't exist.
q : array_like
The generalized coordinates.
u : array_like
The generalized speeds
q_i, u_i : array_like, optional
The independent generalized coordinates and speeds.
q_d, u_d : array_like, optional
The dependent generalized coordinates and speeds.
r : array_like, optional
The input variables.
lams : array_like, optional
The lagrange multipliers
"""
# Generalized equation form
self.f_0 = Matrix(f_0)
self.f_1 = Matrix(f_1)
self.f_2 = Matrix(f_2)
self.f_3 = Matrix(f_3)
self.f_4 = Matrix(f_4)
self.f_c = Matrix(f_c)
self.f_v = Matrix(f_v)
self.f_a = Matrix(f_a)
# Generalized equation variables
self.q = Matrix(q)
self.u = Matrix(u)
none_handler = lambda x: Matrix(x) if x else Matrix()
self.q_i = none_handler(q_i)
self.q_d = none_handler(q_d)
self.u_i = none_handler(u_i)
self.u_d = none_handler(u_d)
self.r = none_handler(r)
self.lams = none_handler(lams)
# Derivatives of generalized equation variables
self._qd = self.q.diff(dynamicsymbols._t)
self._ud = self.u.diff(dynamicsymbols._t)
# If the user doesn't actually use generalized variables, and the
# qd and u vectors have any intersecting variables, this can cause
# problems. We'll fix this with some hackery, and Dummy variables
dup_vars = set(self._qd).intersection(self.u)
self._qd_dup = Matrix([var if var not in dup_vars else Dummy()
for var in self._qd])
# Derive dimesion terms
l = len(self.f_c)
m = len(self.f_v)
n = len(self.q)
o = len(self.u)
s = len(self.r)
k = len(self.lams)
dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
self._dims = dims(l, m, n, o, s, k)
self._setup_done = False
def _setup(self):
# Calculations here only need to be run once. They are moved out of
# the __init__ method to increase the speed of Linearizer creation.
self._form_permutation_matrices()
self._form_block_matrices()
self._form_coefficient_matrices()
self._setup_done = True
def _form_permutation_matrices(self):
"""Form the permutation matrices Pq and Pu."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Compute permutation matrices
if n != 0:
self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
if l > 0:
self._Pqi = self._Pq[:, :-l]
self._Pqd = self._Pq[:, -l:]
else:
self._Pqi = self._Pq
self._Pqd = Matrix()
if o != 0:
self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
if m > 0:
self._Pui = self._Pu[:, :-m]
self._Pud = self._Pu[:, -m:]
else:
self._Pui = self._Pu
self._Pud = Matrix()
# Compute combination permutation matrix for computing A and B
P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
if P_col1:
if P_col2:
self.perm_mat = P_col1.row_join(P_col2)
else:
self.perm_mat = P_col1
else:
self.perm_mat = P_col2
def _form_coefficient_matrices(self):
"""Form the coefficient matrices C_0, C_1, and C_2."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Build up the coefficient matrices C_0, C_1, and C_2
# If there are configuration constraints (l > 0), form C_0 as normal.
# If not, C_0 is I_(nxn). Note that this works even if n=0
if l > 0:
f_c_jac_q = self.f_c.jacobian(self.q)
self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q *
self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi
else:
self._C_0 = eye(n)
# If there are motion constraints (m > 0), form C_1 and C_2 as normal.
# If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
# o = 0.
if m > 0:
f_v_jac_u = self.f_v.jacobian(self.u)
temp = f_v_jac_u * self._Pud
if n != 0:
f_v_jac_q = self.f_v.jacobian(self.q)
self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q)
else:
self._C_1 = zeros(o, n)
self._C_2 = (eye(o) - self._Pud *
temp.LUsolve(f_v_jac_u)) * self._Pui
else:
self._C_1 = zeros(o, n)
self._C_2 = eye(o)
def _form_block_matrices(self):
"""Form the block matrices for composing M, A, and B."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Block Matrix Definitions. These are only defined if under certain
# conditions. If undefined, an empty matrix is used instead
if n != 0:
self._M_qq = self.f_0.jacobian(self._qd)
self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
else:
self._M_qq = Matrix()
self._A_qq = Matrix()
if n != 0 and m != 0:
self._M_uqc = self.f_a.jacobian(self._qd_dup)
self._A_uqc = -self.f_a.jacobian(self.q)
else:
self._M_uqc = Matrix()
self._A_uqc = Matrix()
if n != 0 and o - m + k != 0:
self._M_uqd = self.f_3.jacobian(self._qd_dup)
self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
else:
self._M_uqd = Matrix()
self._A_uqd = Matrix()
if o != 0 and m != 0:
self._M_uuc = self.f_a.jacobian(self._ud)
self._A_uuc = -self.f_a.jacobian(self.u)
else:
self._M_uuc = Matrix()
self._A_uuc = Matrix()
if o != 0 and o - m + k != 0:
self._M_uud = self.f_2.jacobian(self._ud)
self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
else:
self._M_uud = Matrix()
self._A_uud = Matrix()
if o != 0 and n != 0:
self._A_qu = -self.f_1.jacobian(self.u)
else:
self._A_qu = Matrix()
if k != 0 and o - m + k != 0:
self._M_uld = self.f_4.jacobian(self.lams)
else:
self._M_uld = Matrix()
if s != 0 and o - m + k != 0:
self._B_u = -self.f_3.jacobian(self.r)
else:
self._B_u = Matrix()
def linearize(self, op_point=None, A_and_B=False, simplify=False):
"""Linearize the system about the operating point. Note that
q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
These may be either symbolic or numeric.
Parameters
==========
op_point : dict or iterable of dicts, optional
Dictionary or iterable of dictionaries containing the operating
point conditions. These will be substituted in to the linearized
system before the linearization is complete. Leave blank if you
want a completely symbolic form. Note that any reduction in
symbols (whether substituted for numbers or expressions with a
common parameter) will result in faster runtime.
A_and_B : bool, optional
If A_and_B=False (default), (M, A, B) is returned for forming
[M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True,
(A, B) is returned for forming dx = [A]x + [B]r, where
x = [q_ind, u_ind]^T.
simplify : bool, optional
Determines if returned values are simplified before return.
For large expressions this may be time consuming. Default is False.
Potential Issues
================
Note that the process of solving with A_and_B=True is
computationally intensive if there are many symbolic parameters.
For this reason, it may be more desirable to use the default
A_and_B=False, returning M, A, and B. More values may then be
substituted in to these matrices later on. The state space form can
then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where
P = Linearizer.perm_mat.
"""
# Run the setup if needed:
if not self._setup_done:
self._setup()
# Compose dict of operating conditions
if isinstance(op_point, dict):
op_point_dict = op_point
elif isinstance(op_point, Iterable):
op_point_dict = {}
for op in op_point:
op_point_dict.update(op)
else:
op_point_dict = {}
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Rename terms to shorten expressions
M_qq = self._M_qq
M_uqc = self._M_uqc
M_uqd = self._M_uqd
M_uuc = self._M_uuc
M_uud = self._M_uud
M_uld = self._M_uld
A_qq = self._A_qq
A_uqc = self._A_uqc
A_uqd = self._A_uqd
A_qu = self._A_qu
A_uuc = self._A_uuc
A_uud = self._A_uud
B_u = self._B_u
C_0 = self._C_0
C_1 = self._C_1
C_2 = self._C_2
# Build up Mass Matrix
# |M_qq 0_nxo 0_nxk|
# M = |M_uqc M_uuc 0_mxk|
# |M_uqd M_uud M_uld|
if o != 0:
col2 = Matrix([zeros(n, o), M_uuc, M_uud])
if k != 0:
col3 = Matrix([zeros(n + m, k), M_uld])
if n != 0:
col1 = Matrix([M_qq, M_uqc, M_uqd])
if o != 0 and k != 0:
M = col1.row_join(col2).row_join(col3)
elif o != 0:
M = col1.row_join(col2)
else:
M = col1
elif k != 0:
M = col2.row_join(col3)
else:
M = col2
M_eq = msubs(M, op_point_dict)
# Build up state coefficient matrix A
# |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
# A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
# |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
# Col 1 is only defined if n != 0
if n != 0:
r1c1 = A_qq
if o != 0:
r1c1 += (A_qu * C_1)
r1c1 = r1c1 * C_0
if m != 0:
r2c1 = A_uqc
if o != 0:
r2c1 += (A_uuc * C_1)
r2c1 = r2c1 * C_0
else:
r2c1 = Matrix()
if o - m + k != 0:
r3c1 = A_uqd
if o != 0:
r3c1 += (A_uud * C_1)
r3c1 = r3c1 * C_0
else:
r3c1 = Matrix()
col1 = Matrix([r1c1, r2c1, r3c1])
else:
col1 = Matrix()
# Col 2 is only defined if o != 0
if o != 0:
if n != 0:
r1c2 = A_qu * C_2
else:
r1c2 = Matrix()
if m != 0:
r2c2 = A_uuc * C_2
else:
r2c2 = Matrix()
if o - m + k != 0:
r3c2 = A_uud * C_2
else:
r3c2 = Matrix()
col2 = Matrix([r1c2, r2c2, r3c2])
else:
col2 = Matrix()
if col1:
if col2:
Amat = col1.row_join(col2)
else:
Amat = col1
else:
Amat = col2
Amat_eq = msubs(Amat, op_point_dict)
# Build up the B matrix if there are forcing variables
# |0_(n + m)xs|
# B = |B_u |
if s != 0 and o - m + k != 0:
Bmat = zeros(n + m, s).col_join(B_u)
Bmat_eq = msubs(Bmat, op_point_dict)
else:
Bmat_eq = Matrix()
# kwarg A_and_B indicates to return A, B for forming the equation
# dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
if A_and_B:
A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq)
if Bmat_eq:
B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq)
else:
# Bmat = Matrix([]), so no need to sub
B_cont = Bmat_eq
if simplify:
A_cont.simplify()
B_cont.simplify()
return A_cont, B_cont
# Otherwise return M, A, B for forming the equation
# [M]dx = [A]x + [B]r, where x = [q, u]^T
else:
if simplify:
M_eq.simplify()
Amat_eq.simplify()
Bmat_eq.simplify()
return M_eq, Amat_eq, Bmat_eq
def permutation_matrix(orig_vec, per_vec):
"""Compute the permutation matrix to change order of
orig_vec into order of per_vec.
Parameters
==========
orig_vec : array_like
Symbols in original ordering.
per_vec : array_like
Symbols in new ordering.
Returns
=======
p_matrix : Matrix
Permutation matrix such that orig_vec == (p_matrix * per_vec).
"""
if not isinstance(orig_vec, (list, tuple)):
orig_vec = flatten(orig_vec)
if not isinstance(per_vec, (list, tuple)):
per_vec = flatten(per_vec)
if set(orig_vec) != set(per_vec):
raise ValueError("orig_vec and per_vec must be the same length, " +
"and contain the same symbols.")
ind_list = [orig_vec.index(i) for i in per_vec]
p_matrix = zeros(len(orig_vec))
for i, j in enumerate(ind_list):
p_matrix[i, j] = 1
return p_matrix
|
2fd7084c051685c58686a87114e8a135821b06d29e864e1779baee3bbfd9a1ae | """
Definition of physical dimensions.
Unit systems will be constructed on top of these dimensions.
Most of the examples in the doc use MKS system and are presented from the
computer point of view: from a human point, adding length to time is not legal
in MKS but it is in natural system; for a computer in natural system there is
no time dimension (but a velocity dimension instead) - in the basis - so the
question of adding time to length has no meaning.
"""
from typing import Dict as tDict
import collections
from functools import reduce
from sympy import (Integer, Matrix, S, Symbol, sympify, Basic, Tuple, Dict,
default_sort_key)
from sympy.core.expr import Expr
from sympy.core.power import Pow
from sympy.utilities.exceptions import SymPyDeprecationWarning
class _QuantityMapper:
_quantity_scale_factors_global = {} # type: tDict[Expr, Expr]
_quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr]
_quantity_dimension_global = {} # type: tDict[Expr, Expr]
def __init__(self, *args, **kwargs):
self._quantity_dimension_map = {}
self._quantity_scale_factors = {}
def set_quantity_dimension(self, unit, dimension):
from sympy.physics.units import Quantity
dimension = sympify(dimension)
if not isinstance(dimension, Dimension):
if dimension == 1:
dimension = Dimension(1)
else:
raise ValueError("expected dimension or 1")
elif isinstance(dimension, Quantity):
dimension = self.get_quantity_dimension(dimension)
self._quantity_dimension_map[unit] = dimension
def set_quantity_scale_factor(self, unit, scale_factor):
from sympy.physics.units import Quantity
from sympy.physics.units.prefixes import Prefix
scale_factor = sympify(scale_factor)
# replace all prefixes by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Prefix),
lambda x: x.scale_factor
)
# replace all quantities by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Quantity),
lambda x: self.get_quantity_scale_factor(x)
)
self._quantity_scale_factors[unit] = scale_factor
def get_quantity_dimension(self, unit):
from sympy.physics.units import Quantity
# First look-up the local dimension map, then the global one:
if unit in self._quantity_dimension_map:
return self._quantity_dimension_map[unit]
if unit in self._quantity_dimension_global:
return self._quantity_dimension_global[unit]
if unit in self._quantity_dimensional_equivalence_map_global:
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
if isinstance(dep_unit, Quantity):
return self.get_quantity_dimension(dep_unit)
else:
return Dimension(self.get_dimensional_expr(dep_unit))
if isinstance(unit, Quantity):
return Dimension(unit.name)
else:
return Dimension(1)
def get_quantity_scale_factor(self, unit):
if unit in self._quantity_scale_factors:
return self._quantity_scale_factors[unit]
if unit in self._quantity_scale_factors_global:
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
return mul_factor*self.get_quantity_scale_factor(other_unit)
return S.One
class Dimension(Expr):
"""
This class represent the dimension of a physical quantities.
The ``Dimension`` constructor takes as parameters a name and an optional
symbol.
For example, in classical mechanics we know that time is different from
temperature and dimensions make this difference (but they do not provide
any measure of these quantites.
>>> from sympy.physics.units import Dimension
>>> length = Dimension('length')
>>> length
Dimension(length)
>>> time = Dimension('time')
>>> time
Dimension(time)
Dimensions can be composed using multiplication, division and
exponentiation (by a number) to give new dimensions. Addition and
subtraction is defined only when the two objects are the same dimension.
>>> velocity = length / time
>>> velocity
Dimension(length/time)
It is possible to use a dimension system object to get the dimensionsal
dependencies of a dimension, for example the dimension system used by the
SI units convention can be used:
>>> from sympy.physics.units.systems.si import dimsys_SI
>>> dimsys_SI.get_dimensional_dependencies(velocity)
{'length': 1, 'time': -1}
>>> length + length
Dimension(length)
>>> l2 = length**2
>>> l2
Dimension(length**2)
>>> dimsys_SI.get_dimensional_dependencies(l2)
{'length': 2}
"""
_op_priority = 13.0
# XXX: This doesn't seem to be used anywhere...
_dimensional_dependencies = dict() # type: ignore
is_commutative = True
is_number = False
# make sqrt(M**2) --> M
is_positive = True
is_real = True
def __new__(cls, name, symbol=None):
if isinstance(name, str):
name = Symbol(name)
else:
name = sympify(name)
if not isinstance(name, Expr):
raise TypeError("Dimension name needs to be a valid math expression")
if isinstance(symbol, str):
symbol = Symbol(symbol)
elif symbol is not None:
assert isinstance(symbol, Symbol)
if symbol is not None:
obj = Expr.__new__(cls, name, symbol)
else:
obj = Expr.__new__(cls, name)
obj._name = name
obj._symbol = symbol
return obj
@property
def name(self):
return self._name
@property
def symbol(self):
return self._symbol
def __hash__(self):
return Expr.__hash__(self)
def __eq__(self, other):
if isinstance(other, Dimension):
return self.name == other.name
return False
def __str__(self):
"""
Display the string representation of the dimension.
"""
if self.symbol is None:
return "Dimension(%s)" % (self.name)
else:
return "Dimension(%s, %s)" % (self.name, self.symbol)
def __repr__(self):
return self.__str__()
def __neg__(self):
return self
def __add__(self, other):
from sympy.physics.units.quantities import Quantity
other = sympify(other)
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension) and self == other:
return self
return super().__add__(other)
return self
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __rsub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __pow__(self, other):
return self._eval_power(other)
def _eval_power(self, other):
other = sympify(other)
return Dimension(self.name**other)
def __mul__(self, other):
from sympy.physics.units.quantities import Quantity
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension):
return Dimension(self.name*other.name)
if not other.free_symbols: # other.is_number cannot be used
return self
return super().__mul__(other)
return self
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return self*Pow(other, -1)
def __rtruediv__(self, other):
return other * pow(self, -1)
@classmethod
def _from_dimensional_dependencies(cls, dependencies):
return reduce(lambda x, y: x * y, (
Dimension(d)**e for d, e in dependencies.items()
))
@classmethod
def _get_dimensional_dependencies_for_name(cls, name):
from sympy.physics.units.systems.si import dimsys_default
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="do not call from `Dimension` objects.",
useinstead="DimensionSystem"
).warn()
return dimsys_default.get_dimensional_dependencies(name)
@property
def is_dimensionless(self):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if self.name == 1:
return True
from sympy.physics.units.systems.si import dimsys_default
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="wrong class",
).warn()
dimensional_dependencies=dimsys_default
return dimensional_dependencies.get_dimensional_dependencies(self) == {}
def has_integer_powers(self, dim_sys):
"""
Check if the dimension object has only integer powers.
All the dimension powers should be integers, but rational powers may
appear in intermediate steps. This method may be used to check that the
final result is well-defined.
"""
for dpow in dim_sys.get_dimensional_dependencies(self).values():
if not isinstance(dpow, (int, Integer)):
return False
return True
# Create dimensions according the the base units in MKSA.
# For other unit systems, they can be derived by transforming the base
# dimensional dependency dictionary.
class DimensionSystem(Basic, _QuantityMapper):
r"""
DimensionSystem represents a coherent set of dimensions.
The constructor takes three parameters:
- base dimensions;
- derived dimensions: these are defined in terms of the base dimensions
(for example velocity is defined from the division of length by time);
- dependency of dimensions: how the derived dimensions depend
on the base dimensions.
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
may be omitted.
"""
def __new__(cls, base_dims, derived_dims=[], dimensional_dependencies={}, name=None, descr=None):
dimensional_dependencies = dict(dimensional_dependencies)
if (name is not None) or (descr is not None):
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
useinstead="do not define a `name` or `descr`",
).warn()
def parse_dim(dim):
if isinstance(dim, str):
dim = Dimension(Symbol(dim))
elif isinstance(dim, Dimension):
pass
elif isinstance(dim, Symbol):
dim = Dimension(dim)
else:
raise TypeError("%s wrong type" % dim)
return dim
base_dims = [parse_dim(i) for i in base_dims]
derived_dims = [parse_dim(i) for i in derived_dims]
for dim in base_dims:
dim = dim.name
if (dim in dimensional_dependencies
and (len(dimensional_dependencies[dim]) != 1 or
dimensional_dependencies[dim].get(dim, None) != 1)):
raise IndexError("Repeated value in base dimensions")
dimensional_dependencies[dim] = Dict({dim: 1})
def parse_dim_name(dim):
if isinstance(dim, Dimension):
return dim.name
elif isinstance(dim, str):
return Symbol(dim)
elif isinstance(dim, Symbol):
return dim
else:
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
for dim in dimensional_dependencies.keys():
dim = parse_dim(dim)
if (dim not in derived_dims) and (dim not in base_dims):
derived_dims.append(dim)
def parse_dict(d):
return Dict({parse_dim_name(i): j for i, j in d.items()})
# Make sure everything is a SymPy type:
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
dimensional_dependencies.items()}
for dim in derived_dims:
if dim in base_dims:
raise ValueError("Dimension %s both in base and derived" % dim)
if dim.name not in dimensional_dependencies:
# TODO: should this raise a warning?
dimensional_dependencies[dim.name] = Dict({dim.name: 1})
base_dims.sort(key=default_sort_key)
derived_dims.sort(key=default_sort_key)
base_dims = Tuple(*base_dims)
derived_dims = Tuple(*derived_dims)
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
return obj
@property
def base_dims(self):
return self.args[0]
@property
def derived_dims(self):
return self.args[1]
@property
def dimensional_dependencies(self):
return self.args[2]
def _get_dimensional_dependencies_for_name(self, name):
if isinstance(name, Dimension):
name = name.name
if isinstance(name, str):
name = Symbol(name)
if name.is_Symbol:
# Dimensions not included in the dependencies are considered
# as base dimensions:
return dict(self.dimensional_dependencies.get(name, {name: 1}))
if name.is_Number:
return {}
get_for_name = self._get_dimensional_dependencies_for_name
if name.is_Mul:
ret = collections.defaultdict(int)
dicts = [get_for_name(i) for i in name.args]
for d in dicts:
for k, v in d.items():
ret[k] += v
return {k: v for (k, v) in ret.items() if v != 0}
if name.is_Add:
dicts = [get_for_name(i) for i in name.args]
if all([d == dicts[0] for d in dicts[1:]]):
return dicts[0]
raise TypeError("Only equivalent dimensions can be added or subtracted.")
if name.is_Pow:
dim = get_for_name(name.base)
return {k: v*name.exp for (k, v) in dim.items()}
if name.is_Function:
args = (Dimension._from_dimensional_dependencies(
get_for_name(arg)) for arg in name.args)
result = name.func(*args)
if isinstance(result, Dimension):
return self.get_dimensional_dependencies(result)
elif result.func == name.func:
return {}
else:
return get_for_name(result)
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(name)))
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
dimdep = self._get_dimensional_dependencies_for_name(name)
if mark_dimensionless and dimdep == {}:
return {'dimensionless': 1}
return {str(i): j for i, j in dimdep.items()}
def equivalent_dims(self, dim1, dim2):
deps1 = self.get_dimensional_dependencies(dim1)
deps2 = self.get_dimensional_dependencies(dim2)
return deps1 == deps2
def extend(self, new_base_dims, new_derived_dims=[], new_dim_deps={}, name=None, description=None):
if (name is not None) or (description is not None):
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="name and descriptions of DimensionSystem",
useinstead="do not specify `name` or `description`",
).warn()
deps = dict(self.dimensional_dependencies)
deps.update(new_dim_deps)
new_dim_sys = DimensionSystem(
tuple(self.base_dims) + tuple(new_base_dims),
tuple(self.derived_dims) + tuple(new_derived_dims),
deps
)
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
return new_dim_sys
@staticmethod
def sort_dims(dims):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Sort dimensions given in argument using their str function.
This function will ensure that we get always the same tuple for a given
set of dimensions.
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="sort_dims",
useinstead="sorted(..., key=default_sort_key)",
).warn()
return tuple(sorted(dims, key=str))
def __getitem__(self, key):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Shortcut to the get_dim method, using key access.
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="the get [ ] operator",
useinstead="the dimension definition",
).warn()
d = self.get_dim(key)
#TODO: really want to raise an error?
if d is None:
raise KeyError(key)
return d
def __call__(self, unit):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Wrapper to the method print_dim_base
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="call DimensionSystem",
useinstead="the dimension definition",
).warn()
return self.print_dim_base(unit)
def is_dimensionless(self, dimension):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if dimension.name == 1:
return True
return self.get_dimensional_dependencies(dimension) == {}
@property
def list_can_dims(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
List all canonical dimension names.
"""
dimset = set()
for i in self.base_dims:
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
return tuple(sorted(dimset, key=str))
@property
def inv_can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Compute the inverse transformation matrix from the base to the
canonical dimension basis.
It corresponds to the matrix where columns are the vector of base
dimensions in canonical basis.
This matrix will almost never be used because dimensions are always
defined with respect to the canonical basis, so no work has to be done
to get them in this basis. Nonetheless if this matrix is not square
(or not invertible) it means that we have chosen a bad basis.
"""
matrix = reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in self.base_dims])
return matrix
@property
def can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Return the canonical transformation matrix from the canonical to the
base dimension basis.
It is the inverse of the matrix computed with inv_can_transf_matrix().
"""
#TODO: the inversion will fail if the system is inconsistent, for
# example if the matrix is not a square
return reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
).inv()
def dim_can_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Dimensional representation in terms of the canonical base dimensions.
"""
vec = []
for d in self.list_can_dims:
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
return Matrix(vec)
def dim_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Vector representation in terms of the base dimensions.
"""
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
def print_dim_base(self, dim):
"""
Give the string expression of a dimension in term of the basis symbols.
"""
dims = self.dim_vector(dim)
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
res = S.One
for (s, p) in zip(symbols, dims):
res *= s**p
return res
@property
def dim(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Give the dimension of the system.
That is return the number of dimensions forming the basis.
"""
return len(self.base_dims)
@property
def is_consistent(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Check if the system is well defined.
"""
# not enough or too many base dimensions compared to independent
# dimensions
# in vector language: the set of vectors do not form a basis
return self.inv_can_transf_matrix.is_square
|
c8d51bf72851c9e020113aadb6830b71145b386f44dbbd3a4dfd574e86319d04 | """
Several methods to simplify expressions involving unit objects.
"""
from functools import reduce
from collections.abc import Iterable
from sympy import Add, Mul, Pow, Tuple, sympify
from sympy.core.compatibility import ordered
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.physics.units.dimensions import Dimension
from sympy.physics.units.prefixes import Prefix
from sympy.physics.units.quantities import Quantity
from sympy.utilities.iterables import sift
def _get_conversion_matrix_for_expr(expr, target_units, unit_system):
from sympy import Matrix
dimension_system = unit_system.get_dimension_system()
expr_dim = Dimension(unit_system.get_dimensional_expr(expr))
dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True)
target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units]
canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)]
canon_expr_units = {i for i in dim_dependencies}
if not canon_expr_units.issubset(set(canon_dim_units)):
return None
seen = set()
canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))]
camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])
exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])
try:
res_exponents = camat.solve(exprmat)
except NonInvertibleMatrixError:
return None
return res_exponents
def convert_to(expr, target_units, unit_system="SI"):
"""
Convert ``expr`` to the same expression with all of its units and quantities
represented as factors of ``target_units``, whenever the dimension is compatible.
``target_units`` may be a single unit/quantity, or a collection of
units/quantities.
Examples
========
>>> from sympy.physics.units import speed_of_light, meter, gram, second, day
>>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant
>>> from sympy.physics.units import kilometer, centimeter
>>> from sympy.physics.units import gravitational_constant, hbar
>>> from sympy.physics.units import convert_to
>>> convert_to(mile, kilometer)
25146*kilometer/15625
>>> convert_to(mile, kilometer).n()
1.609344*kilometer
>>> convert_to(speed_of_light, meter/second)
299792458*meter/second
>>> convert_to(day, second)
86400*second
>>> 3*newton
3*newton
>>> convert_to(3*newton, kilogram*meter/second**2)
3*kilogram*meter/second**2
>>> convert_to(atomic_mass_constant, gram)
1.660539060e-24*gram
Conversion to multiple units:
>>> convert_to(speed_of_light, [meter, second])
299792458*meter/second
>>> convert_to(3*newton, [centimeter, gram, second])
300000*centimeter*gram/second**2
Conversion to Planck units:
>>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()
7.62963085040767e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5
"""
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
if not isinstance(target_units, (Iterable, Tuple)):
target_units = [target_units]
if isinstance(expr, Add):
return Add.fromiter(convert_to(i, target_units, unit_system) for i in expr.args)
expr = sympify(expr)
if not isinstance(expr, Quantity) and expr.has(Quantity):
expr = expr.replace(lambda x: isinstance(x, Quantity), lambda x: x.convert_to(target_units, unit_system))
def get_total_scale_factor(expr):
if isinstance(expr, Mul):
return reduce(lambda x, y: x * y, [get_total_scale_factor(i) for i in expr.args])
elif isinstance(expr, Pow):
return get_total_scale_factor(expr.base) ** expr.exp
elif isinstance(expr, Quantity):
return unit_system.get_quantity_scale_factor(expr)
return expr
depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system)
if depmat is None:
return expr
expr_scale_factor = get_total_scale_factor(expr)
return expr_scale_factor * Mul.fromiter((1/get_total_scale_factor(u) * u) ** p for u, p in zip(target_units, depmat))
def quantity_simplify(expr):
"""Return an equivalent expression in which prefixes are replaced
with numerical values and all units of a given dimension are the
unified in a canonical manner.
Examples
========
>>> from sympy.physics.units.util import quantity_simplify
>>> from sympy.physics.units.prefixes import kilo
>>> from sympy.physics.units import foot, inch
>>> quantity_simplify(kilo*foot*inch)
250*foot**2/3
>>> quantity_simplify(foot - 6*inch)
foot/2
"""
if expr.is_Atom or not expr.has(Prefix, Quantity):
return expr
# replace all prefixes with numerical values
p = expr.atoms(Prefix)
expr = expr.xreplace({p: p.scale_factor for p in p})
# replace all quantities of given dimension with a canonical
# quantity, chosen from those in the expression
d = sift(expr.atoms(Quantity), lambda i: i.dimension)
for k in d:
if len(d[k]) == 1:
continue
v = list(ordered(d[k]))
ref = v[0]/v[0].scale_factor
expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]})
return expr
def check_dimensions(expr, unit_system="SI"):
"""Return expr if units in addends have the same
base dimensions, else raise a ValueError."""
# the case of adding a number to a dimensional quantity
# is ignored for the sake of SymPy core routines, so this
# function will raise an error now if such an addend is
# found.
# Also, when doing substitutions, multiplicative constants
# might be introduced, so remove those now
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
def addDict(dict1, dict2):
"""Merge dictionaries by adding values of common keys and
removing keys with value of 0."""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = value + dict1[key]
return {key:val for key, val in dict3.items() if val != 0}
adds = expr.atoms(Add)
DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies
for a in adds:
deset = set()
for ai in a.args:
if ai.is_number:
deset.add(())
continue
dims = []
skip = False
dimdict = {}
for i in Mul.make_args(ai):
if i.has(Quantity):
i = Dimension(unit_system.get_dimensional_expr(i))
if i.has(Dimension):
dimdict = addDict(dimdict, DIM_OF(i))
elif i.free_symbols:
skip = True
break
dims.extend(dimdict.items())
if not skip:
deset.add(tuple(sorted(dims)))
if len(deset) > 1:
raise ValueError(
"addends have incompatible dimensions: {}".format(deset))
# clear multiplicative constants on Dimensions which may be
# left after substitution
reps = {}
for m in expr.atoms(Mul):
if any(isinstance(i, Dimension) for i in m.args):
reps[m] = m.func(*[
i for i in m.args if not i.is_number])
return expr.xreplace(reps)
|
37d3603d40caf309b4ac1bd61deafedd985ed423872fa80f8ff390bb675b459d | from sympy import Derivative
from sympy.core.function import UndefinedFunction, AppliedUndef
from sympy.core.symbol import Symbol
from sympy.interactive.printing import init_printing
from sympy.printing.latex import LatexPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.pretty_symbology import center_accent
from sympy.printing.str import StrPrinter
from sympy.printing.precedence import PRECEDENCE
__all__ = ['vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex',
'init_vprinting']
class VectorStrPrinter(StrPrinter):
"""String Printer for vector expressions. """
def _print_Derivative(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
if (bool(sum([i == t for i in e.variables])) &
isinstance(type(e.args[0]), UndefinedFunction)):
ol = str(e.args[0].func)
for i, v in enumerate(e.variables):
ol += dynamicsymbols._str
return ol
else:
return StrPrinter().doprint(e)
def _print_Function(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
if isinstance(type(e), UndefinedFunction):
return StrPrinter().doprint(e).replace("(%s)" % t, '')
return e.func.__name__ + "(%s)" % self.stringify(e.args, ", ")
class VectorStrReprPrinter(VectorStrPrinter):
"""String repr printer for vector expressions."""
def _print_str(self, s):
return repr(s)
class VectorLatexPrinter(LatexPrinter):
"""Latex Printer for vector expressions. """
def _print_Function(self, expr, exp=None):
from sympy.physics.vector.functions import dynamicsymbols
func = expr.func.__name__
t = dynamicsymbols._t
if hasattr(self, '_print_' + func) and \
not isinstance(type(expr), UndefinedFunction):
return getattr(self, '_print_' + func)(expr, exp)
elif isinstance(type(expr), UndefinedFunction) and (expr.args == (t,)):
# treat this function like a symbol
expr = Symbol(func)
if exp is not None:
# copied from LatexPrinter._helper_print_standard_power, which
# we can't call because we only have exp as a string.
base = self.parenthesize(expr, PRECEDENCE['Pow'])
base = self.parenthesize_super(base)
return r"%s^{%s}" % (base, exp)
else:
return super()._print(expr)
else:
return super()._print_Function(expr, exp)
def _print_Derivative(self, der_expr):
from sympy.physics.vector.functions import dynamicsymbols
# make sure it is in the right form
der_expr = der_expr.doit()
if not isinstance(der_expr, Derivative):
return r"\left(%s\right)" % self.doprint(der_expr)
# check if expr is a dynamicsymbol
t = dynamicsymbols._t
expr = der_expr.expr
red = expr.atoms(AppliedUndef)
syms = der_expr.variables
test1 = not all([True for i in red if i.free_symbols == {t}])
test2 = not all([(t == i) for i in syms])
if test1 or test2:
return super()._print_Derivative(der_expr)
# done checking
dots = len(syms)
base = self._print_Function(expr)
base_split = base.split('_', 1)
base = base_split[0]
if dots == 1:
base = r"\dot{%s}" % base
elif dots == 2:
base = r"\ddot{%s}" % base
elif dots == 3:
base = r"\dddot{%s}" % base
elif dots == 4:
base = r"\ddddot{%s}" % base
else: # Fallback to standard printing
return super()._print_Derivative(der_expr)
if len(base_split) != 1:
base += '_' + base_split[1]
return base
class VectorPrettyPrinter(PrettyPrinter):
"""Pretty Printer for vectorialexpressions. """
def _print_Derivative(self, deriv):
from sympy.physics.vector.functions import dynamicsymbols
# XXX use U('PARTIAL DIFFERENTIAL') here ?
t = dynamicsymbols._t
dot_i = 0
syms = list(reversed(deriv.variables))
while len(syms) > 0:
if syms[-1] == t:
syms.pop()
dot_i += 1
else:
return super()._print_Derivative(deriv)
if not (isinstance(type(deriv.expr), UndefinedFunction)
and (deriv.expr.args == (t,))):
return super()._print_Derivative(deriv)
else:
pform = self._print_Function(deriv.expr)
# the following condition would happen with some sort of non-standard
# dynamic symbol I guess, so we'll just print the SymPy way
if len(pform.picture) > 1:
return super()._print_Derivative(deriv)
# There are only special symbols up to fourth-order derivatives
if dot_i >= 5:
return super()._print_Derivative(deriv)
# Deal with special symbols
dots = {0 : "",
1 : "\N{COMBINING DOT ABOVE}",
2 : "\N{COMBINING DIAERESIS}",
3 : "\N{COMBINING THREE DOTS ABOVE}",
4 : "\N{COMBINING FOUR DOTS ABOVE}"}
d = pform.__dict__
#if unicode is false then calculate number of apostrophes needed and add to output
if not self._use_unicode:
apostrophes = ""
for i in range(0, dot_i):
apostrophes += "'"
d['picture'][0] += apostrophes + "(t)"
else:
d['picture'] = [center_accent(d['picture'][0], dots[dot_i])]
return pform
def _print_Function(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
# XXX works only for applied functions
func = e.func
args = e.args
func_name = func.__name__
pform = self._print_Symbol(Symbol(func_name))
# If this function is an Undefined function of t, it is probably a
# dynamic symbol, so we'll skip the (t). The rest of the code is
# identical to the normal PrettyPrinter code
if not (isinstance(func, UndefinedFunction) and (args == (t,))):
return super()._print_Function(e)
return pform
def vprint(expr, **settings):
r"""Function for printing of expressions generated in the
sympy.physics vector package.
Extends SymPy's StrPrinter, takes the same setting accepted by SymPy's
:func:`~.sstr`, and is equivalent to ``print(sstr(foo))``.
Parameters
==========
expr : valid SymPy object
SymPy expression to print.
settings : args
Same as the settings accepted by SymPy's sstr().
Examples
========
>>> from sympy.physics.vector import vprint, dynamicsymbols
>>> u1 = dynamicsymbols('u1')
>>> print(u1)
u1(t)
>>> vprint(u1)
u1
"""
outstr = vsprint(expr, **settings)
import builtins
if (outstr != 'None'):
builtins._ = outstr
print(outstr)
def vsstrrepr(expr, **settings):
"""Function for displaying expression representation's with vector
printing enabled.
Parameters
==========
expr : valid SymPy object
SymPy expression to print.
settings : args
Same as the settings accepted by SymPy's sstrrepr().
"""
p = VectorStrReprPrinter(settings)
return p.doprint(expr)
def vsprint(expr, **settings):
r"""Function for displaying expressions generated in the
sympy.physics vector package.
Returns the output of vprint() as a string.
Parameters
==========
expr : valid SymPy object
SymPy expression to print
settings : args
Same as the settings accepted by SymPy's sstr().
Examples
========
>>> from sympy.physics.vector import vsprint, dynamicsymbols
>>> u1, u2 = dynamicsymbols('u1 u2')
>>> u2d = dynamicsymbols('u2', level=1)
>>> print("%s = %s" % (u1, u2 + u2d))
u1(t) = u2(t) + Derivative(u2(t), t)
>>> print("%s = %s" % (vsprint(u1), vsprint(u2 + u2d)))
u1 = u2 + u2'
"""
string_printer = VectorStrPrinter(settings)
return string_printer.doprint(expr)
def vpprint(expr, **settings):
r"""Function for pretty printing of expressions generated in the
sympy.physics vector package.
Mainly used for expressions not inside a vector; the output of running
scripts and generating equations of motion. Takes the same options as
SymPy's :func:`~.pretty_print`; see that function for more information.
Parameters
==========
expr : valid SymPy object
SymPy expression to pretty print
settings : args
Same as those accepted by SymPy's pretty_print.
"""
pp = VectorPrettyPrinter(settings)
# Note that this is copied from sympy.printing.pretty.pretty_print:
# XXX: this is an ugly hack, but at least it works
use_unicode = pp._settings['use_unicode']
from sympy.printing.pretty.pretty_symbology import pretty_use_unicode
uflag = pretty_use_unicode(use_unicode)
try:
return pp.doprint(expr)
finally:
pretty_use_unicode(uflag)
def vlatex(expr, **settings):
r"""Function for printing latex representation of sympy.physics.vector
objects.
For latex representation of Vectors, Dyadics, and dynamicsymbols. Takes the
same options as SymPy's :func:`~.latex`; see that function for more information;
Parameters
==========
expr : valid SymPy object
SymPy expression to represent in LaTeX form
settings : args
Same as latex()
Examples
========
>>> from sympy.physics.vector import vlatex, ReferenceFrame, dynamicsymbols
>>> N = ReferenceFrame('N')
>>> q1, q2 = dynamicsymbols('q1 q2')
>>> q1d, q2d = dynamicsymbols('q1 q2', 1)
>>> q1dd, q2dd = dynamicsymbols('q1 q2', 2)
>>> vlatex(N.x + N.y)
'\\mathbf{\\hat{n}_x} + \\mathbf{\\hat{n}_y}'
>>> vlatex(q1 + q2)
'q_{1} + q_{2}'
>>> vlatex(q1d)
'\\dot{q}_{1}'
>>> vlatex(q1 * q2d)
'q_{1} \\dot{q}_{2}'
>>> vlatex(q1dd * q1 / q1d)
'\\frac{q_{1} \\ddot{q}_{1}}{\\dot{q}_{1}}'
"""
latex_printer = VectorLatexPrinter(settings)
return latex_printer.doprint(expr)
def init_vprinting(**kwargs):
"""Initializes time derivative printing for all SymPy objects, i.e. any
functions of time will be displayed in a more compact notation. The main
benefit of this is for printing of time derivatives; instead of
displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is
only actually needed for when derivatives are present and are not in a
physics.vector.Vector or physics.vector.Dyadic object. This function is a
light wrapper to :func:`~.init_printing`. Any keyword
arguments for it are valid here.
{0}
Examples
========
>>> from sympy import Function, symbols
>>> t, x = symbols('t, x')
>>> omega = Function('omega')
>>> omega(x).diff()
Derivative(omega(x), x)
>>> omega(t).diff()
Derivative(omega(t), t)
Now use the string printer:
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> omega(x).diff()
Derivative(omega(x), x)
>>> omega(t).diff()
omega'
"""
kwargs['str_printer'] = vsstrrepr
kwargs['pretty_printer'] = vpprint
kwargs['latex_printer'] = vlatex
init_printing(**kwargs)
params = init_printing.__doc__.split('Examples\n ========')[0] # type: ignore
init_vprinting.__doc__ = init_vprinting.__doc__.format(params) # type: ignore
|
2fb102754cb71c5868fbb34e2f1738988b1aeefa5b6552a796e455e5e2f25623 | from sympy.core.backend import (S, sympify, expand, sqrt, Add, zeros,
ImmutableMatrix as Matrix)
from sympy import trigsimp
from sympy.printing.defaults import Printable
from sympy.utilities.misc import filldedent
from sympy.core.evalf import EvalfMixin, prec_to_dps
__all__ = ['Vector']
class Vector(Printable, EvalfMixin):
"""The class used to define vectors.
It along with ReferenceFrame are the building blocks of describing a
classical mechanics system in PyDy and sympy.physics.vector.
Attributes
==========
simp : Boolean
Let certain methods use trigsimp on their outputs
"""
simp = False
is_number = False
def __init__(self, inlist):
"""This is the constructor for the Vector class. You shouldn't be
calling this, it should only be used by other functions. You should be
treating Vectors like you would with if you were doing the math by
hand, and getting the first 3 from the standard basis vectors from a
ReferenceFrame.
The only exception is to create a zero vector:
zv = Vector(0)
"""
self.args = []
if inlist == 0:
inlist = []
if isinstance(inlist, dict):
d = inlist
else:
d = {}
for inp in inlist:
if inp[1] in d:
d[inp[1]] += inp[0]
else:
d[inp[1]] = inp[0]
for k, v in d.items():
if v != Matrix([0, 0, 0]):
self.args.append((v, k))
@property
def func(self):
"""Returns the class Vector. """
return Vector
def __hash__(self):
return hash(tuple(self.args))
def __add__(self, other):
"""The add operator for Vector. """
if other == 0:
return self
other = _check_vector(other)
return Vector(self.args + other.args)
def __and__(self, other):
"""Dot product of two vectors.
Returns a scalar, the dot product of the two Vectors
Parameters
==========
other : Vector
The Vector which we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot
>>> from sympy import symbols
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> dot(N.x, N.x)
1
>>> dot(N.x, N.y)
0
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> dot(N.y, A.y)
cos(q1)
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
out = S.Zero
for i, v1 in enumerate(self.args):
for j, v2 in enumerate(other.args):
out += ((v2[0].T)
* (v2[1].dcm(v1[1]))
* (v1[0]))[0]
if Vector.simp:
return trigsimp(sympify(out), recursive=True)
else:
return sympify(out)
def __truediv__(self, other):
"""This uses mul and inputs self and 1 divided by other. """
return self.__mul__(sympify(1) / other)
def __eq__(self, other):
"""Tests for equality.
It is very import to note that this is only as good as the SymPy
equality test; False does not always mean they are not equivalent
Vectors.
If other is 0, and self is empty, returns True.
If other is 0 and self is not empty, returns False.
If none of the above, only accepts other as a Vector.
"""
if other == 0:
other = Vector(0)
try:
other = _check_vector(other)
except TypeError:
return False
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
frame = self.args[0][1]
for v in frame:
if expand((self - other) & v) != 0:
return False
return True
def __mul__(self, other):
"""Multiplies the Vector by a sympifyable expression.
Parameters
==========
other : Sympifyable
The scalar to multiply this Vector with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> b = Symbol('b')
>>> V = 10 * b * N.x
>>> print(V)
10*b*N.x
"""
newlist = [v for v in self.args]
for i, v in enumerate(newlist):
newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1])
return Vector(newlist)
def __ne__(self, other):
return not self == other
def __neg__(self):
return self * -1
def __or__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def _latex(self, printer):
"""Latex Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].latex_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].latex_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + ar[i][1].latex_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
"""Pretty Printing method. """
from sympy.printing.pretty.stringpict import prettyForm
e = self
class Fake:
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
if len(ar) == 0:
return str(0)
pforms = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
pform = printer._print(ar[i][1].pretty_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
pform = printer._print(ar[i][1].pretty_vecs[j])
pform = prettyForm(*pform.left(" - "))
bin = prettyForm.NEG
pform = prettyForm(binding=bin, *pform)
elif ar[i][0][j] != 0:
# If the basis vector coeff is not 1 or -1,
# we might wrap it in parentheses, for readability.
pform = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
tmp = pform.parens()
pform = prettyForm(tmp[0], tmp[1])
pform = prettyForm(*pform.right(" ",
ar[i][1].pretty_vecs[j]))
else:
continue
pforms.append(pform)
pform = prettyForm.__add__(*pforms)
kwargs["wrap_line"] = kwargs.get("wrap_line")
kwargs["num_columns"] = kwargs.get("num_columns")
out_str = pform.render(*args, **kwargs)
mlines = [line.rstrip() for line in out_str.split("\n")]
return "\n".join(mlines)
return Fake()
def __ror__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(other.args):
for i2, v2 in enumerate(self.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def __rsub__(self, other):
return (-1 * self) + other
def _sympystr(self, printer, order=True):
"""Printing method. """
if not order or len(self.args) == 1:
ar = list(self.args)
elif len(self.args) == 0:
return printer._print(0)
else:
d = {v[1]: v[0] for v in self.args}
keys = sorted(d.keys(), key=lambda x: x.index)
ar = []
for key in keys:
ar.append((d[key], key))
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].str_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].str_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*' + ar[i][1].str_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""The cross product operator for two Vectors.
Returns a Vector, expressed in the same ReferenceFrames as self.
Parameters
==========
other : Vector
The Vector which we are crossing with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import symbols
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> N.x ^ N.y
N.z
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> A.x ^ N.y
N.z
>>> N.y ^ A.x
- sin(q1)*A.y - cos(q1)*A.z
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
if other.args == []:
return Vector(0)
def _det(mat):
"""This is needed as a little method for to find the determinant
of a list in python; needs to work for a 3x3 list.
SymPy's Matrix won't take in Vector, so need a custom function.
You shouldn't be calling this.
"""
return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1])
+ mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] *
mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] -
mat[1][1] * mat[2][0]))
outlist = []
ar = other.args # For brevity
for i, v in enumerate(ar):
tempx = v[1].x
tempy = v[1].y
tempz = v[1].z
tempm = ([[tempx, tempy, tempz], [self & tempx, self & tempy,
self & tempz], [Vector([ar[i]]) & tempx,
Vector([ar[i]]) & tempy, Vector([ar[i]]) & tempz]])
outlist += _det(tempm).args
return Vector(outlist)
__radd__ = __add__
__rand__ = __and__
__rmul__ = __mul__
def separate(self):
"""
The constituents of this vector in different reference frames,
as per its definition.
Returns a dict mapping each ReferenceFrame to the corresponding
constituent Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> R1 = ReferenceFrame('R1')
>>> R2 = ReferenceFrame('R2')
>>> v = R1.x + R2.x
>>> v.separate() == {R1: R1.x, R2: R2.x}
True
"""
components = {}
for x in self.args:
components[x[1]] = Vector([x])
return components
def dot(self, other):
return self & other
dot.__doc__ = __and__.__doc__
def cross(self, other):
return self ^ other
cross.__doc__ = __xor__.__doc__
def outer(self, other):
return self | other
outer.__doc__ = __or__.__doc__
def diff(self, var, frame, var_in_dcm=True):
"""Returns the partial derivative of the vector with respect to a
variable in the provided reference frame.
Parameters
==========
var : Symbol
What the partial derivative is taken with respect to.
frame : ReferenceFrame
The reference frame that the partial derivative is taken in.
var_in_dcm : boolean
If true, the differentiation algorithm assumes that the variable
may be present in any of the direction cosine matrices that relate
the frame to the frames of any component of the vector. But if it
is known that the variable is not present in the direction cosine
matrices, false can be set to skip full reexpression in the desired
frame.
Examples
========
>>> from sympy import Symbol
>>> from sympy.physics.vector import dynamicsymbols, ReferenceFrame
>>> from sympy.physics.vector import Vector
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> Vector.simp = True
>>> t = Symbol('t')
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.diff(t, N)
- q1'*A.z
>>> B = ReferenceFrame('B')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> v = u1 * A.x + u2 * B.y
>>> v.diff(u2, N, var_in_dcm=False)
B.y
"""
from sympy.physics.vector.frame import _check_frame
var = sympify(var)
_check_frame(frame)
inlist = []
for vector_component in self.args:
measure_number = vector_component[0]
component_frame = vector_component[1]
if component_frame == frame:
inlist += [(measure_number.diff(var), frame)]
else:
# If the direction cosine matrix relating the component frame
# with the derivative frame does not contain the variable.
if not var_in_dcm or (frame.dcm(component_frame).diff(var) ==
zeros(3, 3)):
inlist += [(measure_number.diff(var),
component_frame)]
else: # else express in the frame
reexp_vec_comp = Vector([vector_component]).express(frame)
deriv = reexp_vec_comp.args[0][0].diff(var)
inlist += Vector([(deriv, frame)]).express(component_frame).args
return Vector(inlist)
def express(self, otherframe, variables=False):
"""
Returns a Vector equivalent to this one, expressed in otherframe.
Uses the global express method.
Parameters
==========
otherframe : ReferenceFrame
The frame for this Vector to be described in
variables : boolean
If True, the coordinate symbols(if present) in this Vector
are re-expressed in terms otherframe
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.express(N)
cos(q1)*N.x - sin(q1)*N.z
"""
from sympy.physics.vector import express
return express(self, otherframe, variables=variables)
def to_matrix(self, reference_frame):
"""Returns the matrix form of the vector with respect to the given
frame.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows of the matrix correspond to.
Returns
-------
matrix : ImmutableMatrix, shape(3,1)
The matrix that gives the 1D vector.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> a, b, c = symbols('a, b, c')
>>> N = ReferenceFrame('N')
>>> vector = a * N.x + b * N.y + c * N.z
>>> vector.to_matrix(N)
Matrix([
[a],
[b],
[c]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> vector.to_matrix(A)
Matrix([
[ a],
[ b*cos(beta) + c*sin(beta)],
[-b*sin(beta) + c*cos(beta)]])
"""
return Matrix([self.dot(unit_vec) for unit_vec in
reference_frame]).reshape(3, 1)
def doit(self, **hints):
"""Calls .doit() on each term in the Vector"""
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(lambda x: x.doit(**hints))
return Vector(d)
def dt(self, otherframe):
"""
Returns a Vector which is the time derivative of
the self Vector, taken in frame otherframe.
Calls the global time_derivative method
Parameters
==========
otherframe : ReferenceFrame
The frame to calculate the time derivative in
"""
from sympy.physics.vector import time_derivative
return time_derivative(self, otherframe)
def simplify(self):
"""Returns a simplified Vector."""
d = {}
for v in self.args:
d[v[1]] = v[0].simplify()
return Vector(d)
def subs(self, *args, **kwargs):
"""Substitution on the Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = N.x * s
>>> a.subs({s: 2})
2*N.x
"""
d = {}
for v in self.args:
d[v[1]] = v[0].subs(*args, **kwargs)
return Vector(d)
def magnitude(self):
"""Returns the magnitude (Euclidean norm) of self."""
return sqrt(self & self)
def normalize(self):
"""Returns a Vector of magnitude 1, codirectional with self."""
return Vector(self.args + []) / self.magnitude()
def applyfunc(self, f):
"""Apply a function to each component of a vector."""
if not callable(f):
raise TypeError("`f` must be callable.")
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(f)
return Vector(d)
def free_symbols(self, reference_frame):
"""
Returns the free symbols in the measure numbers of the vector
expressed in the given reference frame.
Parameter
=========
reference_frame : ReferenceFrame
The frame with respect to which the free symbols of the
given vector is to be determined.
"""
return self.to_matrix(reference_frame).free_symbols
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
for mat, frame in self.args:
new_args.append([mat.evalf(n=prec_to_dps(prec)), frame])
return Vector(new_args)
class VectorTypeError(TypeError):
def __init__(self, other, want):
msg = filldedent("Expected an instance of %s, but received object "
"'%s' of %s." % (type(want), other, type(other)))
super().__init__(msg)
def _check_vector(other):
if not isinstance(other, Vector):
raise TypeError('A Vector must be supplied')
return other
|
cbda8e74146f20ebc226d605faea2c48d8e6878cde963026cb85f99d45062c89 | from functools import reduce
from sympy.core.backend import (sympify, diff, sin, cos, Matrix, symbols,
Function, S, Symbol)
from sympy import integrate, trigsimp
from .vector import Vector, _check_vector
from .frame import CoordinateSym, _check_frame
from .dyadic import Dyadic
from .printing import vprint, vsprint, vpprint, vlatex, init_vprinting
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import translate
__all__ = ['cross', 'dot', 'express', 'time_derivative', 'outer',
'kinematic_equations', 'get_motion_params', 'partial_velocity',
'dynamicsymbols', 'vprint', 'vsprint', 'vpprint', 'vlatex',
'init_vprinting']
def cross(vec1, vec2):
"""Cross product convenience wrapper for Vector.cross(): \n"""
if not isinstance(vec1, (Vector, Dyadic)):
raise TypeError('Cross product is between two vectors')
return vec1 ^ vec2
cross.__doc__ += Vector.cross.__doc__ # type: ignore
def dot(vec1, vec2):
"""Dot product convenience wrapper for Vector.dot(): \n"""
if not isinstance(vec1, (Vector, Dyadic)):
raise TypeError('Dot product is between two vectors')
return vec1 & vec2
dot.__doc__ += Vector.dot.__doc__ # type: ignore
def express(expr, frame, frame2=None, variables=False):
"""
Global function for 'express' functionality.
Re-expresses a Vector, scalar(sympyfiable) or Dyadic in given frame.
Refer to the local methods of Vector and Dyadic for details.
If 'variables' is True, then the coordinate variables (CoordinateSym
instances) of other frames present in the vector/scalar field or
dyadic expression are also substituted in terms of the base scalars of
this frame.
Parameters
==========
expr : Vector/Dyadic/scalar(sympyfiable)
The expression to re-express in ReferenceFrame 'frame'
frame: ReferenceFrame
The reference frame to express expr in
frame2 : ReferenceFrame
The other frame required for re-expression(only for Dyadic expr)
variables : boolean
Specifies whether to substitute the coordinate variables present
in expr, in terms of those of frame
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> from sympy.physics.vector import express
>>> express(d, B, N)
cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x)
>>> express(B.x, N)
cos(q)*N.x + sin(q)*N.y
>>> express(N[0], B, variables=True)
B_x*cos(q) - B_y*sin(q)
"""
_check_frame(frame)
if expr == 0:
return expr
if isinstance(expr, Vector):
#Given expr is a Vector
if variables:
#If variables attribute is True, substitute
#the coordinate variables in the Vector
frame_list = [x[-1] for x in expr.args]
subs_dict = {}
for f in frame_list:
subs_dict.update(f.variable_map(frame))
expr = expr.subs(subs_dict)
#Re-express in this frame
outvec = Vector([])
for i, v in enumerate(expr.args):
if v[1] != frame:
temp = frame.dcm(v[1]) * v[0]
if Vector.simp:
temp = temp.applyfunc(lambda x:
trigsimp(x, method='fu'))
outvec += Vector([(temp, frame)])
else:
outvec += Vector([v])
return outvec
if isinstance(expr, Dyadic):
if frame2 is None:
frame2 = frame
_check_frame(frame2)
ol = Dyadic(0)
for i, v in enumerate(expr.args):
ol += express(v[0], frame, variables=variables) * \
(express(v[1], frame, variables=variables) |
express(v[2], frame2, variables=variables))
return ol
else:
if variables:
#Given expr is a scalar field
frame_set = set()
expr = sympify(expr)
#Substitute all the coordinate variables
for x in expr.free_symbols:
if isinstance(x, CoordinateSym)and x.frame != frame:
frame_set.add(x.frame)
subs_dict = {}
for f in frame_set:
subs_dict.update(f.variable_map(frame))
return expr.subs(subs_dict)
return expr
def time_derivative(expr, frame, order=1):
"""
Calculate the time derivative of a vector/scalar field function
or dyadic expression in given frame.
References
==========
https://en.wikipedia.org/wiki/Rotating_reference_frame#Time_derivatives_in_the_two_frames
Parameters
==========
expr : Vector/Dyadic/sympifyable
The expression whose time derivative is to be calculated
frame : ReferenceFrame
The reference frame to calculate the time derivative in
order : integer
The order of the derivative to be calculated
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> from sympy import Symbol
>>> q1 = Symbol('q1')
>>> u1 = dynamicsymbols('u1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> v = u1 * N.x
>>> A.set_ang_vel(N, 10*A.x)
>>> from sympy.physics.vector import time_derivative
>>> time_derivative(v, N)
u1'*N.x
>>> time_derivative(u1*A[0], N)
N_x*u1'
>>> B = N.orientnew('B', 'Axis', [u1, N.z])
>>> from sympy.physics.vector import outer
>>> d = outer(N.x, N.x)
>>> time_derivative(d, B)
- u1'*(N.y|N.x) - u1'*(N.x|N.y)
"""
t = dynamicsymbols._t
_check_frame(frame)
if order == 0:
return expr
if order % 1 != 0 or order < 0:
raise ValueError("Unsupported value of order entered")
if isinstance(expr, Vector):
outlist = []
for i, v in enumerate(expr.args):
if v[1] == frame:
outlist += [(express(v[0], frame,
variables=True).diff(t), frame)]
else:
outlist += (time_derivative(Vector([v]), v[1]) + \
(v[1].ang_vel_in(frame) ^ Vector([v]))).args
outvec = Vector(outlist)
return time_derivative(outvec, frame, order - 1)
if isinstance(expr, Dyadic):
ol = Dyadic(0)
for i, v in enumerate(expr.args):
ol += (v[0].diff(t) * (v[1] | v[2]))
ol += (v[0] * (time_derivative(v[1], frame) | v[2]))
ol += (v[0] * (v[1] | time_derivative(v[2], frame)))
return time_derivative(ol, frame, order - 1)
else:
return diff(express(expr, frame, variables=True), t, order)
def outer(vec1, vec2):
"""Outer product convenience wrapper for Vector.outer():\n"""
if not isinstance(vec1, Vector):
raise TypeError('Outer product is between two Vectors')
return vec1 | vec2
outer.__doc__ += Vector.outer.__doc__ # type: ignore
def kinematic_equations(speeds, coords, rot_type, rot_order=''):
"""Gives equations relating the qdot's to u's for a rotation type.
Supply rotation type and order as in orient. Speeds are assumed to be
body-fixed; if we are defining the orientation of B in A using by rot_type,
the angular velocity of B in A is assumed to be in the form: speed[0]*B.x +
speed[1]*B.y + speed[2]*B.z
Parameters
==========
speeds : list of length 3
The body fixed angular velocity measure numbers.
coords : list of length 3 or 4
The coordinates used to define the orientation of the two frames.
rot_type : str
The type of rotation used to create the equations. Body, Space, or
Quaternion only
rot_order : str or int
If applicable, the order of a series of rotations.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import kinematic_equations, vprint
>>> u1, u2, u3 = dynamicsymbols('u1 u2 u3')
>>> q1, q2, q3 = dynamicsymbols('q1 q2 q3')
>>> vprint(kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313'),
... order=None)
[-(u1*sin(q3) + u2*cos(q3))/sin(q2) + q1', -u1*cos(q3) + u2*sin(q3) + q2', (u1*sin(q3) + u2*cos(q3))*cos(q2)/sin(q2) - u3 + q3']
"""
# Code below is checking and sanitizing input
approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131',
'212', '232', '313', '323', '1', '2', '3', '')
# make sure XYZ => 123 and rot_type is in lower case
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.lower()
if not isinstance(speeds, (list, tuple)):
raise TypeError('Need to supply speeds in a list')
if len(speeds) != 3:
raise TypeError('Need to supply 3 body-fixed speeds')
if not isinstance(coords, (list, tuple)):
raise TypeError('Need to supply coordinates in a list')
if rot_type in ['body', 'space']:
if rot_order not in approved_orders:
raise ValueError('Not an acceptable rotation order')
if len(coords) != 3:
raise ValueError('Need 3 coordinates for body or space')
# Actual hard-coded kinematic differential equations
w1, w2, w3 = speeds
if w1 == w2 == w3 == 0:
return [S.Zero]*3
q1, q2, q3 = coords
q1d, q2d, q3d = [diff(i, dynamicsymbols._t) for i in coords]
s1, s2, s3 = [sin(q1), sin(q2), sin(q3)]
c1, c2, c3 = [cos(q1), cos(q2), cos(q3)]
if rot_type == 'body':
if rot_order == '123':
return [q1d - (w1 * c3 - w2 * s3) / c2, q2d - w1 * s3 - w2 *
c3, q3d - (-w1 * c3 + w2 * s3) * s2 / c2 - w3]
if rot_order == '231':
return [q1d - (w2 * c3 - w3 * s3) / c2, q2d - w2 * s3 - w3 *
c3, q3d - w1 - (- w2 * c3 + w3 * s3) * s2 / c2]
if rot_order == '312':
return [q1d - (-w1 * s3 + w3 * c3) / c2, q2d - w1 * c3 - w3 *
s3, q3d - (w1 * s3 - w3 * c3) * s2 / c2 - w2]
if rot_order == '132':
return [q1d - (w1 * c3 + w3 * s3) / c2, q2d + w1 * s3 - w3 *
c3, q3d - (w1 * c3 + w3 * s3) * s2 / c2 - w2]
if rot_order == '213':
return [q1d - (w1 * s3 + w2 * c3) / c2, q2d - w1 * c3 + w2 *
s3, q3d - (w1 * s3 + w2 * c3) * s2 / c2 - w3]
if rot_order == '321':
return [q1d - (w2 * s3 + w3 * c3) / c2, q2d - w2 * c3 + w3 *
s3, q3d - w1 - (w2 * s3 + w3 * c3) * s2 / c2]
if rot_order == '121':
return [q1d - (w2 * s3 + w3 * c3) / s2, q2d - w2 * c3 + w3 *
s3, q3d - w1 + (w2 * s3 + w3 * c3) * c2 / s2]
if rot_order == '131':
return [q1d - (-w2 * c3 + w3 * s3) / s2, q2d - w2 * s3 - w3 *
c3, q3d - w1 - (w2 * c3 - w3 * s3) * c2 / s2]
if rot_order == '212':
return [q1d - (w1 * s3 - w3 * c3) / s2, q2d - w1 * c3 - w3 *
s3, q3d - (-w1 * s3 + w3 * c3) * c2 / s2 - w2]
if rot_order == '232':
return [q1d - (w1 * c3 + w3 * s3) / s2, q2d + w1 * s3 - w3 *
c3, q3d + (w1 * c3 + w3 * s3) * c2 / s2 - w2]
if rot_order == '313':
return [q1d - (w1 * s3 + w2 * c3) / s2, q2d - w1 * c3 + w2 *
s3, q3d + (w1 * s3 + w2 * c3) * c2 / s2 - w3]
if rot_order == '323':
return [q1d - (-w1 * c3 + w2 * s3) / s2, q2d - w1 * s3 - w2 *
c3, q3d - (w1 * c3 - w2 * s3) * c2 / s2 - w3]
if rot_type == 'space':
if rot_order == '123':
return [q1d - w1 - (w2 * s1 + w3 * c1) * s2 / c2, q2d - w2 *
c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / c2]
if rot_order == '231':
return [q1d - (w1 * c1 + w3 * s1) * s2 / c2 - w2, q2d + w1 *
s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / c2]
if rot_order == '312':
return [q1d - (w1 * s1 + w2 * c1) * s2 / c2 - w3, q2d - w1 *
c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / c2]
if rot_order == '132':
return [q1d - w1 - (-w2 * c1 + w3 * s1) * s2 / c2, q2d - w2 *
s1 - w3 * c1, q3d - (w2 * c1 - w3 * s1) / c2]
if rot_order == '213':
return [q1d - (w1 * s1 - w3 * c1) * s2 / c2 - w2, q2d - w1 *
c1 - w3 * s1, q3d - (-w1 * s1 + w3 * c1) / c2]
if rot_order == '321':
return [q1d - (-w1 * c1 + w2 * s1) * s2 / c2 - w3, q2d - w1 *
s1 - w2 * c1, q3d - (w1 * c1 - w2 * s1) / c2]
if rot_order == '121':
return [q1d - w1 + (w2 * s1 + w3 * c1) * c2 / s2, q2d - w2 *
c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / s2]
if rot_order == '131':
return [q1d - w1 - (w2 * c1 - w3 * s1) * c2 / s2, q2d - w2 *
s1 - w3 * c1, q3d - (-w2 * c1 + w3 * s1) / s2]
if rot_order == '212':
return [q1d - (-w1 * s1 + w3 * c1) * c2 / s2 - w2, q2d - w1 *
c1 - w3 * s1, q3d - (w1 * s1 - w3 * c1) / s2]
if rot_order == '232':
return [q1d + (w1 * c1 + w3 * s1) * c2 / s2 - w2, q2d + w1 *
s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / s2]
if rot_order == '313':
return [q1d + (w1 * s1 + w2 * c1) * c2 / s2 - w3, q2d - w1 *
c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / s2]
if rot_order == '323':
return [q1d - (w1 * c1 - w2 * s1) * c2 / s2 - w3, q2d - w1 *
s1 - w2 * c1, q3d - (-w1 * c1 + w2 * s1) / s2]
elif rot_type == 'quaternion':
if rot_order != '':
raise ValueError('Cannot have rotation order for quaternion')
if len(coords) != 4:
raise ValueError('Need 4 coordinates for quaternion')
# Actual hard-coded kinematic differential equations
e0, e1, e2, e3 = coords
w = Matrix(speeds + [0])
E = Matrix([[e0, -e3, e2, e1], [e3, e0, -e1, e2], [-e2, e1, e0, e3],
[-e1, -e2, -e3, e0]])
edots = Matrix([diff(i, dynamicsymbols._t) for i in [e1, e2, e3, e0]])
return list(edots.T - 0.5 * w.T * E.T)
else:
raise ValueError('Not an approved rotation type for this function')
def get_motion_params(frame, **kwargs):
"""
Returns the three motion parameters - (acceleration, velocity, and
position) as vectorial functions of time in the given frame.
If a higher order differential function is provided, the lower order
functions are used as boundary conditions. For example, given the
acceleration, the velocity and position parameters are taken as
boundary conditions.
The values of time at which the boundary conditions are specified
are taken from timevalue1(for position boundary condition) and
timevalue2(for velocity boundary condition).
If any of the boundary conditions are not provided, they are taken
to be zero by default (zero vectors, in case of vectorial inputs). If
the boundary conditions are also functions of time, they are converted
to constants by substituting the time values in the dynamicsymbols._t
time Symbol.
This function can also be used for calculating rotational motion
parameters. Have a look at the Parameters and Examples for more clarity.
Parameters
==========
frame : ReferenceFrame
The frame to express the motion parameters in
acceleration : Vector
Acceleration of the object/frame as a function of time
velocity : Vector
Velocity as function of time or as boundary condition
of velocity at time = timevalue1
position : Vector
Velocity as function of time or as boundary condition
of velocity at time = timevalue1
timevalue1 : sympyfiable
Value of time for position boundary condition
timevalue2 : sympyfiable
Value of time for velocity boundary condition
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, get_motion_params, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> from sympy import symbols
>>> R = ReferenceFrame('R')
>>> v1, v2, v3 = dynamicsymbols('v1 v2 v3')
>>> v = v1*R.x + v2*R.y + v3*R.z
>>> get_motion_params(R, position = v)
(v1''*R.x + v2''*R.y + v3''*R.z, v1'*R.x + v2'*R.y + v3'*R.z, v1*R.x + v2*R.y + v3*R.z)
>>> a, b, c = symbols('a b c')
>>> v = a*R.x + b*R.y + c*R.z
>>> get_motion_params(R, velocity = v)
(0, a*R.x + b*R.y + c*R.z, a*t*R.x + b*t*R.y + c*t*R.z)
>>> parameters = get_motion_params(R, acceleration = v)
>>> parameters[1]
a*t*R.x + b*t*R.y + c*t*R.z
>>> parameters[2]
a*t**2/2*R.x + b*t**2/2*R.y + c*t**2/2*R.z
"""
##Helper functions
def _process_vector_differential(vectdiff, condition, \
variable, ordinate, frame):
"""
Helper function for get_motion methods. Finds derivative of vectdiff wrt
variable, and its integral using the specified boundary condition at
value of variable = ordinate.
Returns a tuple of - (derivative, function and integral) wrt vectdiff
"""
#Make sure boundary condition is independent of 'variable'
if condition != 0:
condition = express(condition, frame, variables=True)
#Special case of vectdiff == 0
if vectdiff == Vector(0):
return (0, 0, condition)
#Express vectdiff completely in condition's frame to give vectdiff1
vectdiff1 = express(vectdiff, frame)
#Find derivative of vectdiff
vectdiff2 = time_derivative(vectdiff, frame)
#Integrate and use boundary condition
vectdiff0 = Vector(0)
lims = (variable, ordinate, variable)
for dim in frame:
function1 = vectdiff1.dot(dim)
abscissa = dim.dot(condition).subs({variable : ordinate})
# Indefinite integral of 'function1' wrt 'variable', using
# the given initial condition (ordinate, abscissa).
vectdiff0 += (integrate(function1, lims) + abscissa) * dim
#Return tuple
return (vectdiff2, vectdiff, vectdiff0)
##Function body
_check_frame(frame)
#Decide mode of operation based on user's input
if 'acceleration' in kwargs:
mode = 2
elif 'velocity' in kwargs:
mode = 1
else:
mode = 0
#All the possible parameters in kwargs
#Not all are required for every case
#If not specified, set to default values(may or may not be used in
#calculations)
conditions = ['acceleration', 'velocity', 'position',
'timevalue', 'timevalue1', 'timevalue2']
for i, x in enumerate(conditions):
if x not in kwargs:
if i < 3:
kwargs[x] = Vector(0)
else:
kwargs[x] = S.Zero
elif i < 3:
_check_vector(kwargs[x])
else:
kwargs[x] = sympify(kwargs[x])
if mode == 2:
vel = _process_vector_differential(kwargs['acceleration'],
kwargs['velocity'],
dynamicsymbols._t,
kwargs['timevalue2'], frame)[2]
pos = _process_vector_differential(vel, kwargs['position'],
dynamicsymbols._t,
kwargs['timevalue1'], frame)[2]
return (kwargs['acceleration'], vel, pos)
elif mode == 1:
return _process_vector_differential(kwargs['velocity'],
kwargs['position'],
dynamicsymbols._t,
kwargs['timevalue1'], frame)
else:
vel = time_derivative(kwargs['position'], frame)
acc = time_derivative(vel, frame)
return (acc, vel, kwargs['position'])
def partial_velocity(vel_vecs, gen_speeds, frame):
"""Returns a list of partial velocities with respect to the provided
generalized speeds in the given reference frame for each of the supplied
velocity vectors.
The output is a list of lists. The outer list has a number of elements
equal to the number of supplied velocity vectors. The inner lists are, for
each velocity vector, the partial derivatives of that velocity vector with
respect to the generalized speeds supplied.
Parameters
==========
vel_vecs : iterable
An iterable of velocity vectors (angular or linear).
gen_speeds : iterable
An iterable of generalized speeds.
frame : ReferenceFrame
The reference frame that the partial derivatives are going to be taken
in.
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import partial_velocity
>>> u = dynamicsymbols('u')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, u * N.x)
>>> vel_vecs = [P.vel(N)]
>>> gen_speeds = [u]
>>> partial_velocity(vel_vecs, gen_speeds, N)
[[N.x]]
"""
if not iterable(vel_vecs):
raise TypeError('Velocity vectors must be contained in an iterable.')
if not iterable(gen_speeds):
raise TypeError('Generalized speeds must be contained in an iterable')
vec_partials = []
for vec in vel_vecs:
partials = []
for speed in gen_speeds:
partials.append(vec.diff(speed, frame, var_in_dcm=False))
vec_partials.append(partials)
return vec_partials
def dynamicsymbols(names, level=0,**assumptions):
"""Uses symbols and Function for functions of time.
Creates a SymPy UndefinedFunction, which is then initialized as a function
of a variable, the default being Symbol('t').
Parameters
==========
names : str
Names of the dynamic symbols you want to create; works the same way as
inputs to symbols
level : int
Level of differentiation of the returned function; d/dt once of t,
twice of t, etc.
assumptions :
- real(bool) : This is used to set the dynamicsymbol as real,
by default is False.
- positive(bool) : This is used to set the dynamicsymbol as positive,
by default is False.
- commutative(bool) : This is used to set the commutative property of
a dynamicsymbol, by default is True.
- integer(bool) : This is used to set the dynamicsymbol as integer,
by default is False.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy import diff, Symbol
>>> q1 = dynamicsymbols('q1')
>>> q1
q1(t)
>>> q2 = dynamicsymbols('q2', real=True)
>>> q2.is_real
True
>>> q3 = dynamicsymbols('q3', positive=True)
>>> q3.is_positive
True
>>> q4, q5 = dynamicsymbols('q4,q5', commutative=False)
>>> bool(q4*q5 != q5*q4)
True
>>> q6 = dynamicsymbols('q6', integer=True)
>>> q6.is_integer
True
>>> diff(q1, Symbol('t'))
Derivative(q1(t), t)
"""
esses = symbols(names, cls=Function,**assumptions)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, [t] * level, e(t)) for e in esses]
return esses
else:
return reduce(diff, [t] * level, esses(t))
dynamicsymbols._t = Symbol('t') # type: ignore
dynamicsymbols._str = '\'' # type: ignore
|
e4b2e3fb35390dffddc31c0dfad1cff19e5fc8299ee841f525f28ca9d8e60477 | from sympy.core.backend import sympify, Add, ImmutableMatrix as Matrix
from sympy.core.evalf import EvalfMixin, prec_to_dps
from sympy.printing.defaults import Printable
__all__ = ['Dyadic']
class Dyadic(Printable, EvalfMixin):
"""A Dyadic object.
See:
https://en.wikipedia.org/wiki/Dyadic_tensor
Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
A more powerful way to represent a rigid body's inertia. While it is more
complex, by choosing Dyadic components to be in body fixed basis vectors,
the resulting matrix is equivalent to the inertia tensor.
"""
is_number = False
def __init__(self, inlist):
"""
Just like Vector's init, you shouldn't call this unless creating a
zero dyadic.
zd = Dyadic(0)
Stores a Dyadic as a list of lists; the inner list has the measure
number and the two unit vectors; the outerlist holds each unique
unit vector pair.
"""
self.args = []
if inlist == 0:
inlist = []
while len(inlist) != 0:
added = 0
for i, v in enumerate(self.args):
if ((str(inlist[0][1]) == str(self.args[i][1])) and
(str(inlist[0][2]) == str(self.args[i][2]))):
self.args[i] = (self.args[i][0] + inlist[0][0],
inlist[0][1], inlist[0][2])
inlist.remove(inlist[0])
added = 1
break
if added != 1:
self.args.append(inlist[0])
inlist.remove(inlist[0])
i = 0
# This code is to remove empty parts from the list
while i < len(self.args):
if ((self.args[i][0] == 0) | (self.args[i][1] == 0) |
(self.args[i][2] == 0)):
self.args.remove(self.args[i])
i -= 1
i += 1
@property
def func(self):
"""Returns the class Dyadic. """
return Dyadic
def __add__(self, other):
"""The add operator for Dyadic. """
other = _check_dyadic(other)
return Dyadic(self.args + other.args)
def __and__(self, other):
"""The inner product operator for a Dyadic and a Dyadic or Vector.
Parameters
==========
other : Dyadic or Vector
The other Dyadic or Vector to take the inner product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> D1 = outer(N.x, N.y)
>>> D2 = outer(N.y, N.y)
>>> D1.dot(D2)
(N.x|N.y)
>>> D1.dot(N.y)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
if isinstance(other, Dyadic):
other = _check_dyadic(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
ol += v[0] * v2[0] * (v[2] & v2[1]) * (v[1] | v2[2])
else:
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[1] * (v[2] & other)
return ol
def __truediv__(self, other):
"""Divides the Dyadic by a sympifyable expression. """
return self.__mul__(1 / other)
def __eq__(self, other):
"""Tests for equality.
Is currently weak; needs stronger comparison testing
"""
if other == 0:
other = Dyadic(0)
other = _check_dyadic(other)
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
return set(self.args) == set(other.args)
def __mul__(self, other):
"""Multiplies the Dyadic by a sympifyable expression.
Parameters
==========
other : Sympafiable
The scalar to multiply this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> 5 * d
5*(N.x|N.x)
"""
newlist = [v for v in self.args]
for i, v in enumerate(newlist):
newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1],
newlist[i][2])
return Dyadic(newlist)
def __ne__(self, other):
return not self == other
def __neg__(self):
return self * -1
def _latex(self, printer):
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + ' + printer._print(ar[i][1]) + r"\otimes " +
printer._print(ar[i][2]))
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - ' +
printer._print(ar[i][1]) +
r"\otimes " +
printer._print(ar[i][2]))
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = '(%s)' % arg_str
if arg_str.startswith('-'):
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + printer._print(ar[i][1]) +
r"\otimes " + printer._print(ar[i][2]))
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
e = self
class Fake:
baseline = 0
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
mpp = printer
if len(ar) == 0:
return str(0)
bar = "\N{CIRCLED TIMES}" if printer._use_unicode else "|"
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.extend([" + ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.extend([" - ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
if isinstance(ar[i][0], Add):
arg_str = mpp._print(
ar[i][0]).parens()[0]
else:
arg_str = mpp.doprint(ar[i][0])
if arg_str.startswith("-"):
arg_str = arg_str[1:]
str_start = " - "
else:
str_start = " + "
ol.extend([str_start, arg_str, " ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
outstr = "".join(ol)
if outstr.startswith(" + "):
outstr = outstr[3:]
elif outstr.startswith(" "):
outstr = outstr[1:]
return outstr
return Fake()
def __rand__(self, other):
"""The inner product operator for a Vector or Dyadic, and a Dyadic
This is for: Vector dot Dyadic
Parameters
==========
other : Vector
The vector we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> dot(N.x, d)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[2] * (v[1] & other)
return ol
def __rsub__(self, other):
return (-1 * self) + other
def __rxor__(self, other):
"""For a cross product in the form: Vector x Dyadic
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(N.y, d)
- (N.z|N.x)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * ((other ^ v[1]) | v[2])
return ol
def _sympystr(self, printer):
"""Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return printer._print(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')')
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')')
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*(' + printer._print(ar[i][1]) +
'|' + printer._print(ar[i][2]) + ')')
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""For a cross product in the form: Dyadic x Vector.
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(d, N.y)
(N.x|N.z)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * (v[1] | (v[2] ^ other))
return ol
__radd__ = __add__
__rmul__ = __mul__
def express(self, frame1, frame2=None):
"""Expresses this Dyadic in alternate frame(s)
The first frame is the list side expression, the second frame is the
right side; if Dyadic is in form A.x|B.y, you can express it in two
different frames. If no second frame is given, the Dyadic is
expressed in only one frame.
Calls the global express function
Parameters
==========
frame1 : ReferenceFrame
The frame to express the left side of the Dyadic in
frame2 : ReferenceFrame
If provided, the frame to express the right side of the Dyadic in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.express(B, N)
cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x)
"""
from sympy.physics.vector.functions import express
return express(self, frame1, frame2)
def to_matrix(self, reference_frame, second_reference_frame=None):
"""Returns the matrix form of the dyadic with respect to one or two
reference frames.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows and columns of the matrix
correspond to. If a second reference frame is provided, this
only corresponds to the rows of the matrix.
second_reference_frame : ReferenceFrame, optional, default=None
The reference frame that the columns of the matrix correspond
to.
Returns
-------
matrix : ImmutableMatrix, shape(3,3)
The matrix that gives the 2D tensor form.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, Vector
>>> Vector.simp = True
>>> from sympy.physics.mechanics import inertia
>>> Ixx, Iyy, Izz, Ixy, Iyz, Ixz = symbols('Ixx, Iyy, Izz, Ixy, Iyz, Ixz')
>>> N = ReferenceFrame('N')
>>> inertia_dyadic = inertia(N, Ixx, Iyy, Izz, Ixy, Iyz, Ixz)
>>> inertia_dyadic.to_matrix(N)
Matrix([
[Ixx, Ixy, Ixz],
[Ixy, Iyy, Iyz],
[Ixz, Iyz, Izz]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> inertia_dyadic.to_matrix(A)
Matrix([
[ Ixx, Ixy*cos(beta) + Ixz*sin(beta), -Ixy*sin(beta) + Ixz*cos(beta)],
[ Ixy*cos(beta) + Ixz*sin(beta), Iyy*cos(2*beta)/2 + Iyy/2 + Iyz*sin(2*beta) - Izz*cos(2*beta)/2 + Izz/2, -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2],
[-Ixy*sin(beta) + Ixz*cos(beta), -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2, -Iyy*cos(2*beta)/2 + Iyy/2 - Iyz*sin(2*beta) + Izz*cos(2*beta)/2 + Izz/2]])
"""
if second_reference_frame is None:
second_reference_frame = reference_frame
return Matrix([i.dot(self).dot(j) for i in reference_frame for j in
second_reference_frame]).reshape(3, 3)
def doit(self, **hints):
"""Calls .doit() on each term in the Dyadic"""
return sum([Dyadic([(v[0].doit(**hints), v[1], v[2])])
for v in self.args], Dyadic(0))
def dt(self, frame):
"""Take the time derivative of this Dyadic in a frame.
This function calls the global time_derivative method
Parameters
==========
frame : ReferenceFrame
The frame to take the time derivative in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.dt(B)
- q'*(N.y|N.x) - q'*(N.x|N.y)
"""
from sympy.physics.vector.functions import time_derivative
return time_derivative(self, frame)
def simplify(self):
"""Returns a simplified Dyadic."""
out = Dyadic(0)
for v in self.args:
out += Dyadic([(v[0].simplify(), v[1], v[2])])
return out
def subs(self, *args, **kwargs):
"""Substitution on the Dyadic.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = s*(N.x|N.x)
>>> a.subs({s: 2})
2*(N.x|N.x)
"""
return sum([Dyadic([(v[0].subs(*args, **kwargs), v[1], v[2])])
for v in self.args], Dyadic(0))
def applyfunc(self, f):
"""Apply a function to each component of a Dyadic."""
if not callable(f):
raise TypeError("`f` must be callable.")
out = Dyadic(0)
for a, b, c in self.args:
out += f(a) * (b|c)
return out
dot = __and__
cross = __xor__
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
for inlist in self.args:
new_inlist = list(inlist)
new_inlist[0] = inlist[0].evalf(n=prec_to_dps(prec))
new_args.append(tuple(new_inlist))
return Dyadic(new_args)
def _check_dyadic(other):
if not isinstance(other, Dyadic):
raise TypeError('A Dyadic must be supplied')
return other
|
1825d967c0f9557fee78087348bb26094ec82c979ba8a910fa2ed4c246868df3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The module implements routines to model the polarization of optical fields
and can be used to calculate the effects of polarization optical elements on
the fields.
- Jones vectors.
- Stokes vectors.
- Jones matrices.
- Mueller matrices.
Examples
========
We calculate a generic Jones vector:
>>> from sympy import symbols, pprint, zeros, simplify
>>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
... half_wave_retarder, polarizing_beam_splitter, jones_2_stokes)
>>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True)
>>> x0 = jones_vector(psi, chi)
>>> pprint(x0, use_unicode=True)
⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
⎢ ⎥
⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
And the more general Stokes vector:
>>> s0 = stokes_vector(psi, chi, p, I0)
>>> pprint(s0, use_unicode=True)
⎡ I₀ ⎤
⎢ ⎥
⎢I₀⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
⎢ ⎥
⎢I₀⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
⎢ ⎥
⎣ I₀⋅p⋅sin(2⋅χ) ⎦
We calculate how the Jones vector is modified by a half-wave plate:
>>> alpha = symbols("alpha", real=True)
>>> HWP = half_wave_retarder(alpha)
>>> x1 = simplify(HWP*x0)
We calculate the very common operation of passing a beam through a half-wave
plate and then through a polarizing beam-splitter. We do this by putting this
Jones vector as the first entry of a two-Jones-vector state that is transformed
by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the
transmitted and reflected Jones vectors:
>>> PBS = polarizing_beam_splitter()
>>> X1 = zeros(4, 1)
>>> X1[:2, :] = x1
>>> X2 = PBS*X1
>>> transmitted_port = X2[:2, :]
>>> reflected_port = X2[2:, :]
This allows us to calculate how the power in both ports depends on the initial
polarization:
>>> transmitted_power = jones_2_stokes(transmitted_port)[0]
>>> reflected_power = jones_2_stokes(reflected_port)[0]
>>> print(transmitted_power)
cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2
>>> print(reflected_power)
sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2
Please see the description of the individual functions for further
details and examples.
References
==========
.. [1] https://en.wikipedia.org/wiki/Jones_calculus
.. [2] https://en.wikipedia.org/wiki/Mueller_calculus
.. [3] https://en.wikipedia.org/wiki/Stokes_parameters
"""
from sympy import sin, cos, exp, I, pi, sqrt, Matrix, Abs, re, im, simplify
from sympy.physics.quantum import TensorProduct
def jones_vector(psi, chi):
"""A Jones vector corresponding to a polarization ellipse with `psi` tilt,
and `chi` circularity.
Parameters
==========
``psi`` : numeric type or sympy Symbol
The tilt of the polarization relative to the `x` axis.
``chi`` : numeric type or sympy Symbol
The angle adjacent to the mayor axis of the polarization ellipse.
Returns
=======
Matrix :
A Jones vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, symbols, pi
>>> from sympy.physics.optics.polarization import jones_vector
>>> psi, chi = symbols("psi, chi", real=True)
A general Jones vector.
>>> pprint(jones_vector(psi, chi), use_unicode=True)
⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
⎢ ⎥
⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
Horizontal polarization.
>>> pprint(jones_vector(0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎣0⎦
Vertical polarization.
>>> pprint(jones_vector(pi/2, 0), use_unicode=True)
⎡0⎤
⎢ ⎥
⎣1⎦
Diagonal polarization.
>>> pprint(jones_vector(pi/4, 0), use_unicode=True)
⎡√2⎤
⎢──⎥
⎢2 ⎥
⎢ ⎥
⎢√2⎥
⎢──⎥
⎣2 ⎦
Anti-diagonal polarization.
>>> pprint(jones_vector(-pi/4, 0), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢-√2 ⎥
⎢────⎥
⎣ 2 ⎦
Right-hand circular polarization.
>>> pprint(jones_vector(0, pi/4), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢√2⋅ⅈ⎥
⎢────⎥
⎣ 2 ⎦
Left-hand circular polarization.
>>> pprint(jones_vector(0, -pi/4), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢-√2⋅ⅈ ⎥
⎢──────⎥
⎣ 2 ⎦
"""
return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi),
I*sin(chi)*cos(psi) + sin(psi)*cos(chi)])
def stokes_vector(psi, chi, p=1, I=1):
"""A Stokes vector corresponding to a polarization ellipse with ``psi``
tilt, and ``chi`` circularity.
Parameters
==========
``psi`` : numeric type or sympy Symbol
The tilt of the polarization relative to the ``x`` axis.
``chi`` : numeric type or sympy Symbol
The angle adjacent to the mayor axis of the polarization ellipse.
``p`` : numeric type or sympy Symbol
The degree of polarization.
``I`` : numeric type or sympy Symbol
The intensity of the field.
Returns
=======
Matrix :
A Stokes vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, symbols, pi
>>> from sympy.physics.optics.polarization import stokes_vector
>>> psi, chi, p, I = symbols("psi, chi, p, I", real=True)
>>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True)
⎡ I ⎤
⎢ ⎥
⎢I⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
⎢ ⎥
⎢I⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
⎢ ⎥
⎣ I⋅p⋅sin(2⋅χ) ⎦
Horizontal polarization
>>> pprint(stokes_vector(0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢1⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣0⎦
Vertical polarization
>>> pprint(stokes_vector(pi/2, 0), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢-1⎥
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎣0 ⎦
Diagonal polarization
>>> pprint(stokes_vector(pi/4, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢1⎥
⎢ ⎥
⎣0⎦
Anti-diagonal polarization
>>> pprint(stokes_vector(-pi/4, 0), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎢-1⎥
⎢ ⎥
⎣0 ⎦
Right-hand circular polarization
>>> pprint(stokes_vector(0, pi/4), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣1⎦
Left-hand circular polarization
>>> pprint(stokes_vector(0, -pi/4), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎣-1⎦
Unpolarized light
>>> pprint(stokes_vector(0, 0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣0⎦
"""
S0 = I
S1 = I*p*cos(2*psi)*cos(2*chi)
S2 = I*p*sin(2*psi)*cos(2*chi)
S3 = I*p*sin(2*chi)
return Matrix([S0, S1, S2, S3])
def jones_2_stokes(e):
"""Return the Stokes vector for a Jones vector `e`.
Parameters
==========
``e`` : sympy Matrix
A Jones vector.
Returns
=======
sympy Matrix
A Jones vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, pi
>>> from sympy.physics.optics.polarization import jones_vector
>>> from sympy.physics.optics.polarization import jones_2_stokes
>>> H = jones_vector(0, 0)
>>> V = jones_vector(pi/2, 0)
>>> D = jones_vector(pi/4, 0)
>>> A = jones_vector(-pi/4, 0)
>>> R = jones_vector(0, pi/4)
>>> L = jones_vector(0, -pi/4)
>>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]],
... use_unicode=True)
⎡⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤⎤
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎢⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥ ⎢0⎥ ⎢0 ⎥⎥
⎢⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥⎥
⎢⎢0⎥ ⎢0 ⎥ ⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎣⎣0⎦ ⎣0 ⎦ ⎣0⎦ ⎣0 ⎦ ⎣1⎦ ⎣-1⎦⎦
"""
ex, ey = e
return Matrix([Abs(ex)**2 + Abs(ey)**2,
Abs(ex)**2 - Abs(ey)**2,
2*re(ex*ey.conjugate()),
-2*im(ex*ey.conjugate())])
def linear_polarizer(theta=0):
"""A linear polarizer Jones matrix with transmission axis at
an angle ``theta``.
Parameters
==========
``theta`` : numeric type or sympy Symbol
The angle of the transmission axis relative to the horizontal plane.
Returns
=======
sympy Matrix
A Jones matrix representing the polarizer.
Examples
========
A generic polarizer.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import linear_polarizer
>>> theta = symbols("theta", real=True)
>>> J = linear_polarizer(theta)
>>> pprint(J, use_unicode=True)
⎡ 2 ⎤
⎢ cos (θ) sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ 2 ⎥
⎣sin(θ)⋅cos(θ) sin (θ) ⎦
"""
M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)],
[sin(theta)*cos(theta), sin(theta)**2]])
return M
def phase_retarder(theta=0, delta=0):
"""A phase retarder Jones matrix with retardance `delta` at angle `theta`.
Parameters
==========
``theta`` : numeric type or sympy Symbol
The angle of the fast axis relative to the horizontal plane.
``delta`` : numeric type or sympy Symbol
The phase difference between the fast and slow axes of the
transmitted light.
Returns
=======
sympy Matrix :
A Jones matrix representing the retarder.
Examples
========
A generic retarder.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import phase_retarder
>>> theta, delta = symbols("theta, delta", real=True)
>>> R = phase_retarder(theta, delta)
>>> pprint(R, use_unicode=True)
⎡ -ⅈ⋅δ -ⅈ⋅δ ⎤
⎢ ───── ───── ⎥
⎢⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎛ ⅈ⋅δ⎞ 2 ⎥
⎢⎝ℯ ⋅sin (θ) + cos (θ)⎠⋅ℯ ⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ -ⅈ⋅δ -ⅈ⋅δ ⎥
⎢ ───── ─────⎥
⎢⎛ ⅈ⋅δ⎞ 2 ⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎥
⎣⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝ℯ ⋅cos (θ) + sin (θ)⎠⋅ℯ ⎦
"""
R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
(1-exp(I*delta))*cos(theta)*sin(theta)],
[(1-exp(I*delta))*cos(theta)*sin(theta),
sin(theta)**2 + exp(I*delta)*cos(theta)**2]])
return R*exp(-I*delta/2)
def half_wave_retarder(theta):
"""A half-wave retarder Jones matrix at angle `theta`.
Parameters
==========
``theta`` : numeric type or sympy Symbol
The angle of the fast axis relative to the horizontal plane.
Returns
=======
sympy Matrix
A Jones matrix representing the retarder.
Examples
========
A generic half-wave plate.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import half_wave_retarder
>>> theta= symbols("theta", real=True)
>>> HWP = half_wave_retarder(theta)
>>> pprint(HWP, use_unicode=True)
⎡ ⎛ 2 2 ⎞ ⎤
⎢-ⅈ⋅⎝- sin (θ) + cos (θ)⎠ -2⋅ⅈ⋅sin(θ)⋅cos(θ) ⎥
⎢ ⎥
⎢ ⎛ 2 2 ⎞⎥
⎣ -2⋅ⅈ⋅sin(θ)⋅cos(θ) -ⅈ⋅⎝sin (θ) - cos (θ)⎠⎦
"""
return phase_retarder(theta, pi)
def quarter_wave_retarder(theta):
"""A quarter-wave retarder Jones matrix at angle `theta`.
Parameters
==========
``theta`` : numeric type or sympy Symbol
The angle of the fast axis relative to the horizontal plane.
Returns
=======
sympy Matrix
A Jones matrix representing the retarder.
Examples
========
A generic quarter-wave plate.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import quarter_wave_retarder
>>> theta= symbols("theta", real=True)
>>> QWP = quarter_wave_retarder(theta)
>>> pprint(QWP, use_unicode=True)
⎡ -ⅈ⋅π -ⅈ⋅π ⎤
⎢ ───── ───── ⎥
⎢⎛ 2 2 ⎞ 4 4 ⎥
⎢⎝ⅈ⋅sin (θ) + cos (θ)⎠⋅ℯ (1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ -ⅈ⋅π -ⅈ⋅π ⎥
⎢ ───── ─────⎥
⎢ 4 ⎛ 2 2 ⎞ 4 ⎥
⎣(1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝sin (θ) + ⅈ⋅cos (θ)⎠⋅ℯ ⎦
"""
return phase_retarder(theta, pi/2)
def transmissive_filter(T):
"""An attenuator Jones matrix with transmittance `T`.
Parameters
==========
``T`` : numeric type or sympy Symbol
The transmittance of the attenuator.
Returns
=======
sympy Matrix
A Jones matrix representing the filter.
Examples
========
A generic filter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import transmissive_filter
>>> T = symbols("T", real=True)
>>> NDF = transmissive_filter(T)
>>> pprint(NDF, use_unicode=True)
⎡√T 0 ⎤
⎢ ⎥
⎣0 √T⎦
"""
return Matrix([[sqrt(T), 0], [0, sqrt(T)]])
def reflective_filter(R):
"""A reflective filter Jones matrix with reflectance `R`.
Parameters
==========
``R`` : numeric type or sympy Symbol
The reflectance of the filter.
Returns
=======
sympy Matrix
A Jones matrix representing the filter.
Examples
========
A generic filter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import reflective_filter
>>> R = symbols("R", real=True)
>>> pprint(reflective_filter(R), use_unicode=True)
⎡√R 0 ⎤
⎢ ⎥
⎣0 -√R⎦
"""
return Matrix([[sqrt(R), 0], [0, -sqrt(R)]])
def mueller_matrix(J):
"""The Mueller matrix corresponding to Jones matrix `J`.
Parameters
==========
``J`` : sympy Matrix
A Jones matrix.
Returns
=======
sympy Matrix
The corresponding Mueller matrix.
Examples
========
Generic optical components.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import (mueller_matrix,
... linear_polarizer, half_wave_retarder, quarter_wave_retarder)
>>> theta = symbols("theta", real=True)
A linear_polarizer
>>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True)
⎡ cos(2⋅θ) sin(2⋅θ) ⎤
⎢ 1/2 ──────── ──────── 0⎥
⎢ 2 2 ⎥
⎢ ⎥
⎢cos(2⋅θ) cos(4⋅θ) 1 sin(4⋅θ) ⎥
⎢──────── ──────── + ─ ──────── 0⎥
⎢ 2 4 4 4 ⎥
⎢ ⎥
⎢sin(2⋅θ) sin(4⋅θ) 1 cos(4⋅θ) ⎥
⎢──────── ──────── ─ - ──────── 0⎥
⎢ 2 4 4 4 ⎥
⎢ ⎥
⎣ 0 0 0 0⎦
A half-wave plate
>>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True)
⎡1 0 0 0 ⎤
⎢ ⎥
⎢ 4 2 ⎥
⎢0 8⋅sin (θ) - 8⋅sin (θ) + 1 sin(4⋅θ) 0 ⎥
⎢ ⎥
⎢ 4 2 ⎥
⎢0 sin(4⋅θ) - 8⋅sin (θ) + 8⋅sin (θ) - 1 0 ⎥
⎢ ⎥
⎣0 0 0 -1⎦
A quarter-wave plate
>>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True)
⎡1 0 0 0 ⎤
⎢ ⎥
⎢ cos(4⋅θ) 1 sin(4⋅θ) ⎥
⎢0 ──────── + ─ ──────── -sin(2⋅θ)⎥
⎢ 2 2 2 ⎥
⎢ ⎥
⎢ sin(4⋅θ) 1 cos(4⋅θ) ⎥
⎢0 ──────── ─ - ──────── cos(2⋅θ) ⎥
⎢ 2 2 2 ⎥
⎢ ⎥
⎣0 sin(2⋅θ) -cos(2⋅θ) 0 ⎦
"""
A = Matrix([[1, 0, 0, 1],
[1, 0, 0, -1],
[0, 1, 1, 0],
[0, -I, I, 0]])
return simplify(A*TensorProduct(J, J.conjugate())*A.inv())
def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0):
r"""A polarizing beam splitter Jones matrix at angle `theta`.
Parameters
==========
``J`` : sympy Matrix
A Jones matrix.
``Tp`` : numeric type or sympy Symbol
The transmissivity of the P-polarized component.
``Rs`` : numeric type or sympy Symbol
The reflectivity of the S-polarized component.
``Ts`` : numeric type or sympy Symbol
The transmissivity of the S-polarized component.
``Rp`` : numeric type or sympy Symbol
The reflectivity of the P-polarized component.
``phia`` : numeric type or sympy Symbol
The phase difference between transmitted and reflected component for
output mode a.
``phib`` : numeric type or sympy Symbol
The phase difference between transmitted and reflected component for
output mode b.
Returns
=======
sympy Matrix
A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector
whose first two entries are the Jones vector on one of the PBS ports,
and the last two entries the Jones vector on the other port.
Examples
========
Generic polarizing beam-splitter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import polarizing_beam_splitter
>>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True)
>>> phia, phib = symbols("phi_a, phi_b", real=True)
>>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib)
>>> pprint(PBS, use_unicode=False)
[ ____ ____ ]
[ \/ Tp 0 I*\/ Rp 0 ]
[ ]
[ ____ ____ I*phi_a]
[ 0 \/ Ts 0 -I*\/ Rs *e ]
[ ]
[ ____ ____ ]
[I*\/ Rp 0 \/ Tp 0 ]
[ ]
[ ____ I*phi_b ____ ]
[ 0 -I*\/ Rs *e 0 \/ Ts ]
"""
PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0],
[0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)],
[I*sqrt(Rp), 0, sqrt(Tp), 0],
[0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]])
return PBS
|
74d0798d672910639452b340d258f025d2a74db4df3ef7e15a5974efa8ecb3a9 | """
**Contains**
* Medium
"""
from sympy.physics.units import second, meter, kilogram, ampere
__all__ = ['Medium']
from sympy import Symbol, sympify, sqrt
from sympy.physics.units import speed_of_light, u0, e0
c = speed_of_light.convert_to(meter/second)
_e0mksa = e0.convert_to(ampere**2*second**4/(kilogram*meter**3))
_u0mksa = u0.convert_to(meter*kilogram/(ampere**2*second**2))
class Medium(Symbol):
"""
This class represents an optical medium. The prime reason to implement this is
to facilitate refraction, Fermat's principle, etc.
Explanation
===========
An optical medium is a material through which electromagnetic waves propagate.
The permittivity and permeability of the medium define how electromagnetic
waves propagate in it.
Parameters
==========
name: string
The display name of the Medium.
permittivity: Sympifyable
Electric permittivity of the space.
permeability: Sympifyable
Magnetic permeability of the space.
n: Sympifyable
Index of refraction of the medium.
Examples
========
>>> from sympy.abc import epsilon, mu
>>> from sympy.physics.optics import Medium
>>> m1 = Medium('m1')
>>> m2 = Medium('m2', epsilon, mu)
>>> m1.intrinsic_impedance
149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
>>> m2.refractive_index
299792458*meter*sqrt(epsilon*mu)/second
References
==========
.. [1] https://en.wikipedia.org/wiki/Optical_medium
"""
def __new__(cls, name, permittivity=None, permeability=None, n=None):
obj = super().__new__(cls, name)
obj._permittivity = sympify(permittivity)
obj._permeability = sympify(permeability)
obj._n = sympify(n)
if n is not None:
if permittivity is not None and permeability is None:
obj._permeability = n**2/(c**2*obj._permittivity)
if permeability is not None and permittivity is None:
obj._permittivity = n**2/(c**2*obj._permeability)
if permittivity is not None and permittivity is not None:
if abs(n - c*sqrt(obj._permittivity*obj._permeability)) > 1e-6:
raise ValueError("Values are not consistent.")
elif permittivity is not None and permeability is not None:
obj._n = c*sqrt(permittivity*permeability)
elif permittivity is None and permeability is None:
obj._permittivity = _e0mksa
obj._permeability = _u0mksa
return obj
@property
def intrinsic_impedance(self):
"""
Returns intrinsic impedance of the medium.
Explanation
===========
The intrinsic impedance of a medium is the ratio of the
transverse components of the electric and magnetic fields
of the electromagnetic wave travelling in the medium.
In a region with no electrical conductivity it simplifies
to the square root of ratio of magnetic permeability to
electric permittivity.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.intrinsic_impedance
149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
"""
return sqrt(self._permeability/self._permittivity)
@property
def speed(self):
"""
Returns speed of the electromagnetic wave travelling in the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.speed
299792458*meter/second
>>> m2 = Medium('m2', n=1)
>>> m.speed == m2.speed
True
"""
if self._permittivity is not None and self._permeability is not None:
return 1/sqrt(self._permittivity*self._permeability)
else:
return c/self._n
@property
def refractive_index(self):
"""
Returns refractive index of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.refractive_index
1
"""
return (c/self.speed)
@property
def permittivity(self):
"""
Returns electric permittivity of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permittivity
625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3)
"""
return self._permittivity
@property
def permeability(self):
"""
Returns magnetic permeability of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permeability
pi*kilogram*meter/(2500000*ampere**2*second**2)
"""
return self._permeability
def __str__(self):
from sympy.printing import sstr
return type(self).__name__ + ': ' + sstr([self._permittivity,
self._permeability, self._n])
def __lt__(self, other):
"""
Compares based on refractive index of the medium.
"""
return self.refractive_index < other.refractive_index
def __gt__(self, other):
return not self < other
def __eq__(self, other):
return self.refractive_index == other.refractive_index
def __ne__(self, other):
return not self == other
|
432c41cb5f7753c6c54f22e9b45311f8e8b04f75f668dfe685c822a06b9fb98b | """
**Contains**
* refraction_angle
* fresnel_coefficients
* deviation
* brewster_angle
* critical_angle
* lens_makers_formula
* mirror_formula
* lens_formula
* hyperfocal_distance
* transverse_magnification
"""
__all__ = ['refraction_angle',
'deviation',
'fresnel_coefficients',
'brewster_angle',
'critical_angle',
'lens_makers_formula',
'mirror_formula',
'lens_formula',
'hyperfocal_distance',
'transverse_magnification'
]
from sympy import Symbol, sympify, sqrt, Matrix, acos, oo, Limit, atan2, asin,\
cos, sin, tan, I, cancel, pi, Float
from sympy.core.compatibility import is_sequence
from sympy.geometry.line import Ray3D
from sympy.geometry.util import intersection
from sympy.geometry.plane import Plane
from .medium import Medium
def refractive_index_of_medium(medium):
"""
Helper function that returns refractive index, given a medium
"""
if isinstance(medium, Medium):
n = medium.refractive_index
else:
n = sympify(medium)
return n
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
"""
This function calculates transmitted vector after refraction at planar
surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
If ``incident`` is a number then treated as angle of incidence (in radians)
in which case refraction angle is returned.
If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
plane of separation is not provided and normal is an instance of `Ray3D`,
``normal`` will be assumed to be intersecting incident ray at the plane of
separation. This will not be the case when `normal` is a `Matrix` or
any other sequence.
If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
and ``normal`` is not `Ray3D`, output will be a `Matrix`.
Parameters
==========
incident : Matrix, Ray3D, sequence or a number
Incident vector or angle of incidence
medium1 : sympy.physics.optics.medium.Medium or sympifiable
Medium 1 or its refractive index
medium2 : sympy.physics.optics.medium.Medium or sympifiable
Medium 2 or its refractive index
normal : Matrix, Ray3D, or sequence
Normal vector
plane : Plane
Plane of separation of the two media.
Returns
=======
Returns an angle of refraction or a refracted ray depending on inputs.
Examples
========
>>> from sympy.physics.optics import refraction_angle
>>> from sympy.geometry import Point3D, Ray3D, Plane
>>> from sympy.matrices import Matrix
>>> from sympy import symbols, pi
>>> n = Matrix([0, 0, 1])
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
>>> refraction_angle(r1, 1, 1, n)
Matrix([
[ 1],
[ 1],
[-1]])
>>> refraction_angle(r1, 1, 1, plane=P)
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
With different index of refraction of the two media
>>> n1, n2 = symbols('n1, n2')
>>> refraction_angle(r1, n1, n2, n)
Matrix([
[ n1/n2],
[ n1/n2],
[-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
>>> refraction_angle(r1, n1, n2, plane=P)
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
>>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
0.41152
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
# check if an incidence angle was supplied instead of a ray
try:
angle_of_incidence = float(incident)
except TypeError:
angle_of_incidence = None
try:
critical_angle_ = critical_angle(medium1, medium2)
except (ValueError, TypeError):
critical_angle_ = None
if angle_of_incidence is not None:
if normal is not None or plane is not None:
raise ValueError('Normal/plane not allowed if incident is an angle')
if not 0.0 <= angle_of_incidence < pi*0.5:
raise ValueError('Angle of incidence not in range [0:pi/2)')
if critical_angle_ and angle_of_incidence > critical_angle_:
raise ValueError('Ray undergoes total internal reflection')
return asin(n1*sin(angle_of_incidence)/n2)
if angle_of_incidence and not 0 <= angle_of_incidence < pi*0.5:
raise ValueError
# Treat the incident as ray below
# A flag to check whether to return Ray3D or not
return_ray = False
if plane is not None and normal is not None:
raise ValueError("Either plane or normal is acceptable.")
if not isinstance(incident, Matrix):
if is_sequence(incident):
_incident = Matrix(incident)
elif isinstance(incident, Ray3D):
_incident = Matrix(incident.direction_ratio)
else:
raise TypeError(
"incident should be a Matrix, Ray3D, or sequence")
else:
_incident = incident
# If plane is provided, get direction ratios of the normal
# to the plane from the plane else go with `normal` param.
if plane is not None:
if not isinstance(plane, Plane):
raise TypeError("plane should be an instance of geometry.plane.Plane")
# If we have the plane, we can get the intersection
# point of incident ray and the plane and thus return
# an instance of Ray3D.
if isinstance(incident, Ray3D):
return_ray = True
intersection_pt = plane.intersection(incident)[0]
_normal = Matrix(plane.normal_vector)
else:
if not isinstance(normal, Matrix):
if is_sequence(normal):
_normal = Matrix(normal)
elif isinstance(normal, Ray3D):
_normal = Matrix(normal.direction_ratio)
if isinstance(incident, Ray3D):
intersection_pt = intersection(incident, normal)
if len(intersection_pt) == 0:
raise ValueError(
"Normal isn't concurrent with the incident ray.")
else:
return_ray = True
intersection_pt = intersection_pt[0]
else:
raise TypeError(
"Normal should be a Matrix, Ray3D, or sequence")
else:
_normal = normal
eta = n1/n2 # Relative index of refraction
# Calculating magnitude of the vectors
mag_incident = sqrt(sum([i**2 for i in _incident]))
mag_normal = sqrt(sum([i**2 for i in _normal]))
# Converting vectors to unit vectors by dividing
# them with their magnitudes
_incident /= mag_incident
_normal /= mag_normal
c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
if cs2.is_negative: # This is the case of total internal reflection(TIR).
return 0
drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
# Multiplying unit vector by its magnitude
drs = drs*mag_incident
if not return_ray:
return drs
else:
return Ray3D(intersection_pt, direction_ratio=drs)
def fresnel_coefficients(angle_of_incidence, medium1, medium2):
"""
This function uses Fresnel equations to calculate reflection and
transmission coefficients. Those are obtained for both polarisations
when the electric field vector is in the plane of incidence (labelled 'p')
and when the electric field vector is perpendicular to the plane of
incidence (labelled 's'). There are four real coefficients unless the
incident ray reflects in total internal in which case there are two complex
ones. Angle of incidence is the angle between the incident ray and the
surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
sympifiable object.
Parameters
==========
angle_of_incidence : sympifiable
medium1 : Medium or sympifiable
Medium 1 or its refractive index
medium2 : Medium or sympifiable
Medium 2 or its refractive index
Returns
=======
Returns a list with four real Fresnel coefficients:
[reflection p (TM), reflection s (TE),
transmission p (TM), transmission s (TE)]
If the ray is undergoes total internal reflection then returns a
list of two complex Fresnel coefficients:
[reflection p (TM), reflection s (TE)]
Examples
========
>>> from sympy.physics.optics import fresnel_coefficients
>>> fresnel_coefficients(0.3, 1, 2)
[0.317843553417859, -0.348645229818821,
0.658921776708929, 0.651354770181179]
>>> fresnel_coefficients(0.6, 2, 1)
[-0.235625382192159 - 0.971843958291041*I,
0.816477005968898 - 0.577377951366403*I]
References
==========
.. [1] https://en.wikipedia.org/wiki/Fresnel_equations
"""
if not 0 <= 2*angle_of_incidence < pi:
raise ValueError('Angle of incidence not in range [0:pi/2)')
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
try:
angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
except ValueError:
angle_of_total_internal_reflection_onset = None
if angle_of_total_internal_reflection_onset == None or\
angle_of_total_internal_reflection_onset > angle_of_incidence:
R_s = -sin(angle_of_incidence - angle_of_refraction)\
/sin(angle_of_incidence + angle_of_refraction)
R_p = tan(angle_of_incidence - angle_of_refraction)\
/tan(angle_of_incidence + angle_of_refraction)
T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
/sin(angle_of_incidence + angle_of_refraction)
T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
/(sin(angle_of_incidence + angle_of_refraction)\
*cos(angle_of_incidence - angle_of_refraction))
return [R_p, R_s, T_p, T_s]
else:
n = n2/n1
R_s = cancel((cos(angle_of_incidence)-\
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
/(cos(angle_of_incidence)+\
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
R_p = cancel((n**2*cos(angle_of_incidence)-\
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
/(n**2*cos(angle_of_incidence)+\
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
return [R_p, R_s]
def deviation(incident, medium1, medium2, normal=None, plane=None):
"""
This function calculates the angle of deviation of a ray
due to refraction at planar surface.
Parameters
==========
incident : Matrix, Ray3D, sequence or float
Incident vector or angle of incidence
medium1 : sympy.physics.optics.medium.Medium or sympifiable
Medium 1 or its refractive index
medium2 : sympy.physics.optics.medium.Medium or sympifiable
Medium 2 or its refractive index
normal : Matrix, Ray3D, or sequence
Normal vector
plane : Plane
Plane of separation of the two media.
Returns angular deviation between incident and refracted rays
Examples
========
>>> from sympy.physics.optics import deviation
>>> from sympy.geometry import Point3D, Ray3D, Plane
>>> from sympy.matrices import Matrix
>>> from sympy import symbols
>>> n1, n2 = symbols('n1, n2')
>>> n = Matrix([0, 0, 1])
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
>>> deviation(r1, 1, 1, n)
0
>>> deviation(r1, n1, n2, plane=P)
-acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
>>> round(deviation(0.1, 1.2, 1.5), 5)
-0.02005
"""
refracted = refraction_angle(incident,
medium1,
medium2,
normal=normal,
plane=plane)
try:
angle_of_incidence = Float(incident)
except TypeError:
angle_of_incidence = None
if angle_of_incidence is not None:
return float(refracted) - angle_of_incidence
if refracted != 0:
if isinstance(refracted, Ray3D):
refracted = Matrix(refracted.direction_ratio)
if not isinstance(incident, Matrix):
if is_sequence(incident):
_incident = Matrix(incident)
elif isinstance(incident, Ray3D):
_incident = Matrix(incident.direction_ratio)
else:
raise TypeError(
"incident should be a Matrix, Ray3D, or sequence")
else:
_incident = incident
if plane is None:
if not isinstance(normal, Matrix):
if is_sequence(normal):
_normal = Matrix(normal)
elif isinstance(normal, Ray3D):
_normal = Matrix(normal.direction_ratio)
else:
raise TypeError(
"normal should be a Matrix, Ray3D, or sequence")
else:
_normal = normal
else:
_normal = Matrix(plane.normal_vector)
mag_incident = sqrt(sum([i**2 for i in _incident]))
mag_normal = sqrt(sum([i**2 for i in _normal]))
mag_refracted = sqrt(sum([i**2 for i in refracted]))
_incident /= mag_incident
_normal /= mag_normal
refracted /= mag_refracted
i = acos(_incident.dot(_normal))
r = acos(refracted.dot(_normal))
return i - r
def brewster_angle(medium1, medium2):
"""
This function calculates the Brewster's angle of incidence to Medium 2 from
Medium 1 in radians.
Parameters
==========
medium 1 : Medium or sympifiable
Refractive index of Medium 1
medium 2 : Medium or sympifiable
Refractive index of Medium 1
Examples
========
>>> from sympy.physics.optics import brewster_angle
>>> brewster_angle(1, 1.33)
0.926093295503462
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
return atan2(n2, n1)
def critical_angle(medium1, medium2):
"""
This function calculates the critical angle of incidence (marking the onset
of total internal) to Medium 2 from Medium 1 in radians.
Parameters
==========
medium 1 : Medium or sympifiable
Refractive index of Medium 1.
medium 2 : Medium or sympifiable
Refractive index of Medium 1.
Examples
========
>>> from sympy.physics.optics import critical_angle
>>> critical_angle(1.33, 1)
0.850908514477849
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
if n2 > n1:
raise ValueError('Total internal reflection impossible for n1 < n2')
else:
return asin(n2/n1)
def lens_makers_formula(n_lens, n_surr, r1, r2):
"""
This function calculates focal length of a thin lens.
It follows cartesian sign convention.
Parameters
==========
n_lens : Medium or sympifiable
Index of refraction of lens.
n_surr : Medium or sympifiable
Index of reflection of surrounding.
r1 : sympifiable
Radius of curvature of first surface.
r2 : sympifiable
Radius of curvature of second surface.
Examples
========
>>> from sympy.physics.optics import lens_makers_formula
>>> lens_makers_formula(1.33, 1, 10, -10)
15.1515151515151
"""
if isinstance(n_lens, Medium):
n_lens = n_lens.refractive_index
else:
n_lens = sympify(n_lens)
if isinstance(n_surr, Medium):
n_surr = n_surr.refractive_index
else:
n_surr = sympify(n_surr)
r1 = sympify(r1)
r2 = sympify(r2)
return 1/((n_lens - n_surr)/n_surr*(1/r1 - 1/r2))
def mirror_formula(focal_length=None, u=None, v=None):
"""
This function provides one of the three parameters
when two of them are supplied.
This is valid only for paraxial rays.
Parameters
==========
focal_length : sympifiable
Focal length of the mirror.
u : sympifiable
Distance of object from the pole on
the principal axis.
v : sympifiable
Distance of the image from the pole
on the principal axis.
Examples
========
>>> from sympy.physics.optics import mirror_formula
>>> from sympy.abc import f, u, v
>>> mirror_formula(focal_length=f, u=u)
f*u/(-f + u)
>>> mirror_formula(focal_length=f, v=v)
f*v/(-f + v)
>>> mirror_formula(u=u, v=v)
u*v/(u + v)
"""
if focal_length and u and v:
raise ValueError("Please provide only two parameters")
focal_length = sympify(focal_length)
u = sympify(u)
v = sympify(v)
if u is oo:
_u = Symbol('u')
if v is oo:
_v = Symbol('v')
if focal_length is oo:
_f = Symbol('f')
if focal_length is None:
if u is oo and v is oo:
return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
if u is oo:
return Limit(v*_u/(v + _u), _u, oo).doit()
if v is oo:
return Limit(_v*u/(_v + u), _v, oo).doit()
return v*u/(v + u)
if u is None:
if v is oo and focal_length is oo:
return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
if v is oo:
return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
if focal_length is oo:
return Limit(v*_f/(v - _f), _f, oo).doit()
return v*focal_length/(v - focal_length)
if v is None:
if u is oo and focal_length is oo:
return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
if u is oo:
return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
if focal_length is oo:
return Limit(u*_f/(u - _f), _f, oo).doit()
return u*focal_length/(u - focal_length)
def lens_formula(focal_length=None, u=None, v=None):
"""
This function provides one of the three parameters
when two of them are supplied.
This is valid only for paraxial rays.
Parameters
==========
focal_length : sympifiable
Focal length of the mirror.
u : sympifiable
Distance of object from the optical center on
the principal axis.
v : sympifiable
Distance of the image from the optical center
on the principal axis.
Examples
========
>>> from sympy.physics.optics import lens_formula
>>> from sympy.abc import f, u, v
>>> lens_formula(focal_length=f, u=u)
f*u/(f + u)
>>> lens_formula(focal_length=f, v=v)
f*v/(f - v)
>>> lens_formula(u=u, v=v)
u*v/(u - v)
"""
if focal_length and u and v:
raise ValueError("Please provide only two parameters")
focal_length = sympify(focal_length)
u = sympify(u)
v = sympify(v)
if u is oo:
_u = Symbol('u')
if v is oo:
_v = Symbol('v')
if focal_length is oo:
_f = Symbol('f')
if focal_length is None:
if u is oo and v is oo:
return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
if u is oo:
return Limit(v*_u/(_u - v), _u, oo).doit()
if v is oo:
return Limit(_v*u/(u - _v), _v, oo).doit()
return v*u/(u - v)
if u is None:
if v is oo and focal_length is oo:
return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
if v is oo:
return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
if focal_length is oo:
return Limit(v*_f/(_f - v), _f, oo).doit()
return v*focal_length/(focal_length - v)
if v is None:
if u is oo and focal_length is oo:
return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
if u is oo:
return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
if focal_length is oo:
return Limit(u*_f/(u + _f), _f, oo).doit()
return u*focal_length/(u + focal_length)
def hyperfocal_distance(f, N, c):
"""
Parameters
==========
f: sympifiable
Focal length of a given lens.
N: sympifiable
F-number of a given lens.
c: sympifiable
Circle of Confusion (CoC) of a given image format.
Example
=======
>>> from sympy.physics.optics import hyperfocal_distance
>>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
9.47
"""
f = sympify(f)
N = sympify(N)
c = sympify(c)
return (1/(N * c))*(f**2)
def transverse_magnification(si, so):
"""
Calculates the transverse magnification, which is the ratio of the
image size to the object size.
Parameters
==========
so: sympifiable
Lens-object distance.
si: sympifiable
Lens-image distance.
Example
=======
>>> from sympy.physics.optics import transverse_magnification
>>> transverse_magnification(30, 15)
-2
"""
si = sympify(si)
so = sympify(so)
return (-(si/so))
|
78eb4155332fd37d02e248becdea66028a4fdb60c34b6fc57222f67eb4917082 | """
This module has all the classes and functions related to waves in optics.
**Contains**
* TWave
"""
__all__ = ['TWave']
from sympy import (sympify, pi, sin, cos, sqrt, Symbol, S,
symbols, Derivative, atan2)
from sympy.core.expr import Expr
from sympy.physics.units import speed_of_light, meter, second
c = speed_of_light.convert_to(meter/second)
class TWave(Expr):
r"""
This is a simple transverse sine wave travelling in a one-dimensional space.
Basic properties are required at the time of creation of the object,
but they can be changed later with respective methods provided.
Explanation
===========
It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
where :math:`A` is the amplitude, :math:`\omega` is the angular velocity,
:math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
to represent the position on the dimension on which the wave propagates,
and :math:`\phi` is the phase angle of the wave.
Arguments
=========
amplitude : Sympifyable
Amplitude of the wave.
frequency : Sympifyable
Frequency of the wave.
phase : Sympifyable
Phase angle of the wave.
time_period : Sympifyable
Time period of the wave.
n : Sympifyable
Refractive index of the medium.
Raises
=======
ValueError : When neither frequency nor time period is provided
or they are not consistent.
TypeError : When anything other than TWave objects is added.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
>>> w1 = TWave(A1, f, phi1)
>>> w2 = TWave(A2, f, phi2)
>>> w3 = w1 + w2 # Superposition of two waves
>>> w3
TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2)))
>>> w3.amplitude
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
>>> w3.phase
atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2))
>>> w3.speed
299792458*meter/(second*n)
>>> w3.angular_velocity
2*pi*f
"""
def __init__(
self,
amplitude,
frequency=None,
phase=S.Zero,
time_period=None,
n=Symbol('n')):
frequency = sympify(frequency)
amplitude = sympify(amplitude)
phase = sympify(phase)
time_period = sympify(time_period)
n = sympify(n)
self._frequency = frequency
self._amplitude = amplitude
self._phase = phase
self._time_period = time_period
self._n = n
if time_period is not None:
self._frequency = 1/self._time_period
if frequency is not None:
self._time_period = 1/self._frequency
if time_period is not None:
if frequency != 1/time_period:
raise ValueError("frequency and time_period should be consistent.")
if frequency is None and time_period is None:
raise ValueError("Either frequency or time period is needed.")
@property
def frequency(self):
"""
Returns the frequency of the wave,
in cycles per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.frequency
f
"""
return self._frequency
@property
def time_period(self):
"""
Returns the temporal period of the wave,
in seconds per cycle.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.time_period
1/f
"""
return self._time_period
@property
def wavelength(self):
"""
Returns the wavelength (spatial period) of the wave,
in meters per cycle.
It depends on the medium of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
299792458*meter/(second*f*n)
"""
return c/(self._frequency*self._n)
@property
def amplitude(self):
"""
Returns the amplitude of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.amplitude
A
"""
return self._amplitude
@property
def phase(self):
"""
Returns the phase angle of the wave,
in radians.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.phase
phi
"""
return self._phase
@property
def speed(self):
"""
Returns the propagation speed of the wave,
in meters per second.
It is dependent on the propagation medium.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
299792458*meter/(second*n)
"""
return self.wavelength*self._frequency
@property
def angular_velocity(self):
"""
Returns the angular velocity of the wave,
in radians per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.angular_velocity
2*pi*f
"""
return 2*pi*self._frequency
@property
def wavenumber(self):
"""
Returns the wavenumber of the wave,
in radians per meter.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavenumber
pi*second*f*n/(149896229*meter)
"""
return 2*pi/self.wavelength
def __str__(self):
"""String representation of a TWave."""
from sympy.printing import sstr
return type(self).__name__ + sstr(self.args)
__repr__ = __str__
def __add__(self, other):
"""
Addition of two waves will result in their superposition.
The type of interference will depend on their phase angles.
"""
if isinstance(other, TWave):
if self._frequency == other._frequency and self.wavelength == other.wavelength:
return TWave(sqrt(self._amplitude**2 + other._amplitude**2 + 2 *
self.amplitude*other.amplitude*cos(
self._phase - other.phase)),
self.frequency,
atan2(self._amplitude*cos(self._phase)
+other._amplitude*cos(other._phase),
self._amplitude*sin(self._phase)
+other._amplitude*sin(other._phase))
)
else:
raise NotImplementedError("Interference of waves with different frequencies"
" has not been implemented.")
else:
raise TypeError(type(other).__name__ + " and TWave objects can't be added.")
def _eval_rewrite_as_sin(self, *args, **kwargs):
return self._amplitude*sin(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
def _eval_rewrite_as_cos(self, *args, **kwargs):
return self._amplitude*cos(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase)
def _eval_rewrite_as_pde(self, *args, **kwargs):
from sympy import Function
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
E = Function('E')
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
def _eval_rewrite_as_exp(self, *args, **kwargs):
from sympy import exp, I
return self._amplitude*exp(I*(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase))
|
e24496983b0f6553aa0f10f7df3b589a5f342fbf8e62eaa24d5dcd9bf1938cdf | """
Gaussian optics.
The module implements:
- Ray transfer matrices for geometrical and gaussian optics.
See RayTransferMatrix, GeometricRay and BeamParameter
- Conjugation relations for geometrical and gaussian optics.
See geometric_conj*, gauss_conj and conjugate_gauss_beams
The conventions for the distances are as follows:
focal distance
positive for convergent lenses
object distance
positive for real objects
image distance
positive for real images
"""
__all__ = [
'RayTransferMatrix',
'FreeSpace',
'FlatRefraction',
'CurvedRefraction',
'FlatMirror',
'CurvedMirror',
'ThinLens',
'GeometricRay',
'BeamParameter',
'waist2rayleigh',
'rayleigh2waist',
'geometric_conj_ab',
'geometric_conj_af',
'geometric_conj_bf',
'gaussian_conj',
'conjugate_gauss_beams',
]
from sympy import (atan2, Expr, I, im, Matrix, pi, re, sqrt, sympify,
together, MutableDenseMatrix)
from sympy.utilities.misc import filldedent
###
# A, B, C, D matrices
###
class RayTransferMatrix(MutableDenseMatrix):
"""
Base class for a Ray Transfer Matrix.
It should be used if there isn't already a more specific subclass mentioned
in See Also.
Parameters
==========
parameters :
A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix, ThinLens
>>> from sympy import Symbol, Matrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat
Matrix([
[1, 2],
[3, 4]])
>>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
Matrix([
[1, 2],
[3, 4]])
>>> mat.A
1
>>> f = Symbol('f')
>>> lens = ThinLens(f)
>>> lens
Matrix([
[ 1, 0],
[-1/f, 1]])
>>> lens.C
-1/f
See Also
========
GeometricRay, BeamParameter,
FreeSpace, FlatRefraction, CurvedRefraction,
FlatMirror, CurvedMirror, ThinLens
References
==========
.. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
"""
def __new__(cls, *args):
if len(args) == 4:
temp = ((args[0], args[1]), (args[2], args[3]))
elif len(args) == 1 \
and isinstance(args[0], Matrix) \
and args[0].shape == (2, 2):
temp = args[0]
else:
raise ValueError(filldedent('''
Expecting 2x2 Matrix or the 4 elements of
the Matrix but got %s''' % str(args)))
return Matrix.__new__(cls, temp)
def __mul__(self, other):
if isinstance(other, RayTransferMatrix):
return RayTransferMatrix(Matrix.__mul__(self, other))
elif isinstance(other, GeometricRay):
return GeometricRay(Matrix.__mul__(self, other))
elif isinstance(other, BeamParameter):
temp = self*Matrix(((other.q,), (1,)))
q = (temp[0]/temp[1]).expand(complex=True)
return BeamParameter(other.wavelen,
together(re(q)),
z_r=together(im(q)))
else:
return Matrix.__mul__(self, other)
@property
def A(self):
"""
The A parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.A
1
"""
return self[0, 0]
@property
def B(self):
"""
The B parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.B
2
"""
return self[0, 1]
@property
def C(self):
"""
The C parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.C
3
"""
return self[1, 0]
@property
def D(self):
"""
The D parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.D
4
"""
return self[1, 1]
class FreeSpace(RayTransferMatrix):
"""
Ray Transfer Matrix for free space.
Parameters
==========
distance
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FreeSpace
>>> from sympy import symbols
>>> d = symbols('d')
>>> FreeSpace(d)
Matrix([
[1, d],
[0, 1]])
"""
def __new__(cls, d):
return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
class FlatRefraction(RayTransferMatrix):
"""
Ray Transfer Matrix for refraction.
Parameters
==========
n1 :
Refractive index of one medium.
n2 :
Refractive index of other medium.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FlatRefraction
>>> from sympy import symbols
>>> n1, n2 = symbols('n1 n2')
>>> FlatRefraction(n1, n2)
Matrix([
[1, 0],
[0, n1/n2]])
"""
def __new__(cls, n1, n2):
n1, n2 = map(sympify, (n1, n2))
return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
class CurvedRefraction(RayTransferMatrix):
"""
Ray Transfer Matrix for refraction on curved interface.
Parameters
==========
R :
Radius of curvature (positive for concave).
n1 :
Refractive index of one medium.
n2 :
Refractive index of other medium.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import CurvedRefraction
>>> from sympy import symbols
>>> R, n1, n2 = symbols('R n1 n2')
>>> CurvedRefraction(R, n1, n2)
Matrix([
[ 1, 0],
[(n1 - n2)/(R*n2), n1/n2]])
"""
def __new__(cls, R, n1, n2):
R, n1, n2 = map(sympify, (R, n1, n2))
return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
class FlatMirror(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FlatMirror
>>> FlatMirror()
Matrix([
[1, 0],
[0, 1]])
"""
def __new__(cls):
return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
class CurvedMirror(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection from curved surface.
Parameters
==========
R : radius of curvature (positive for concave)
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import CurvedMirror
>>> from sympy import symbols
>>> R = symbols('R')
>>> CurvedMirror(R)
Matrix([
[ 1, 0],
[-2/R, 1]])
"""
def __new__(cls, R):
R = sympify(R)
return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
class ThinLens(RayTransferMatrix):
"""
Ray Transfer Matrix for a thin lens.
Parameters
==========
f :
The focal distance.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import ThinLens
>>> from sympy import symbols
>>> f = symbols('f')
>>> ThinLens(f)
Matrix([
[ 1, 0],
[-1/f, 1]])
"""
def __new__(cls, f):
f = sympify(f)
return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
###
# Representation for geometric ray
###
class GeometricRay(MutableDenseMatrix):
"""
Representation for a geometric ray in the Ray Transfer Matrix formalism.
Parameters
==========
h : height, and
angle : angle, or
matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
Examples
========
>>> from sympy.physics.optics import GeometricRay, FreeSpace
>>> from sympy import symbols, Matrix
>>> d, h, angle = symbols('d, h, angle')
>>> GeometricRay(h, angle)
Matrix([
[ h],
[angle]])
>>> FreeSpace(d)*GeometricRay(h, angle)
Matrix([
[angle*d + h],
[ angle]])
>>> GeometricRay( Matrix( ((h,), (angle,)) ) )
Matrix([
[ h],
[angle]])
See Also
========
RayTransferMatrix
"""
def __new__(cls, *args):
if len(args) == 1 and isinstance(args[0], Matrix) \
and args[0].shape == (2, 1):
temp = args[0]
elif len(args) == 2:
temp = ((args[0],), (args[1],))
else:
raise ValueError(filldedent('''
Expecting 2x1 Matrix or the 2 elements of
the Matrix but got %s''' % str(args)))
return Matrix.__new__(cls, temp)
@property
def height(self):
"""
The distance from the optical axis.
Examples
========
>>> from sympy.physics.optics import GeometricRay
>>> from sympy import symbols
>>> h, angle = symbols('h, angle')
>>> gRay = GeometricRay(h, angle)
>>> gRay.height
h
"""
return self[0]
@property
def angle(self):
"""
The angle with the optical axis.
Examples
========
>>> from sympy.physics.optics import GeometricRay
>>> from sympy import symbols
>>> h, angle = symbols('h, angle')
>>> gRay = GeometricRay(h, angle)
>>> gRay.angle
angle
"""
return self[1]
###
# Representation for gauss beam
###
class BeamParameter(Expr):
"""
Representation for a gaussian ray in the Ray Transfer Matrix formalism.
Parameters
==========
wavelen : the wavelength,
z : the distance to waist, and
w : the waist, or
z_r : the rayleigh range.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.q
1 + 1.88679245283019*I*pi
>>> p.q.n()
1.0 + 5.92753330865999*I
>>> p.w_0.n()
0.00100000000000000
>>> p.z_r.n()
5.92753330865999
>>> from sympy.physics.optics import FreeSpace
>>> fs = FreeSpace(10)
>>> p1 = fs*p
>>> p.w.n()
0.00101413072159615
>>> p1.w.n()
0.00210803120913829
See Also
========
RayTransferMatrix
References
==========
.. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter
.. [2] https://en.wikipedia.org/wiki/Gaussian_beam
"""
#TODO A class Complex may be implemented. The BeamParameter may
# subclass it. See:
# https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
def __new__(cls, wavelen, z, z_r=None, w=None):
wavelen = sympify(wavelen)
z = sympify(z)
if z_r is not None and w is None:
z_r = sympify(z_r)
elif w is not None and z_r is None:
z_r = waist2rayleigh(sympify(w), wavelen)
else:
raise ValueError('Constructor expects exactly one named argument.')
return Expr.__new__(cls, wavelen, z, z_r)
@property
def wavelen(self):
return self.args[0]
@property
def z(self):
return self.args[1]
@property
def z_r(self):
return self.args[2]
@property
def q(self):
"""
The complex parameter representing the beam.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.q
1 + 1.88679245283019*I*pi
"""
return self.z + I*self.z_r
@property
def radius(self):
"""
The radius of curvature of the phase front.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.radius
1 + 3.55998576005696*pi**2
"""
return self.z*(1 + (self.z_r/self.z)**2)
@property
def w(self):
"""
The beam radius at `1/e^2` intensity.
See Also
========
w_0 :
The minimal radius of beam.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.w
0.001*sqrt(0.2809/pi**2 + 1)
"""
return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
@property
def w_0(self):
"""
The beam waist (minimal radius).
See Also
========
w : the beam radius at `1/e^2` intensity
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.w_0
0.00100000000000000
"""
return sqrt(self.z_r/pi*self.wavelen)
@property
def divergence(self):
"""
Half of the total angular spread.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.divergence
0.00053/pi
"""
return self.wavelen/pi/self.w_0
@property
def gouy(self):
"""
The Gouy phase.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.gouy
atan(0.53/pi)
"""
return atan2(self.z, self.z_r)
@property
def waist_approximation_limit(self):
"""
The minimal waist for which the gauss beam approximation is valid.
Explanation
===========
The gauss beam is a solution to the paraxial equation. For curvatures
that are too great it is not a valid approximation.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.waist_approximation_limit
1.06e-6/pi
"""
return 2*self.wavelen/pi
###
# Utilities
###
def waist2rayleigh(w, wavelen):
"""
Calculate the rayleigh range from the waist of a gaussian beam.
See Also
========
rayleigh2waist, BeamParameter
Examples
========
>>> from sympy.physics.optics import waist2rayleigh
>>> from sympy import symbols
>>> w, wavelen = symbols('w wavelen')
>>> waist2rayleigh(w, wavelen)
pi*w**2/wavelen
"""
w, wavelen = map(sympify, (w, wavelen))
return w**2*pi/wavelen
def rayleigh2waist(z_r, wavelen):
"""Calculate the waist from the rayleigh range of a gaussian beam.
See Also
========
waist2rayleigh, BeamParameter
Examples
========
>>> from sympy.physics.optics import rayleigh2waist
>>> from sympy import symbols
>>> z_r, wavelen = symbols('z_r wavelen')
>>> rayleigh2waist(z_r, wavelen)
sqrt(wavelen*z_r)/sqrt(pi)
"""
z_r, wavelen = map(sympify, (z_r, wavelen))
return sqrt(z_r/pi*wavelen)
def geometric_conj_ab(a, b):
"""
Conjugation relation for geometrical beams under paraxial conditions.
Explanation
===========
Takes the distances to the optical element and returns the needed
focal distance.
See Also
========
geometric_conj_af, geometric_conj_bf
Examples
========
>>> from sympy.physics.optics import geometric_conj_ab
>>> from sympy import symbols
>>> a, b = symbols('a b')
>>> geometric_conj_ab(a, b)
a*b/(a + b)
"""
a, b = map(sympify, (a, b))
if a.is_infinite or b.is_infinite:
return a if b.is_infinite else b
else:
return a*b/(a + b)
def geometric_conj_af(a, f):
"""
Conjugation relation for geometrical beams under paraxial conditions.
Explanation
===========
Takes the object distance (for geometric_conj_af) or the image distance
(for geometric_conj_bf) to the optical element and the focal distance.
Then it returns the other distance needed for conjugation.
See Also
========
geometric_conj_ab
Examples
========
>>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
>>> from sympy import symbols
>>> a, b, f = symbols('a b f')
>>> geometric_conj_af(a, f)
a*f/(a - f)
>>> geometric_conj_bf(b, f)
b*f/(b - f)
"""
a, f = map(sympify, (a, f))
return -geometric_conj_ab(a, -f)
geometric_conj_bf = geometric_conj_af
def gaussian_conj(s_in, z_r_in, f):
"""
Conjugation relation for gaussian beams.
Parameters
==========
s_in :
The distance to optical element from the waist.
z_r_in :
The rayleigh range of the incident beam.
f :
The focal length of the optical element.
Returns
=======
a tuple containing (s_out, z_r_out, m)
s_out :
The distance between the new waist and the optical element.
z_r_out :
The rayleigh range of the emergent beam.
m :
The ration between the new and the old waists.
Examples
========
>>> from sympy.physics.optics import gaussian_conj
>>> from sympy import symbols
>>> s_in, z_r_in, f = symbols('s_in z_r_in f')
>>> gaussian_conj(s_in, z_r_in, f)[0]
1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
>>> gaussian_conj(s_in, z_r_in, f)[1]
z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
>>> gaussian_conj(s_in, z_r_in, f)[2]
1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
"""
s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
return (s_out, z_r_out, m)
def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
"""
Find the optical setup conjugating the object/image waists.
Parameters
==========
wavelen :
The wavelength of the beam.
waist_in and waist_out :
The waists to be conjugated.
f :
The focal distance of the element used in the conjugation.
Returns
=======
a tuple containing (s_in, s_out, f)
s_in :
The distance before the optical element.
s_out :
The distance after the optical element.
f :
The focal distance of the optical element.
Examples
========
>>> from sympy.physics.optics import conjugate_gauss_beams
>>> from sympy import symbols, factor
>>> l, w_i, w_o, f = symbols('l w_i w_o f')
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))
>>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
pi**2*w_i**4/(f**2*l**2)))/w_i**2
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
f
"""
#TODO add the other possible arguments
wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
m = waist_out / waist_in
z = waist2rayleigh(waist_in, wavelen)
if len(kwargs) != 1:
raise ValueError("The function expects only one named argument")
elif 'dist' in kwargs:
raise NotImplementedError(filldedent('''
Currently only focal length is supported as a parameter'''))
elif 'f' in kwargs:
f = sympify(kwargs['f'])
s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
s_out = gaussian_conj(s_in, z, f)[0]
elif 's_in' in kwargs:
raise NotImplementedError(filldedent('''
Currently only focal length is supported as a parameter'''))
else:
raise ValueError(filldedent('''
The functions expects the focal length as a named argument'''))
return (s_in, s_out, f)
#TODO
#def plot_beam():
# """Plot the beam radius as it propagates in space."""
# pass
#TODO
#def plot_beam_conjugation():
# """
# Plot the intersection of two beams.
#
# Represents the conjugation relation.
#
# See Also
# ========
#
# conjugate_gauss_beams
# """
# pass
|
aa74d43d4fb6f4a9c1ee786e6ac2300daa986bff57596de0635676346a4dd907 | # -*- encoding: utf-8 -*-
"""
TODO:
* Address Issue 2251, printing of spin states
"""
from typing import Dict, Any
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate
from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.qubit import Qubit, IntQubit
from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD
from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.sho1d import RaisingOp
from sympy import Derivative, Function, Interval, Matrix, Pow, S, symbols, Symbol, oo
from sympy.testing.pytest import XFAIL
# Imports used in srepr strings
from sympy.physics.quantum.spin import JzOp
from sympy.printing import srepr
from sympy.printing.pretty import pretty as xpretty
from sympy.printing.latex import latex
MutableDenseMatrix = Matrix
ENV = {} # type: Dict[str, Any]
exec('from sympy import *', ENV)
exec('from sympy.physics.quantum import *', ENV)
exec('from sympy.physics.quantum.cg import *', ENV)
exec('from sympy.physics.quantum.spin import *', ENV)
exec('from sympy.physics.quantum.hilbert import *', ENV)
exec('from sympy.physics.quantum.qubit import *', ENV)
exec('from sympy.physics.quantum.qexpr import *', ENV)
exec('from sympy.physics.quantum.gate import *', ENV)
exec('from sympy.physics.quantum.constants import *', ENV)
def sT(expr, string):
"""
sT := sreprTest
from sympy/printing/tests/test_repr.py
"""
assert srepr(expr) == string
assert eval(string, ENV) == expr
def pretty(expr):
"""ASCII pretty-printing"""
return xpretty(expr, use_unicode=False, wrap_line=False)
def upretty(expr):
"""Unicode pretty-printing"""
return xpretty(expr, use_unicode=True, wrap_line=False)
def test_anticommutator():
A = Operator('A')
B = Operator('B')
ac = AntiCommutator(A, B)
ac_tall = AntiCommutator(A**2, B)
assert str(ac) == '{A,B}'
assert pretty(ac) == '{A,B}'
assert upretty(ac) == '{A,B}'
assert latex(ac) == r'\left\{A,B\right\}'
sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(ac_tall) == '{A**2,B}'
ascii_str = \
"""\
/ 2 \\\n\
<A ,B>\n\
\\ /\
"""
ucode_str = \
"""\
⎧ 2 ⎫\n\
⎨A ,B⎬\n\
⎩ ⎭\
"""
assert pretty(ac_tall) == ascii_str
assert upretty(ac_tall) == ucode_str
assert latex(ac_tall) == r'\left\{A^{2},B\right\}'
sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_cg():
cg = CG(1, 2, 3, 4, 5, 6)
wigner3j = Wigner3j(1, 2, 3, 4, 5, 6)
wigner6j = Wigner6j(1, 2, 3, 4, 5, 6)
wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)
assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
ucode_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
assert pretty(cg) == ascii_str
assert upretty(cg) == ucode_str
assert latex(cg) == r'C^{5,6}_{1,2,3,4}'
sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 3 5\\\n\
| |\n\
\\2 4 6/\
"""
ucode_str = \
"""\
⎛1 3 5⎞\n\
⎜ ⎟\n\
⎝2 4 6⎠\
"""
assert pretty(wigner3j) == ascii_str
assert upretty(wigner3j) == ucode_str
assert latex(wigner3j) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)'
sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 2 3\\\n\
< >\n\
\\4 5 6/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎨ ⎬\n\
⎩4 5 6⎭\
"""
assert pretty(wigner6j) == ascii_str
assert upretty(wigner6j) == ucode_str
assert latex(wigner6j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}'
sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)'
ascii_str = \
"""\
/1 2 3\\\n\
| |\n\
<4 5 6>\n\
| |\n\
\\7 8 9/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎪ ⎪\n\
⎨4 5 6⎬\n\
⎪ ⎪\n\
⎩7 8 9⎭\
"""
assert pretty(wigner9j) == ascii_str
assert upretty(wigner9j) == ucode_str
assert latex(wigner9j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}'
sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))")
def test_commutator():
A = Operator('A')
B = Operator('B')
c = Commutator(A, B)
c_tall = Commutator(A**2, B)
assert str(c) == '[A,B]'
assert pretty(c) == '[A,B]'
assert upretty(c) == '[A,B]'
assert latex(c) == r'\left[A,B\right]'
sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(c_tall) == '[A**2,B]'
ascii_str = \
"""\
[ 2 ]\n\
[A ,B]\
"""
ucode_str = \
"""\
⎡ 2 ⎤\n\
⎣A ,B⎦\
"""
assert pretty(c_tall) == ascii_str
assert upretty(c_tall) == ucode_str
assert latex(c_tall) == r'\left[A^{2},B\right]'
sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_constants():
assert str(hbar) == 'hbar'
assert pretty(hbar) == 'hbar'
assert upretty(hbar) == 'ℏ'
assert latex(hbar) == r'\hbar'
sT(hbar, "HBar()")
def test_dagger():
x = symbols('x')
expr = Dagger(x)
assert str(expr) == 'Dagger(x)'
ascii_str = \
"""\
+\n\
x \
"""
ucode_str = \
"""\
†\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
assert latex(expr) == r'x^{\dagger}'
sT(expr, "Dagger(Symbol('x'))")
@XFAIL
def test_gate_failing():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
g = UGate((0,), uMat)
assert str(g) == 'U(0)'
def test_gate():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
q = Qubit(1, 0, 1, 0, 1)
g1 = IdentityGate(2)
g2 = CGate((3, 0), XGate(1))
g3 = CNotGate(1, 0)
g4 = UGate((0,), uMat)
assert str(g1) == '1(2)'
assert pretty(g1) == '1 \n 2'
assert upretty(g1) == '1 \n 2'
assert latex(g1) == r'1_{2}'
sT(g1, "IdentityGate(Integer(2))")
assert str(g1*q) == '1(2)*|10101>'
ascii_str = \
"""\
1 *|10101>\n\
2 \
"""
ucode_str = \
"""\
1 ⋅❘10101⟩\n\
2 \
"""
assert pretty(g1*q) == ascii_str
assert upretty(g1*q) == ucode_str
assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }'
sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))")
assert str(g2) == 'C((3,0),X(1))'
ascii_str = \
"""\
C /X \\\n\
3,0\\ 1/\
"""
ucode_str = \
"""\
C ⎛X ⎞\n\
3,0⎝ 1⎠\
"""
assert pretty(g2) == ascii_str
assert upretty(g2) == ucode_str
assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}'
sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))")
assert str(g3) == 'CNOT(1,0)'
ascii_str = \
"""\
CNOT \n\
1,0\
"""
ucode_str = \
"""\
CNOT \n\
1,0\
"""
assert pretty(g3) == ascii_str
assert upretty(g3) == ucode_str
assert latex(g3) == r'CNOT_{1,0}'
sT(g3, "CNotGate(Integer(1),Integer(0))")
ascii_str = \
"""\
U \n\
0\
"""
ucode_str = \
"""\
U \n\
0\
"""
assert str(g4) == \
"""\
U((0,),Matrix([\n\
[a, b],\n\
[c, d]]))\
"""
assert pretty(g4) == ascii_str
assert upretty(g4) == ucode_str
assert latex(g4) == r'U_{0}'
sT(g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))")
def test_hilbert():
h1 = HilbertSpace()
h2 = ComplexSpace(2)
h3 = FockSpace()
h4 = L2(Interval(0, oo))
assert str(h1) == 'H'
assert pretty(h1) == 'H'
assert upretty(h1) == 'H'
assert latex(h1) == r'\mathcal{H}'
sT(h1, "HilbertSpace()")
assert str(h2) == 'C(2)'
ascii_str = \
"""\
2\n\
C \
"""
ucode_str = \
"""\
2\n\
C \
"""
assert pretty(h2) == ascii_str
assert upretty(h2) == ucode_str
assert latex(h2) == r'\mathcal{C}^{2}'
sT(h2, "ComplexSpace(Integer(2))")
assert str(h3) == 'F'
assert pretty(h3) == 'F'
assert upretty(h3) == 'F'
assert latex(h3) == r'\mathcal{F}'
sT(h3, "FockSpace()")
assert str(h4) == 'L2(Interval(0, oo))'
ascii_str = \
"""\
2\n\
L \
"""
ucode_str = \
"""\
2\n\
L \
"""
assert pretty(h4) == ascii_str
assert upretty(h4) == ucode_str
assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)'
sT(h4, "L2(Interval(Integer(0), oo, false, true))")
assert str(h1 + h2) == 'H+C(2)'
ascii_str = \
"""\
2\n\
H + C \
"""
ucode_str = \
"""\
2\n\
H ⊕ C \
"""
assert pretty(h1 + h2) == ascii_str
assert upretty(h1 + h2) == ucode_str
assert latex(h1 + h2)
sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1*h2) == "H*C(2)"
ascii_str = \
"""\
2\n\
H x C \
"""
ucode_str = \
"""\
2\n\
H ⨂ C \
"""
assert pretty(h1*h2) == ascii_str
assert upretty(h1*h2) == ucode_str
assert latex(h1*h2)
sT(h1*h2,
"TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1**2) == 'H**2'
ascii_str = \
"""\
x2\n\
H \
"""
ucode_str = \
"""\
⨂2\n\
H \
"""
assert pretty(h1**2) == ascii_str
assert upretty(h1**2) == ucode_str
assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}'
sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))")
def test_innerproduct():
x = symbols('x')
ip1 = InnerProduct(Bra(), Ket())
ip2 = InnerProduct(TimeDepBra(), TimeDepKet())
ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1))
ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1)))
ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2))
ip_tall2 = InnerProduct(Bra(x), Ket(x/2))
ip_tall3 = InnerProduct(Bra(x/2), Ket(x))
assert str(ip1) == '<psi|psi>'
assert pretty(ip1) == '<psi|psi>'
assert upretty(ip1) == '⟨ψ❘ψ⟩'
assert latex(
ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }'
sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))")
assert str(ip2) == '<psi;t|psi;t>'
assert pretty(ip2) == '<psi;t|psi;t>'
assert upretty(ip2) == '⟨ψ;t❘ψ;t⟩'
assert latex(ip2) == \
r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }'
sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))")
assert str(ip3) == "<1,1|1,1>"
assert pretty(ip3) == '<1,1|1,1>'
assert upretty(ip3) == '⟨1,1❘1,1⟩'
assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }'
sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))")
assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>"
assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>'
assert upretty(ip4) == '⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩'
assert latex(ip4) == \
r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }'
sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))")
assert str(ip_tall1) == '<x/2|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ x|x \\\n\
\\ -|- /\n\
\\2|2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│x ╲\n\
╲ ─│─ ╱\n\
╲2│2╱ \
"""
assert pretty(ip_tall1) == ascii_str
assert upretty(ip_tall1) == ucode_str
assert latex(ip_tall1) == \
r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall2) == '<x|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ |x \\\n\
\\ x|- /\n\
\\ |2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ │x ╲\n\
╲ x│─ ╱\n\
╲ │2╱ \
"""
assert pretty(ip_tall2) == ascii_str
assert upretty(ip_tall2) == ucode_str
assert latex(ip_tall2) == \
r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall2,
"InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall3) == '<x/2|x>'
ascii_str = \
"""\
/ | \\ \n\
/ x| \\\n\
\\ -|x /\n\
\\2| / \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│ ╲\n\
╲ ─│x ╱\n\
╲2│ ╱ \
"""
assert pretty(ip_tall3) == ascii_str
assert upretty(ip_tall3) == ucode_str
assert latex(ip_tall3) == \
r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }'
sT(ip_tall3,
"InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))")
def test_operator():
a = Operator('A')
b = Operator('B', Symbol('t'), S.Half)
inv = a.inv()
f = Function('f')
x = symbols('x')
d = DifferentialOperator(Derivative(f(x), x), f(x))
op = OuterProduct(Ket(), Bra())
assert str(a) == 'A'
assert pretty(a) == 'A'
assert upretty(a) == 'A'
assert latex(a) == 'A'
sT(a, "Operator(Symbol('A'))")
assert str(inv) == 'A**(-1)'
ascii_str = \
"""\
-1\n\
A \
"""
ucode_str = \
"""\
-1\n\
A \
"""
assert pretty(inv) == ascii_str
assert upretty(inv) == ucode_str
assert latex(inv) == r'A^{-1}'
sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
ascii_str = \
"""\
/d \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
\\dx /\
"""
ucode_str = \
"""\
⎛d ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
⎝dx ⎠\
"""
assert pretty(d) == ascii_str
assert upretty(d) == ucode_str
assert latex(d) == \
r'DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)'
sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))")
assert str(b) == 'Operator(B,t,1/2)'
assert pretty(b) == 'Operator(B,t,1/2)'
assert upretty(b) == 'Operator(B,t,1/2)'
assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
assert str(op) == '|psi><psi|'
assert pretty(op) == '|psi><psi|'
assert upretty(op) == '❘ψ⟩⟨ψ❘'
assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
def test_qexpr():
q = QExpr('q')
assert str(q) == 'q'
assert pretty(q) == 'q'
assert upretty(q) == 'q'
assert latex(q) == r'q'
sT(q, "QExpr(Symbol('q'))")
def test_qubit():
q1 = Qubit('0101')
q2 = IntQubit(8)
assert str(q1) == '|0101>'
assert pretty(q1) == '|0101>'
assert upretty(q1) == '❘0101⟩'
assert latex(q1) == r'{\left|0101\right\rangle }'
sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
assert str(q2) == '|8>'
assert pretty(q2) == '|8>'
assert upretty(q2) == '❘8⟩'
assert latex(q2) == r'{\left|8\right\rangle }'
sT(q2, "IntQubit(8)")
def test_spin():
lz = JzOp('L')
ket = JzKet(1, 0)
bra = JzBra(1, 0)
cket = JzKetCoupled(1, 0, (1, 2))
cbra = JzBraCoupled(1, 0, (1, 2))
cket_big = JzKetCoupled(1, 0, (1, 2, 3))
cbra_big = JzBraCoupled(1, 0, (1, 2, 3))
rot = Rotation(1, 2, 3)
bigd = WignerD(1, 2, 3, 4, 5, 6)
smalld = WignerD(1, 2, 3, 0, 4, 0)
assert str(lz) == 'Lz'
ascii_str = \
"""\
L \n\
z\
"""
ucode_str = \
"""\
L \n\
z\
"""
assert pretty(lz) == ascii_str
assert upretty(lz) == ucode_str
assert latex(lz) == 'L_z'
sT(lz, "JzOp(Symbol('L'))")
assert str(J2) == 'J2'
ascii_str = \
"""\
2\n\
J \
"""
ucode_str = \
"""\
2\n\
J \
"""
assert pretty(J2) == ascii_str
assert upretty(J2) == ucode_str
assert latex(J2) == r'J^2'
sT(J2, "J2Op(Symbol('J'))")
assert str(Jz) == 'Jz'
ascii_str = \
"""\
J \n\
z\
"""
ucode_str = \
"""\
J \n\
z\
"""
assert pretty(Jz) == ascii_str
assert upretty(Jz) == ucode_str
assert latex(Jz) == 'J_z'
sT(Jz, "JzOp(Symbol('J'))")
assert str(ket) == '|1,0>'
assert pretty(ket) == '|1,0>'
assert upretty(ket) == '❘1,0⟩'
assert latex(ket) == r'{\left|1,0\right\rangle }'
sT(ket, "JzKet(Integer(1),Integer(0))")
assert str(bra) == '<1,0|'
assert pretty(bra) == '<1,0|'
assert upretty(bra) == '⟨1,0❘'
assert latex(bra) == r'{\left\langle 1,0\right|}'
sT(bra, "JzBra(Integer(1),Integer(0))")
assert str(cket) == '|1,0,j1=1,j2=2>'
assert pretty(cket) == '|1,0,j1=1,j2=2>'
assert upretty(cket) == '❘1,0,j₁=1,j₂=2⟩'
assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }'
sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cbra) == '<1,0,j1=1,j2=2|'
assert pretty(cbra) == '<1,0,j1=1,j2=2|'
assert upretty(cbra) == '⟨1,0,j₁=1,j₂=2❘'
assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}'
sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>'
# TODO: Fix non-unicode pretty printing
# i.e. j1,2 -> j(1,2)
assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>'
assert upretty(cket_big) == '❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩'
assert latex(cket_big) == \
r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }'
sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|'
assert pretty(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j1,2=3|'
assert upretty(cbra_big) == '⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘'
assert latex(cbra_big) == \
r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}'
sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(rot) == 'R(1,2,3)'
assert pretty(rot) == 'R (1,2,3)'
assert upretty(rot) == 'ℛ (1,2,3)'
assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)'
sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))")
assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
assert pretty(bigd) == ascii_str
assert upretty(bigd) == ucode_str
assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)'
sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)'
ascii_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
assert pretty(smalld) == ascii_str
assert upretty(smalld) == ucode_str
assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)'
sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))")
def test_state():
x = symbols('x')
bra = Bra()
ket = Ket()
bra_tall = Bra(x/2)
ket_tall = Ket(x/2)
tbra = TimeDepBra()
tket = TimeDepKet()
assert str(bra) == '<psi|'
assert pretty(bra) == '<psi|'
assert upretty(bra) == '⟨ψ❘'
assert latex(bra) == r'{\left\langle \psi\right|}'
sT(bra, "Bra(Symbol('psi'))")
assert str(ket) == '|psi>'
assert pretty(ket) == '|psi>'
assert upretty(ket) == '❘ψ⟩'
assert latex(ket) == r'{\left|\psi\right\rangle }'
sT(ket, "Ket(Symbol('psi'))")
assert str(bra_tall) == '<x/2|'
ascii_str = \
"""\
/ |\n\
/ x|\n\
\\ -|\n\
\\2|\
"""
ucode_str = \
"""\
╱ │\n\
╱ x│\n\
╲ ─│\n\
╲2│\
"""
assert pretty(bra_tall) == ascii_str
assert upretty(bra_tall) == ucode_str
assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}'
sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))")
assert str(ket_tall) == '|x/2>'
ascii_str = \
"""\
| \\ \n\
|x \\\n\
|- /\n\
|2/ \
"""
ucode_str = \
"""\
│ ╲ \n\
│x ╲\n\
│─ ╱\n\
│2╱ \
"""
assert pretty(ket_tall) == ascii_str
assert upretty(ket_tall) == ucode_str
assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }'
sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))")
assert str(tbra) == '<psi;t|'
assert pretty(tbra) == '<psi;t|'
assert upretty(tbra) == '⟨ψ;t❘'
assert latex(tbra) == r'{\left\langle \psi;t\right|}'
sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))")
assert str(tket) == '|psi;t>'
assert pretty(tket) == '|psi;t>'
assert upretty(tket) == '❘ψ;t⟩'
assert latex(tket) == r'{\left|\psi;t\right\rangle }'
sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))")
def test_tensorproduct():
tp = TensorProduct(JzKet(1, 1), JzKet(1, 0))
assert str(tp) == '|1,1>x|1,0>'
assert pretty(tp) == '|1,1>x |1,0>'
assert upretty(tp) == '❘1,1⟩⨂ ❘1,0⟩'
assert latex(tp) == \
r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}'
sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))")
def test_big_expr():
f = Function('f')
x = symbols('x')
e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1))
e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2))
e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1)))
e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval(
0, oo)) + HilbertSpace())
assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
ascii_str = \
"""\
/ 3 \\ \n\
|/ +\\ | \n\
2 / + +\\ <| /d \\ | + +> \n\
/J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
\\ z/ \\\\ \\dx / / / \
"""
ucode_str = \
"""\
⎧ 3 ⎫ \n\
⎪⎛ †⎞ ⎪ \n\
2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\
⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \
"""
assert pretty(e1) == ascii_str
assert upretty(e1) == ucode_str
assert latex(e1) == \
r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))")
assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
ascii_str = \
"""\
[ 2 ] / -2 + +\\ [ 2 ]\n\
[/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\
[\\ z/ ] \\ / [ z]\
"""
ucode_str = \
"""\
⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\
⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\
"""
assert pretty(e2) == ascii_str
assert upretty(e2) == ucode_str
assert latex(e2) == \
r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]'
sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))")
assert str(e3) == \
"Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
ascii_str = \
"""\
[ + ] / 2 \\ \n\
/1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
| | \\ z/ \n\
\\2 4 6/ \
"""
ucode_str = \
"""\
⎡ † ⎤ ⎛ 2 ⎞ \n\
⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
⎜ ⎟ ⎝ z⎠ \n\
⎝2 4 6⎠ \
"""
assert pretty(e3) == ascii_str
assert upretty(e3) == ucode_str
assert latex(e3) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))")
assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)'
ascii_str = \
"""\
// 1 2\\ x2\\ / 2 \\\n\
\\\\C x C / + F / x \\L + H/\
"""
ucode_str = \
"""\
⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\
⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\
"""
assert pretty(e4) == ascii_str
assert upretty(e4) == ucode_str
assert latex(e4) == \
r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))")
def _test_sho1d():
ad = RaisingOp('a')
assert pretty(ad) == ' \N{DAGGER}\na '
assert latex(ad) == 'a^{\\dagger}'
|
1aaf667f7a3f073b080770c19d22210abd7312d59a9b9c3e5947d5e7124069a9 | from sympy import (Abs, Add, Function, Number, Rational, S, Symbol,
diff, exp, integrate, log, sin, sqrt, symbols)
from sympy.physics.units import (amount_of_substance, convert_to, find_unit,
volume, kilometer, joule)
from sympy.physics.units.definitions import (amu, au, centimeter, coulomb,
day, foot, grams, hour, inch, kg, km, m, meter, millimeter,
minute, quart, s, second, speed_of_light, bit,
byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte,
kilogram, gravitational_constant)
from sympy.physics.units.definitions.dimension_definitions import (
Dimension, charge, length, time, temperature, pressure,
energy
)
from sympy.physics.units.prefixes import PREFIXES, kilo
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.systems import SI
from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy
k = PREFIXES["k"]
def test_str_repr():
assert str(kg) == "kilogram"
def test_eq():
# simple test
assert 10*m == 10*m
assert 10*m != 10*s
def test_convert_to():
q = Quantity("q1")
q.set_global_relative_scale_factor(S(5000), meter)
assert q.convert_to(m) == 5000*m
assert speed_of_light.convert_to(m / s) == 299792458 * m / s
# TODO: eventually support this kind of conversion:
# assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s
assert day.convert_to(s) == 86400*s
# Wrong dimension to convert:
assert q.convert_to(s) == q
assert speed_of_light.convert_to(m) == speed_of_light
expr = joule*second
conv = convert_to(expr, joule)
assert conv == joule*second
def test_Quantity_definition():
q = Quantity("s10", abbrev="sabbr")
q.set_global_relative_scale_factor(10, second)
u = Quantity("u", abbrev="dam")
u.set_global_relative_scale_factor(10, meter)
km = Quantity("km")
km.set_global_relative_scale_factor(kilo, meter)
v = Quantity("u")
v.set_global_relative_scale_factor(5*kilo, meter)
assert q.scale_factor == 10
assert q.dimension == time
assert q.abbrev == Symbol("sabbr")
assert u.dimension == length
assert u.scale_factor == 10
assert u.abbrev == Symbol("dam")
assert km.scale_factor == 1000
assert km.func(*km.args) == km
assert km.func(*km.args).args == km.args
assert v.dimension == length
assert v.scale_factor == 5000
with warns_deprecated_sympy():
Quantity('invalid', 'dimension', 1)
with warns_deprecated_sympy():
Quantity('mismatch', dimension=length, scale_factor=kg)
def test_abbrev():
u = Quantity("u")
u.set_global_relative_scale_factor(S.One, meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("u")
u = Quantity("u", abbrev="om")
u.set_global_relative_scale_factor(S(2), meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("om")
assert u.scale_factor == 2
assert isinstance(u.scale_factor, Number)
u = Quantity("u", abbrev="ikm")
u.set_global_relative_scale_factor(3*kilo, meter)
assert u.abbrev == Symbol("ikm")
assert u.scale_factor == 3000
def test_print():
u = Quantity("unitname", abbrev="dam")
assert repr(u) == "unitname"
assert str(u) == "unitname"
def test_Quantity_eq():
u = Quantity("u", abbrev="dam")
v = Quantity("v1")
assert u != v
v = Quantity("v2", abbrev="ds")
assert u != v
v = Quantity("v3", abbrev="dm")
assert u != v
def test_add_sub():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
assert isinstance(u + v, Add)
assert (u + v.convert_to(u)) == (1 + S.Half)*u
# TODO: eventually add this:
# assert (u + v).convert_to(u) == (1 + S.Half)*u
assert isinstance(u - v, Add)
assert (u - v.convert_to(u)) == S.Half*u
# TODO: eventually add this:
# assert (u - v).convert_to(u) == S.Half*u
def test_quantity_abs():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w3 = Quantity('v_w3')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
v_w3.set_global_relative_scale_factor(1, meter/second)
expr = v_w3 - Abs(v_w1 - v_w2)
assert SI.get_dimensional_expr(v_w1) == (length/time).name
Dq = Dimension(SI.get_dimensional_expr(expr))
with warns_deprecated_sympy():
Dq1 = Dimension(Quantity.get_dimensional_expr(expr))
assert Dq == Dq1
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': 1,
'time': -1,
}
assert meter == sqrt(meter**2)
def test_check_unit_consistency():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
def check_unit_consistency(expr):
SI._collect_factor_and_dimension(expr)
raises(ValueError, lambda: check_unit_consistency(u + w))
raises(ValueError, lambda: check_unit_consistency(u - w))
raises(ValueError, lambda: check_unit_consistency(u + 1))
raises(ValueError, lambda: check_unit_consistency(u - 1))
raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w)))
def test_mul_div():
u = Quantity("u")
v = Quantity("v")
t = Quantity("t")
ut = Quantity("ut")
v2 = Quantity("v")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
t.set_global_relative_scale_factor(S(2), second)
ut.set_global_relative_scale_factor(S(20), meter*second)
v2.set_global_relative_scale_factor(S(5), meter/second)
assert 1 / u == u**(-1)
assert u / 1 == u
v1 = u / t
v2 = v
# Pow only supports structural equality:
assert v1 != v2
assert v1 == v2.convert_to(v1)
# TODO: decide whether to allow such expression in the future
# (requires somehow manipulating the core).
# assert u / Quantity('l2', dimension=length, scale_factor=2) == 5
assert u * 1 == u
ut1 = u * t
ut2 = ut
# Mul only supports structural equality:
assert ut1 != ut2
assert ut1 == ut2.convert_to(ut1)
# Mul only supports structural equality:
lp1 = Quantity("lp1")
lp1.set_global_relative_scale_factor(S(2), 1/meter)
assert u * lp1 != 20
assert u**0 == 1
assert u**1 == u
# TODO: Pow only support structural equality:
u2 = Quantity("u2")
u3 = Quantity("u3")
u2.set_global_relative_scale_factor(S(100), meter**2)
u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter)
assert u ** 2 != u2
assert u ** -1 != u3
assert u ** 2 == u2.convert_to(u)
assert u ** -1 == u3.convert_to(u)
def test_units():
assert convert_to((5*m/s * day) / km, 1) == 432
assert convert_to(foot / meter, meter) == Rational(3048, 10000)
# amu is a pure mass so mass/mass gives a number, not an amount (mol)
# TODO: need better simplification routine:
assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23'
# Light from the sun needs about 8.3 minutes to reach earth
t = (1*au / speed_of_light) / minute
# TODO: need a better way to simplify expressions containing units:
t = convert_to(convert_to(t, meter / minute), meter)
assert t.simplify() == Rational(49865956897, 5995849160)
# TODO: fix this, it should give `m` without `Abs`
assert sqrt(m**2) == m
assert (sqrt(m))**2 == m
t = Symbol('t')
assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s
assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s
def test_issue_quart():
assert convert_to(4 * quart / inch ** 3, meter) == 231
assert convert_to(4 * quart / inch ** 3, millimeter) == 231
def test_issue_5565():
assert (m < s).is_Relational
def test_find_unit():
assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant']
assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(inch) == [
'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um',
'yd', 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles',
'yards', 'inches', 'meters', 'micron', 'microns', 'decimeter',
'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter',
'decimeters', 'kilometers', 'lightyears', 'micrometer', 'millimeter',
'nanometers', 'picometers', 'centimeters', 'micrometers',
'millimeters', 'nautical_mile', 'planck_length', 'nautical_miles', 'astronomical_unit',
'astronomical_units']
assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(inch ** 3) == [
'l', 'cl', 'dl', 'ml', 'liter', 'quart', 'liters', 'quarts',
'deciliter', 'centiliter', 'deciliters', 'milliliter',
'centiliters', 'milliliters', 'planck_volume']
assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage']
def test_Quantity_derivative():
x = symbols("x")
assert diff(x*meter, x) == meter
assert diff(x**3*meter**2, x) == 3*x**2*meter**2
assert diff(meter, meter) == 1
assert diff(meter**2, meter) == 2*meter
def test_quantity_postprocessing():
q1 = Quantity('q1')
q2 = Quantity('q2')
SI.set_quantity_dimension(q1, length*pressure**2*temperature/time)
SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time))
assert q1 + q2
q = q1 + q2
Dq = Dimension(SI.get_dimensional_expr(q))
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': -1,
'mass': 2,
'temperature': 1,
'time': -5,
}
def test_factor_and_dimension():
assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000)
assert (1001, length) == SI._collect_factor_and_dimension(meter + km)
assert (2, length/time) == SI._collect_factor_and_dimension(
meter/second + 36*km/(10*hour))
x, y = symbols('x y')
assert (x + y/100, length) == SI._collect_factor_and_dimension(
x*m + y*centimeter)
cH = Quantity('cH')
SI.set_quantity_dimension(cH, amount_of_substance/volume)
pH = -log(cH)
assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension(
exp(pH))
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
v_w2.set_global_relative_scale_factor(2, meter/second)
expr = Abs(v_w1/2 - v_w2)
assert (Rational(5, 4), length/time) == \
SI._collect_factor_and_dimension(expr)
expr = Rational(5, 2)*second/meter*v_w1 - 3000
assert (-(2996 + Rational(1, 4)), Dimension(1)) == \
SI._collect_factor_and_dimension(expr)
expr = v_w1**(v_w2/v_w1)
assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \
SI._collect_factor_and_dimension(expr)
with warns_deprecated_sympy():
assert (3000, Dimension(1)) == Quantity._collect_factor_and_dimension(3000)
@XFAIL
def test_factor_and_dimension_with_Abs():
with warns_deprecated_sympy():
v_w1 = Quantity('v_w1', length/time, Rational(3, 2)*meter/second)
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
expr = v_w1 - Abs(v_w1)
assert (0, length/time) == Quantity._collect_factor_and_dimension(expr)
def test_dimensional_expr_of_derivative():
l = Quantity('l')
t = Quantity('t')
t1 = Quantity('t1')
l.set_global_relative_scale_factor(36, km)
t.set_global_relative_scale_factor(1, hour)
t1.set_global_relative_scale_factor(1, second)
x = Symbol('x')
y = Symbol('y')
f = Function('f')
dfdx = f(x, y).diff(x, y)
dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1})
assert SI.get_dimensional_expr(dl_dt) ==\
SI.get_dimensional_expr(l / t / t1) ==\
Symbol("length")/Symbol("time")**2
assert SI._collect_factor_and_dimension(dl_dt) ==\
SI._collect_factor_and_dimension(l / t / t1) ==\
(10, length/time**2)
def test_get_dimensional_expr_with_function():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
assert SI.get_dimensional_expr(sin(v_w1)) == \
sin(SI.get_dimensional_expr(v_w1))
assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1
def test_binary_information():
assert convert_to(kibibyte, byte) == 1024*byte
assert convert_to(mebibyte, byte) == 1024**2*byte
assert convert_to(gibibyte, byte) == 1024**3*byte
assert convert_to(tebibyte, byte) == 1024**4*byte
assert convert_to(pebibyte, byte) == 1024**5*byte
assert convert_to(exbibyte, byte) == 1024**6*byte
assert kibibyte.convert_to(bit) == 8*1024*bit
assert byte.convert_to(bit) == 8*bit
a = 10*kibibyte*hour
assert convert_to(a, byte) == 10240*byte*hour
assert convert_to(a, minute) == 600*kibibyte*minute
assert convert_to(a, [byte, minute]) == 614400*byte*minute
def test_conversion_with_2_nonstandard_dimensions():
good_grade = Quantity("good_grade")
kilo_good_grade = Quantity("kilo_good_grade")
centi_good_grade = Quantity("centi_good_grade")
kilo_good_grade.set_global_relative_scale_factor(1000, good_grade)
centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade)
charity_points = Quantity("charity_points")
milli_charity_points = Quantity("milli_charity_points")
missions = Quantity("missions")
milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points)
missions.set_global_relative_scale_factor(251, charity_points)
assert convert_to(
kilo_good_grade*milli_charity_points*millimeter,
[centi_good_grade, missions, centimeter]
) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter
def test_eval_subs():
energy, mass, force = symbols('energy mass force')
expr1 = energy/mass
units = {energy: kilogram*meter**2/second**2, mass: kilogram}
assert expr1.subs(units) == meter**2/second**2
expr2 = force/mass
units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram}
assert expr2.subs(units) == gravitational_constant*kilogram/meter**2
def test_issue_14932():
assert (log(inch) - log(2)).simplify() == log(inch/2)
assert (log(inch) - log(foot)).simplify() == -log(12)
p = symbols('p', positive=True)
assert (log(inch) - log(p)).simplify() == log(inch/p)
def test_issue_14547():
# the root issue is that an argument with dimensions should
# not raise an error when the the `arg - 1` calculation is
# performed in the assumptions system
from sympy.physics.units import foot, inch
from sympy import Eq
assert log(foot).is_zero is None
assert log(foot).is_positive is None
assert log(foot).is_nonnegative is None
assert log(foot).is_negative is None
assert log(foot).is_algebraic is None
assert log(foot).is_rational is None
# doesn't raise error
assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated
x = Symbol('x')
e = foot + x
assert e.is_Add and set(e.args) == {foot, x}
e = foot + 1
assert e.is_Add and set(e.args) == {foot, 1}
def test_deprecated_quantity_methods():
step = Quantity("step")
with warns_deprecated_sympy():
step.set_dimension(length)
step.set_scale_factor(2*meter)
assert convert_to(step, centimeter) == 200*centimeter
assert convert_to(1000*step/second, kilometer/second) == 2*kilometer/second
|
bc844aba23cf33d4cb9fade803e469ce7fbb674039537b24fef34ee83d5e2968 | from sympy import Pow, Tuple, pi, sstr, sympify, symbols
from sympy.physics.units import (
G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin,
kilogram, kilometer, length, meter, mile, minute, newton, planck,
planck_length, planck_mass, planck_temperature, planck_time, radians,
second, speed_of_light, steradian, time, km)
from sympy.physics.units.util import convert_to, check_dimensions
from sympy.testing.pytest import raises
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
L = length
T = time
def test_dim_simplify_add():
# assert Add(L, L) == L
assert L + L == L
def test_dim_simplify_mul():
# assert Mul(L, T) == L*T
assert L*T == L*T
def test_dim_simplify_pow():
assert Pow(L, 2) == L**2
def test_dim_simplify_rec():
# assert Mul(Add(L, L), T) == L*T
assert (L + L) * T == L*T
def test_convert_to_quantities():
assert convert_to(3, meter) == 3
assert convert_to(mile, kilometer) == 25146*kilometer/15625
assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458
assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light
assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light
assert convert_to(speed_of_light, meter/second) == 299792458*meter/second
assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second
assert convert_to(day, second) == 86400*second
assert convert_to(2*hour, minute) == 120*minute
assert convert_to(mile, meter) == 201168*meter/125
assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour)
assert convert_to(3*newton, meter/second) == 3*newton
assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2
assert convert_to(kilometer + mile, meter) == 326168*meter/125
assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125
assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000
assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000
assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second)
assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second)
assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2
assert convert_to(steradian, coulomb) == steradian
assert convert_to(radians, degree) == 180*degree/pi
assert convert_to(radians, [meter, degree]) == 180*degree/pi
assert convert_to(pi*radians, degree) == 180*degree
assert convert_to(pi, degree) == 180*degree
def test_convert_to_tuples_of_quantities():
assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second
assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second
assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second
assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2
assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2
assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light
assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2
# This doesn't make physically sense, but let's keep it as a conversion test:
assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second
assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G
assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000*speed_of_light**(-1.500000)'
assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram'
assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter'
assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second'
assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin'
assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter'
def test_eval_simplify():
from sympy.physics.units import cm, mm, km, m, K, kilo
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert (cm/mm).simplify() == 10
assert (km/m).simplify() == 1000
assert (km/cm).simplify() == 100000
assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin
assert (cm/km/m).simplify() == 1/(10000000*centimeter)
assert (3*kilo*meter).simplify() == 3000*meter
assert (4*kilo*meter/(2*kilometer)).simplify() == 2
assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4
def test_quantity_simplify():
from sympy.physics.units.util import quantity_simplify
from sympy.physics.units import kilo, foot
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y)
assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12
assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12
assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12
assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144
def test_check_dimensions():
x = symbols('x')
assert check_dimensions(inch + x) == inch + x
assert check_dimensions(length + x) == length + x
# after subs we get 2*length; check will clear the constant
assert check_dimensions((length + x).subs(x, length)) == length
assert check_dimensions(newton*meter + joule) == joule + meter*newton
raises(ValueError, lambda: check_dimensions(inch + 1))
raises(ValueError, lambda: check_dimensions(length + 1))
raises(ValueError, lambda: check_dimensions(length + time))
raises(ValueError, lambda: check_dimensions(meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second))
raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter))
raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km))
|
4a8de6be23d8209132d49d3ac5ce82ddda12e30fc9e6e2ecbd4dbad4742ee64b | from sympy import symbols, pi, sin, cos, Float, ImmutableMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, dot
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_Vector():
assert A.x != A.y
assert A.y != A.z
assert A.z != A.x
assert A.x + 0 == A.x
v1 = x*A.x + y*A.y + z*A.z
v2 = x**2*A.x + y**2*A.y + z**2*A.z
v3 = v1 + v2
v4 = v1 - v2
assert isinstance(v1, Vector)
assert dot(v1, A.x) == x
assert dot(v1, A.y) == y
assert dot(v1, A.z) == z
assert isinstance(v2, Vector)
assert dot(v2, A.x) == x**2
assert dot(v2, A.y) == y**2
assert dot(v2, A.z) == z**2
assert isinstance(v3, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v3, A.x) == x**2 + x
assert dot(v3, A.y) == y**2 + y
assert dot(v3, A.z) == z**2 + z
assert isinstance(v4, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v4, A.x) == x - x**2
assert dot(v4, A.y) == y - y**2
assert dot(v4, A.z) == z - z**2
assert v1.to_matrix(A) == Matrix([[x], [y], [z]])
q = symbols('q')
B = A.orientnew('B', 'Axis', (q, A.x))
assert v1.to_matrix(B) == Matrix([[x],
[ y * cos(q) + z * sin(q)],
[-y * sin(q) + z * cos(q)]])
#Test the separate method
B = ReferenceFrame('B')
v5 = x*A.x + y*A.y + z*B.z
assert Vector(0).separate() == {}
assert v1.separate() == {A: v1}
assert v5.separate() == {A: x*A.x + y*A.y, B: z*B.z}
#Test the free_symbols property
v6 = x*A.x + y*A.y + z*A.z
assert v6.free_symbols(A) == {x,y,z}
raises(TypeError, lambda: v3.applyfunc(v1))
def test_Vector_diffs():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
q1dd, q2dd, q3dd, q4dd = dynamicsymbols('q1 q2 q3 q4', 2)
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q3, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
v1 = q2 * A.x + q3 * N.y
v2 = q3 * B.x + v1
v3 = v1.dt(B)
v4 = v2.dt(B)
v5 = q1*A.x + q2*A.y + q3*A.z
assert v1.dt(N) == q2d * A.x + q2 * q3d * A.y + q3d * N.y
assert v1.dt(A) == q2d * A.x + q3 * q3d * N.x + q3d * N.y
assert v1.dt(B) == (q2d * A.x + q3 * q3d * N.x + q3d *\
N.y - q3 * cos(q3) * q2d * N.z)
assert v2.dt(N) == (q2d * A.x + (q2 + q3) * q3d * A.y + q3d * B.x + q3d *
N.y)
assert v2.dt(A) == q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y
assert v2.dt(B) == (q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y -
q3 * cos(q3) * q2d * N.z)
assert v3.dt(N) == (q2dd * A.x + q2d * q3d * A.y + (q3d**2 + q3 * q3dd) *
N.x + q3dd * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(A) == (q2dd * A.x + (2 * q3d**2 + q3 * q3dd) * N.x + (q3dd -
q3 * q3d**2) * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + (2 *
q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v4.dt(N) == (q2dd * A.x + q3d * (q2d + q3d) * A.y + q3dd * B.x +
(q3d**2 + q3 * q3dd) * N.x + q3dd * N.y + (q3 *
sin(q3) * q2d * q3d - cos(q3) * q2d * q3d - q3 *
cos(q3) * q2dd) * N.z)
assert v4.dt(A) == (q2dd * A.x + q3dd * B.x + (2 * q3d**2 + q3 * q3dd) *
N.x + (q3dd - q3 * q3d**2) * N.y + (q3 * sin(q3) *
q2d * q3d - cos(q3) * q2d * q3d - q3 * cos(q3) *
q2dd) * N.z)
assert v4.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + q3dd * B.x +
(2 * q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v5.dt(B) == q1d*A.x + (q3*q2d + q2d)*A.y + (-q2*q2d + q3d)*A.z
assert v5.dt(A) == q1d*A.x + q2d*A.y + q3d*A.z
assert v5.dt(N) == (-q2*q3d + q1d)*A.x + (q1*q3d + q2d)*A.y + q3d*A.z
assert v3.diff(q1d, N) == 0
assert v3.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, N) == q3 * N.x + N.y
assert v3.diff(q1d, A) == 0
assert v3.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, A) == q3 * N.x + N.y
assert v3.diff(q1d, B) == 0
assert v3.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, B) == q3 * N.x + N.y
assert v4.diff(q1d, N) == 0
assert v4.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, N) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, A) == 0
assert v4.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, A) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, B) == 0
assert v4.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, B) == B.x + q3 * N.x + N.y
def test_vector_var_in_dcm():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
u1, u2, u3, u4 = dynamicsymbols('u1 u2 u3 u4')
v = u1 * u2 * A.x + u3 * N.y + u4**2 * N.z
assert v.diff(u1, N, var_in_dcm=False) == u2 * A.x
assert v.diff(u1, A, var_in_dcm=False) == u2 * A.x
assert v.diff(u3, N, var_in_dcm=False) == N.y
assert v.diff(u3, A, var_in_dcm=False) == N.y
assert v.diff(u3, B, var_in_dcm=False) == N.y
assert v.diff(u4, N, var_in_dcm=False) == 2 * u4 * N.z
raises(ValueError, lambda: v.diff(u1, N))
def test_vector_simplify():
x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A')
N = ReferenceFrame('N')
test1 = (1 / x + 1 / y) * N.x
assert (test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * N.x
test2 = test2.simplify()
assert (test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * N.x
test3 = test3.simplify()
assert (test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * N.x
test4 = test4.simplify()
assert (test4 & N.x) == -2 * y
def test_vector_evalf():
a, b = symbols('a b')
v = pi * A.x
assert v.evalf(2) == Float('3.1416', 2) * A.x
v = pi * A.x + 5 * a * A.y - b * A.z
assert v.evalf(3) == Float('3.1416', 3) * A.x + Float('5', 3) * a * A.y - b * A.z
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.