hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
0ecee53f7ed1dfa8ffe6209bd85bb36b94fd238d0c13245c7e264d84486991d4 | import itertools
from collections.abc import Iterable
from sympy import S, Tuple, diff, Basic
from sympy.core.sympify import _sympify
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
def _arrayfy(a):
from sympy.matrices import MatrixBase
if isinstance(a, NDimArray):
return a
if isinstance(a, (MatrixBase, list, tuple, Tuple)):
return ImmutableDenseNDimArray(a)
return a
def tensorproduct(*args):
"""
Tensor product among scalars or array-like objects.
Examples
========
>>> from sympy.tensor.array import tensorproduct, Array
>>> from sympy.abc import x, y, z, t
>>> A = Array([[1, 2], [3, 4]])
>>> B = Array([x, y])
>>> tensorproduct(A, B)
[[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
>>> tensorproduct(A, x)
[[x, 2*x], [3*x, 4*x]]
>>> tensorproduct(A, B, B)
[[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
Applying this function on two matrices will result in a rank 4 array.
>>> from sympy import Matrix, eye
>>> m = Matrix([[x, y], [z, t]])
>>> p = tensorproduct(eye(3), m)
>>> p
[[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
"""
from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
if len(args) == 0:
return S.One
if len(args) == 1:
return _arrayfy(args[0])
if len(args) > 2:
return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
# length of args is 2:
a, b = map(_arrayfy, args)
if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
return a*b
if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
lp = len(b)
new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
array = _arrayfy(array)
# Verify contraction_axes:
taken_dims = set()
for axes_group in contraction_or_diagonal_axes:
if not isinstance(axes_group, Iterable):
raise ValueError("collections of contraction/diagonal axes expected")
dim = array.shape[axes_group[0]]
for d in axes_group:
if d in taken_dims:
raise ValueError("dimension specified more than once")
if dim != array.shape[d]:
raise ValueError("cannot contract or diagonalize between axes of different dimension")
taken_dims.add(d)
rank = array.rank()
remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
cum_shape = [0]*rank
_cumul = 1
for i in range(rank):
cum_shape[rank - i - 1] = _cumul
_cumul *= int(array.shape[rank - i - 1])
# DEFINITION: by absolute position it is meant the position along the one
# dimensional array containing all the tensor components.
# Possible future work on this module: move computation of absolute
# positions to a class method.
# Determine absolute positions of the uncontracted indices:
remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
for i in range(rank) if i not in taken_dims]
# Determine absolute positions of the contracted indices:
summed_deltas = []
for axes_group in contraction_or_diagonal_axes:
lidx = []
for js in range(array.shape[axes_group[0]]):
lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
summed_deltas.append(lidx)
return array, remaining_indices, remaining_shape, summed_deltas
def tensorcontraction(array, *contraction_axes):
"""
Contraction of an array-like object on the specified axes.
Examples
========
>>> from sympy import Array, tensorcontraction
>>> from sympy import Matrix, eye
>>> tensorcontraction(eye(3), (0, 1))
3
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensorcontraction(A, (0, 2))
[21, 30]
Matrix multiplication may be emulated with a proper combination of
``tensorcontraction`` and ``tensorproduct``
>>> from sympy import tensorproduct
>>> from sympy.abc import a,b,c,d,e,f,g,h
>>> m1 = Matrix([[a, b], [c, d]])
>>> m2 = Matrix([[e, f], [g, h]])
>>> p = tensorproduct(m1, m2)
>>> p
[[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
>>> tensorcontraction(p, (1, 2))
[[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
>>> m1*m2
Matrix([
[a*e + b*g, a*f + b*h],
[c*e + d*g, c*f + d*h]])
"""
array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
# Compute the contracted array:
#
# 1. external for loops on all uncontracted indices.
# Uncontracted indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all contracted indices.
# It sums the values of the absolute contracted index and the absolute
# uncontracted index for the external loop.
contracted_array = []
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = S.Zero
for sum_to_index in itertools.product(*summed_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum += array[idx]
contracted_array.append(isum)
if len(remaining_indices) == 0:
assert len(contracted_array) == 1
return contracted_array[0]
return type(array)(contracted_array, remaining_shape)
def tensordiagonal(array, *diagonal_axes):
"""
Diagonalization of an array-like object on the specified axes.
This is equivalent to multiplying the expression by Kronecker deltas
uniting the axes.
The diagonal indices are put at the end of the axes.
Examples
========
``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
equivalent to the diagonal of the matrix:
>>> from sympy import Array, tensordiagonal
>>> from sympy import Matrix, eye
>>> tensordiagonal(eye(3), (0, 1))
[1, 1, 1]
>>> from sympy.abc import a,b,c,d
>>> m1 = Matrix([[a, b], [c, d]])
>>> tensordiagonal(m1, [0, 1])
[a, d]
In case of higher dimensional arrays, the diagonalized out dimensions
are appended removed and appended as a single dimension at the end:
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensordiagonal(A, (0, 2))
[[0, 7, 14], [3, 10, 17]]
>>> from sympy import permutedims
>>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
True
"""
if any([len(i) <= 1 for i in diagonal_axes]):
raise ValueError("need at least two axes to diagonalize")
array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
# Compute the diagonalized array:
#
# 1. external for loops on all undiagonalized indices.
# Undiagonalized indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all diagonal indices.
# It appends the values of the absolute diagonalized index and the absolute
# undiagonalized index for the external loop.
diagonalized_array = []
diagonal_shape = [len(i) for i in diagonal_deltas]
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = []
for sum_to_index in itertools.product(*diagonal_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum.append(array[idx])
isum = type(array)(isum).reshape(*diagonal_shape)
diagonalized_array.append(isum)
return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
def derive_by_array(expr, dx):
r"""
Derivative by arrays. Supports both arrays and scalars.
Explanation
===========
Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
this function will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
Examples
========
>>> from sympy import derive_by_array
>>> from sympy.abc import x, y, z, t
>>> from sympy import cos
>>> derive_by_array(cos(x*t), x)
-t*sin(t*x)
>>> derive_by_array(cos(x*t), [x, y, z, t])
[-t*sin(t*x), 0, 0, -x*sin(t*x)]
>>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
[[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
"""
from sympy.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
array_types = (Iterable, MatrixBase, NDimArray)
if isinstance(dx, array_types):
dx = ImmutableDenseNDimArray(dx)
for i in dx:
if not i._diff_wrt:
raise ValueError("cannot derive by this array")
if isinstance(expr, array_types):
if isinstance(expr, NDimArray):
expr = expr.as_immutable()
else:
expr = ImmutableDenseNDimArray(expr)
if isinstance(dx, array_types):
if isinstance(expr, SparseNDimArray):
lp = len(expr)
new_array = {k + i*lp: v
for i, x in enumerate(Flatten(dx))
for k, v in expr.diff(x)._sparse_array.items()}
else:
new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
return type(expr)(new_array, dx.shape + expr.shape)
else:
return expr.diff(dx)
else:
expr = _sympify(expr)
if isinstance(dx, array_types):
return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
else:
dx = _sympify(dx)
return diff(expr, dx)
def permutedims(expr, perm):
"""
Permutes the indices of an array.
Parameter specifies the permutation of the indices.
Examples
========
>>> from sympy.abc import x, y, z, t
>>> from sympy import sin
>>> from sympy import Array, permutedims
>>> a = Array([[x, y, z], [t, sin(x), 0]])
>>> a
[[x, y, z], [t, sin(x), 0]]
>>> permutedims(a, (1, 0))
[[x, t], [y, sin(x)], [z, 0]]
If the array is of second order, ``transpose`` can be used:
>>> from sympy import transpose
>>> transpose(a)
[[x, t], [y, sin(x)], [z, 0]]
Examples on higher dimensions:
>>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> permutedims(b, (2, 1, 0))
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, (1, 2, 0))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
``Permutation`` objects are also allowed:
>>> from sympy.combinatorics import Permutation
>>> permutedims(b, Permutation([1, 2, 0]))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(expr, NDimArray):
expr = ImmutableDenseNDimArray(expr)
from sympy.combinatorics import Permutation
if not isinstance(perm, Permutation):
perm = Permutation(list(perm))
if perm.size != expr.rank():
raise ValueError("wrong permutation size")
# Get the inverse permutation:
iperm = ~perm
new_shape = perm(expr.shape)
if isinstance(expr, SparseNDimArray):
return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
for k, v in expr._sparse_array.items()}, new_shape)
indices_span = perm([range(i) for i in expr.shape])
new_array = [None]*len(expr)
for i, idx in enumerate(itertools.product(*indices_span)):
t = iperm(idx)
new_array[i] = expr[t]
return type(expr)(new_array, new_shape)
class Flatten(Basic):
'''
Flatten an iterable object to a list in a lazy-evaluation way.
Notes
=====
This class is an iterator with which the memory cost can be economised.
Optimisation has been considered to ameliorate the performance for some
specific data types like DenseNDimArray and SparseNDimArray.
Examples
========
>>> from sympy.tensor.array.arrayop import Flatten
>>> from sympy.tensor.array import Array
>>> A = Array(range(6)).reshape(2, 3)
>>> Flatten(A)
Flatten([[0, 1, 2], [3, 4, 5]])
>>> [i for i in Flatten(A)]
[0, 1, 2, 3, 4, 5]
'''
def __init__(self, iterable):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import NDimArray
if not isinstance(iterable, (Iterable, MatrixBase)):
raise NotImplementedError("Data type not yet supported")
if isinstance(iterable, list):
iterable = NDimArray(iterable)
self._iter = iterable
self._idx = 0
def __iter__(self):
return self
def __next__(self):
from sympy.matrices.matrices import MatrixBase
if len(self._iter) > self._idx:
if isinstance(self._iter, DenseNDimArray):
result = self._iter._array[self._idx]
elif isinstance(self._iter, SparseNDimArray):
if self._idx in self._iter._sparse_array:
result = self._iter._sparse_array[self._idx]
else:
result = 0
elif isinstance(self._iter, MatrixBase):
result = self._iter[self._idx]
elif hasattr(self._iter, '__next__'):
result = next(self._iter)
else:
result = self._iter[self._idx]
else:
raise StopIteration
self._idx += 1
return result
def next(self):
return self.__next__()
|
f312f872501915c1a3ead50e8c5d048c513aa7b9cc74cfc354b41d224ee8cdba | from sympy import Basic
from sympy import S
from sympy.core.expr import Expr
from sympy.core.numbers import Integer
from sympy.core.sympify import sympify
from sympy.core.kind import Kind, NumberKind
from sympy.core.compatibility import SYMPY_INTS
from sympy.printing.defaults import Printable
import itertools
from collections.abc import Iterable
class ArrayKind(Kind):
"""
Kind for N-dimensional array in SymPy.
This kind represents the multidimensional array that algebraic
operations are defined. Basic class for this kind is ``NDimArray``,
but any expression representing the array can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is ``NumberKind``, which means that
the array contains only numbers.
Examples
========
>>> from sympy import NDimArray
>>> NDimArray([1,2,3]).kind
ArrayKind(NumberKind)
See Also
========
sympy.matrices.MatrixKind : Kind for matrices.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "ArrayKind(%s)" % self.element_kind
class NDimArray(Printable):
"""
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
is_scalar = False
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
@property
def kind(self):
return ArrayKind()
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
raise ValueError("Only a tuple index is accepted")
if self._loop_size == 0:
raise ValueError("Index not valide with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any([(isinstance(i, Expr) and (not i.is_number)) for i in tuple_index]):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy import Dict, Tuple
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if any([not isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape]):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
def _eval_derivative(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def _sympystr(self, printer):
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return printer._print(self[()])
return f(self._loop_size, self.shape, 0, self._loop_size)
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __truediv__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rtruediv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index, )
if len(index) < self.rank():
index = tuple([i for i in index] + \
[slice(None) for i in range(len(index), self.rank())])
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
3e5ad560fd9d934ee4ff1961b9778427c79cc58a8d86aa7dc0757609c592de05 | import random
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.testing.pytest import raises
from sympy import symbols, sin, exp, log, cos, transpose, adjoint, conjugate, diff
from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \
tensordiagonal
def test_import_NDimArray():
from sympy.tensor.array import NDimArray
del NDimArray
def test_tensorproduct():
x,y,z,t = symbols('x y z t')
from sympy.abc import a,b,c,d
assert tensorproduct() == 1
assert tensorproduct([x]) == Array([x])
assert tensorproduct([x], [y]) == Array([[x*y]])
assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
assert tensorproduct(x) == x
assert tensorproduct(x, y) == x*y
assert tensorproduct(x, y, z) == x*y*z
assert tensorproduct(x, y, z, t) == x*y*z*t
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
A = ArrayType([x, y])
B = ArrayType([1, 2, 3])
C = ArrayType([a, b, c, d])
assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
[[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
assert tensorproduct(a, A) == ArrayType([a*x, a*y])
assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
# tests for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
a = SparseArrayType({1:2, 3:4},(1000, 2000))
b = SparseArrayType({1:2, 3:4},(1000, 2000))
assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
def test_tensorcontraction():
from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
B = Array(range(18), (2, 3, 3))
assert tensorcontraction(B, (1, 2)) == Array([12, 39])
C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
def test_derivative_by_array():
from sympy.abc import i, j, t, x, y, z
bexpr = x*y**2*exp(z)*log(t)
sexpr = sin(bexpr)
cexpr = cos(bexpr)
a = Array([sexpr])
assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
#https://github.com/sympy/sympy/issues/20655
U = Array([x, y, z])
E = 2
assert derive_by_array(E, U) == ImmutableDenseNDimArray([0, 0, 0])
def test_issue_emerged_while_discussing_10972():
ua = Array([-1,0])
Fa = Array([[0, 1], [-1, 0]])
po = tensorproduct(Fa, ua, Fa, ua)
assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
sa = symbols('a0:144')
po = Array(sa, [2, 2, 3, 3, 2, 2])
assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
[sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
sa[140] + sa[143] + sa[32] + sa[35]]])
assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
[sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
def test_array_permutedims():
sa = symbols('a0:144')
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
m1 = ArrayType(sa[:6], (2, 3))
assert permutedims(m1, (1, 0)) == transpose(m1)
assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
assert m1.tomatrix().T == transpose(m1).tomatrix()
assert m1.tomatrix().C == conjugate(m1).tomatrix()
assert m1.tomatrix().H == adjoint(m1).tomatrix()
assert m1.tomatrix().T == m1.transpose().tomatrix()
assert m1.tomatrix().C == m1.conjugate().tomatrix()
assert m1.tomatrix().H == m1.adjoint().tomatrix()
raises(ValueError, lambda: permutedims(m1, (0,)))
raises(ValueError, lambda: permutedims(m1, (0, 0)))
raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
# Some tests with random arrays:
dims = 6
shape = [random.randint(1,5) for i in range(dims)]
elems = [random.random() for i in range(tensorproduct(*shape))]
ra = ArrayType(elems, shape)
perm = list(range(dims))
# Randomize the permutation:
random.shuffle(perm)
# Test inverse permutation:
assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
# Test that permuted shape corresponds to action by `Permutation`:
assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
z = ArrayType.zeros(4,5,6,7)
assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
raises(ValueError, lambda: permutedims(po, (1, 1)))
raises(ValueError, lambda: po.transpose())
raises(ValueError, lambda: po.adjoint())
assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
[[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
sa[96]], [sa[60], sa[132]]]],
[[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
sa[88]], [sa[52], sa[124]]],
[[sa[28], sa[100]], [sa[64], sa[136]]]],
[[[sa[8],
sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
sa[104]], [sa[68], sa[140]]]]],
[[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
[[[sa[6],
sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
sa[102]], [sa[66], sa[138]]]],
[[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
sa[94]], [sa[58], sa[130]]],
[[sa[34], sa[106]], [sa[70], sa[142]]]]]],
[[[[[sa[1],
sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
sa[97]], [sa[61], sa[133]]]],
[[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
sa[89]], [sa[53], sa[125]]],
[[sa[29], sa[101]], [sa[65], sa[137]]]],
[[[sa[9],
sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
sa[105]], [sa[69], sa[141]]]]],
[[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
[[[sa[7],
sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
sa[103]], [sa[67], sa[139]]]],
[[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
sa[95]], [sa[59], sa[131]]],
[[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
sa[11]]]],
[[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
[[[sa[24], sa[25]], [sa[26],
sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
sa[35]]]]],
[[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
[[[sa[84], sa[85]], [sa[86],
sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
sa[95]]]],
[[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
sa[103]]],
[[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
sa[39]]],
[[sa[40], sa[41]], [sa[42], sa[43]]],
[[sa[44], sa[45]], [sa[46],
sa[47]]]],
[[[sa[48], sa[49]], [sa[50], sa[51]]],
[[sa[52], sa[53]], [sa[54],
sa[55]]],
[[sa[56], sa[57]], [sa[58], sa[59]]]],
[[[sa[60], sa[61]], [sa[62],
sa[63]]],
[[sa[64], sa[65]], [sa[66], sa[67]]],
[[sa[68], sa[69]], [sa[70],
sa[71]]]]], [
[[[sa[108], sa[109]], [sa[110], sa[111]]],
[[sa[112], sa[113]], [sa[114],
sa[115]]],
[[sa[116], sa[117]], [sa[118], sa[119]]]],
[[[sa[120], sa[121]], [sa[122],
sa[123]]],
[[sa[124], sa[125]], [sa[126], sa[127]]],
[[sa[128], sa[129]], [sa[130],
sa[131]]]],
[[[sa[132], sa[133]], [sa[134], sa[135]]],
[[sa[136], sa[137]], [sa[138],
sa[139]]],
[[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
sa[11]]]],
[[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
[[[[sa[12], sa[13]], [sa[16],
sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
sa[23]]]],
[[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
[[[[sa[24], sa[25]], [sa[28],
sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
sa[35]]]],
[[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
[[[[[sa[72], sa[73]], [sa[76],
sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
sa[83]]]],
[[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
sa[111]], [sa[114], sa[115]],
[sa[118], sa[119]]]]],
[[[[sa[84], sa[85]], [sa[88],
sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
sa[95]]]],
[[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
sa[123]], [sa[126], sa[127]],
[sa[130], sa[131]]]]],
[[[[sa[96], sa[97]], [sa[100],
sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
sa[107]]]],
[[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
sa[135]], [sa[138], sa[139]],
[sa[142], sa[143]]]]]]])
po2 = po.reshape(4, 9, 2, 2)
assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
assert permutedims(A, (0, 1, 2)) == A
assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
def test_flatten():
from sympy import Matrix
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
A = ArrayType(range(24)).reshape(4, 6)
assert [i for i in Flatten(A)] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
for i, v in enumerate(Flatten(A)):
i == v
def test_tensordiagonal():
from sympy import eye
expr = Array(range(9)).reshape(3, 3)
raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
x, y, z = symbols("x y z")
expr2 = tensorproduct([x, y, z], expr)
assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
# assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
# assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
# assert tensordiagonal(expr2, [2]) == expr2
# assert tensordiagonal(expr2, [1], [2]) == expr2
# assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])
a, b, c, X, Y, Z = symbols("a b c X Y Z")
expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])
# assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])
raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
|
dad013e9bfdff1be982340eefc1ba1f5dd64411dfacc06746c89329b6960e78d | from typing import Tuple as tTuple
from sympy.core.logic import FuzzyBool
from functools import wraps, reduce
import collections
from sympy.core import S, Symbol, Integer, Basic, Expr, Mul, Add
from sympy.core.decorators import call_highest_priority
from sympy.core.compatibility import SYMPY_INTS, default_sort_key
from sympy.core.symbol import Str
from sympy.core.sympify import SympifyError, _sympify
from sympy.functions import conjugate, adjoint
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.common import NonSquareMatrixError
from sympy.simplify import simplify
from sympy.matrices.matrices import MatrixKind
from sympy.utilities.misc import filldedent
from sympy.multipledispatch import dispatch
def _sympifyit(arg, retval=None):
# This version of _sympifyit sympifies MutableMatrix objects
def deco(func):
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
b = _sympify(b)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
return deco
class MatrixExpr(Expr):
"""Superclass for Matrix Expressions
MatrixExprs represent abstract matrices, linear transformations represented
within a particular basis.
Examples
========
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 3, 3)
>>> y = MatrixSymbol('y', 3, 1)
>>> x = (A.T*A).I * A * y
See Also
========
MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
"""
# Should not be considered iterable by the
# sympy.core.compatibility.iterable function. Subclass that actually are
# iterable (i.e., explicit matrices) should set this to True.
_iterable = False
_op_priority = 11.0
is_Matrix = True # type: bool
is_MatrixExpr = True # type: bool
is_Identity = None # type: FuzzyBool
is_Inverse = False
is_Transpose = False
is_ZeroMatrix = False
is_MatAdd = False
is_MatMul = False
is_commutative = False
is_number = False
is_symbol = False
is_scalar = False
kind = MatrixKind()
def __new__(cls, *args, **kwargs):
args = map(_sympify, args)
return Basic.__new__(cls, *args, **kwargs)
# The following is adapted from the core Expr object
@property
def shape(self) -> tTuple[Expr, Expr]:
raise NotImplementedError
@property
def _add_handler(self):
return MatAdd
@property
def _mul_handler(self):
return MatMul
def __neg__(self):
return MatMul(S.NegativeOne, self).doit()
def __abs__(self):
raise NotImplementedError
@_sympifyit('other', NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return MatAdd(self, other, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return MatAdd(other, self, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return MatAdd(self, -other, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return MatAdd(other, -self, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __matmul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmatmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
return MatPow(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
raise NotImplementedError("Matrix Power not defined")
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self * other**S.NegativeOne
@_sympifyit('other', NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
raise NotImplementedError()
#return MatMul(other, Pow(self, S.NegativeOne))
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
@property
def is_square(self):
return self.rows == self.cols
def _eval_conjugate(self):
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions.transpose import Transpose
return Adjoint(Transpose(self))
def as_real_imag(self, deep=True, **hints):
from sympy import I
real = S.Half * (self + self._eval_conjugate())
im = (self - self._eval_conjugate())/(2*I)
return (real, im)
def _eval_inverse(self):
from sympy.matrices.expressions.inverse import Inverse
return Inverse(self)
def _eval_transpose(self):
return Transpose(self)
def _eval_power(self, exp):
"""
Override this in sub-classes to implement simplification of powers. The cases where the exponent
is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases.
"""
return MatPow(self, exp)
def _eval_simplify(self, **kwargs):
if self.is_Atom:
return self
else:
return self.func(*[simplify(x, **kwargs) for x in self.args])
def _eval_adjoint(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(self)
def _eval_derivative_n_times(self, x, n):
return Basic._eval_derivative_n_times(self, x, n)
def _eval_derivative(self, x):
# `x` is a scalar:
if self.has(x):
# See if there are other methods using it:
return super()._eval_derivative(x)
else:
return ZeroMatrix(*self.shape)
@classmethod
def _check_dim(cls, dim):
"""Helper function to check invalid matrix dimensions"""
from sympy.core.assumptions import check_assumptions
ok = check_assumptions(dim, integer=True, nonnegative=True)
if ok is False:
raise ValueError(
"The dimension specification {} should be "
"a nonnegative integer.".format(dim))
def _entry(self, i, j, **kwargs):
raise NotImplementedError(
"Indexing not implemented for %s" % self.__class__.__name__)
def adjoint(self):
return adjoint(self)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return S.One, self
def conjugate(self):
return conjugate(self)
def transpose(self):
from sympy.matrices.expressions.transpose import transpose
return transpose(self)
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
def inverse(self):
if not self.is_square:
raise NonSquareMatrixError('Inverse of non-square matrix')
return self._eval_inverse()
def inv(self):
return self.inverse()
@property
def I(self):
return self.inverse()
def valid_index(self, i, j):
def is_valid(idx):
return isinstance(idx, (int, Integer, Symbol, Expr))
return (is_valid(i) and is_valid(j) and
(self.rows is None or
(0 <= i) != False and (i < self.rows) != False) and
(0 <= j) != False and (j < self.cols) != False)
def __getitem__(self, key):
if not isinstance(key, tuple) and isinstance(key, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, key, (0, None, 1))
if isinstance(key, tuple) and len(key) == 2:
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, i, j)
i, j = _sympify(i), _sympify(j)
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid indices (%s, %s)" % (i, j))
elif isinstance(key, (SYMPY_INTS, Integer)):
# row-wise decomposition of matrix
rows, cols = self.shape
# allow single indexing if number of columns is known
if not isinstance(cols, Integer):
raise IndexError(filldedent('''
Single indexing is only supported when the number
of columns is known.'''))
key = _sympify(key)
i = key // cols
j = key % cols
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid index %s" % key)
elif isinstance(key, (Symbol, Expr)):
raise IndexError(filldedent('''
Only integers may be used when addressing the matrix
with a single index.'''))
raise IndexError("Invalid index, wanted %s[i,j]" % self)
def as_explicit(self):
"""
Returns a dense Matrix with elements represented explicitly
Returns an object of type ImmutableDenseMatrix.
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.as_explicit()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_mutable: returns mutable Matrix type
"""
if (not isinstance(self.rows, (SYMPY_INTS, Integer))
or not isinstance(self.cols, (SYMPY_INTS, Integer))):
raise ValueError(
'Matrix with symbolic shape '
'cannot be represented explicitly.')
from sympy.matrices.immutable import ImmutableDenseMatrix
return ImmutableDenseMatrix([[self[i, j]
for j in range(self.cols)]
for i in range(self.rows)])
def as_mutable(self):
"""
Returns a dense, mutable matrix with elements represented explicitly
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.shape
(3, 3)
>>> I.as_mutable()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_explicit: returns ImmutableDenseMatrix
"""
return self.as_explicit().as_mutable()
def __array__(self):
from numpy import empty
a = empty(self.shape, dtype=object)
for i in range(self.rows):
for j in range(self.cols):
a[i, j] = self[i, j]
return a
def equals(self, other):
"""
Test elementwise equality between matrices, potentially of different
types
>>> from sympy import Identity, eye
>>> Identity(3).equals(eye(3))
True
"""
return self.as_explicit().equals(other)
def canonicalize(self):
return self
def as_coeff_mmul(self):
return 1, MatMul(self)
@staticmethod
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
r"""
Parse expression of matrices with explicitly summed indices into a
matrix expression without indices, if possible.
This transformation expressed in mathematical notation:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Optional parameter ``first_index``: specify which free index to use as
the index starting the expression.
Examples
========
>>> from sympy import MatrixSymbol, MatrixExpr, Sum
>>> from sympy.abc import i, j, k, l, N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A.T*B
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
Trace(A)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B.T*A.T
"""
from sympy import Sum, Mul, Add, MatMul, transpose, trace
from sympy.strategies.traverse import bottom_up
def remove_matelement(expr, i1, i2):
def repl_match(pos):
def func(x):
if not isinstance(x, MatrixElement):
return False
if x.args[pos] != i1:
return False
if x.args[3-pos] == 0:
if x.args[0].shape[2-pos] == 1:
return True
else:
return False
return True
return func
expr = expr.replace(repl_match(1),
lambda x: x.args[0])
expr = expr.replace(repl_match(2),
lambda x: transpose(x.args[0]))
# Make sure that all Mul are transformed to MatMul and that they
# are flattened:
rule = bottom_up(lambda x: reduce(lambda a, b: a*b, x.args) if isinstance(x, (Mul, MatMul)) else x)
return rule(expr)
def recurse_expr(expr, index_ranges={}):
if expr.is_Mul:
nonmatargs = []
pos_arg = []
pos_ind = []
dlinks = {}
link_ind = []
counter = 0
args_ind = []
for arg in expr.args:
retvals = recurse_expr(arg, index_ranges)
assert isinstance(retvals, list)
if isinstance(retvals, list):
for i in retvals:
args_ind.append(i)
else:
args_ind.append(retvals)
for arg_symbol, arg_indices in args_ind:
if arg_indices is None:
nonmatargs.append(arg_symbol)
continue
if isinstance(arg_symbol, MatrixElement):
arg_symbol = arg_symbol.args[0]
pos_arg.append(arg_symbol)
pos_ind.append(arg_indices)
link_ind.append([None]*len(arg_indices))
for i, ind in enumerate(arg_indices):
if ind in dlinks:
other_i = dlinks[ind]
link_ind[counter][i] = other_i
link_ind[other_i[0]][other_i[1]] = (counter, i)
dlinks[ind] = (counter, i)
counter += 1
counter2 = 0
lines = {}
while counter2 < len(link_ind):
for i, e in enumerate(link_ind):
if None in e:
line_start_index = (i, e.index(None))
break
cur_ind_pos = line_start_index
cur_line = []
index1 = pos_ind[cur_ind_pos[0]][cur_ind_pos[1]]
while True:
d, r = cur_ind_pos
if pos_arg[d] != 1:
if r % 2 == 1:
cur_line.append(transpose(pos_arg[d]))
else:
cur_line.append(pos_arg[d])
next_ind_pos = link_ind[d][1-r]
counter2 += 1
# Mark as visited, there will be no `None` anymore:
link_ind[d] = (-1, -1)
if next_ind_pos is None:
index2 = pos_ind[d][1-r]
lines[(index1, index2)] = cur_line
break
cur_ind_pos = next_ind_pos
lines = {k: MatMul.fromiter(v) if len(v) != 1 else v[0] for k, v in lines.items()}
return [(Mul.fromiter(nonmatargs), None)] + [
(MatrixElement(a, i, j), (i, j)) for (i, j), a in lines.items()
]
elif expr.is_Add:
res = [recurse_expr(i) for i in expr.args]
d = collections.defaultdict(list)
for res_addend in res:
scalar = 1
for elem, indices in res_addend:
if indices is None:
scalar = elem
continue
indices = tuple(sorted(indices, key=default_sort_key))
d[indices].append(scalar*remove_matelement(elem, *indices))
scalar = 1
return [(MatrixElement(Add.fromiter(v), *k), k) for k, v in d.items()]
elif isinstance(expr, KroneckerDelta):
i1, i2 = expr.args
if dimensions is not None:
identity = Identity(dimensions[0])
else:
identity = S.One
return [(MatrixElement(identity, i1, i2), (i1, i2))]
elif isinstance(expr, MatrixElement):
matrix_symbol, i1, i2 = expr.args
if i1 in index_ranges:
r1, r2 = index_ranges[i1]
if r1 != 0 or matrix_symbol.shape[0] != r2+1:
raise ValueError("index range mismatch: {} vs. (0, {})".format(
(r1, r2), matrix_symbol.shape[0]))
if i2 in index_ranges:
r1, r2 = index_ranges[i2]
if r1 != 0 or matrix_symbol.shape[1] != r2+1:
raise ValueError("index range mismatch: {} vs. (0, {})".format(
(r1, r2), matrix_symbol.shape[1]))
if (i1 == i2) and (i1 in index_ranges):
return [(trace(matrix_symbol), None)]
return [(MatrixElement(matrix_symbol, i1, i2), (i1, i2))]
elif isinstance(expr, Sum):
return recurse_expr(
expr.args[0],
index_ranges={i[0]: i[1:] for i in expr.args[1:]}
)
else:
return [(expr, None)]
retvals = recurse_expr(expr)
factors, indices = zip(*retvals)
retexpr = Mul.fromiter(factors)
if len(indices) == 0 or list(set(indices)) == [None]:
return retexpr
if first_index is None:
for i in indices:
if i is not None:
ind0 = i
break
return remove_matelement(retexpr, *ind0)
else:
return remove_matelement(retexpr, first_index, last_index)
def applyfunc(self, func):
from .applyfunc import ElementwiseApplyFunction
return ElementwiseApplyFunction(func, self)
@dispatch(MatrixExpr, Expr)
def _eval_is_eq(lhs, rhs): # noqa:F811
return False
@dispatch(MatrixExpr, MatrixExpr) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if lhs.shape != rhs.shape:
return False
if (lhs - rhs).is_ZeroMatrix:
return True
def get_postprocessor(cls):
def _postprocessor(expr):
# To avoid circular imports, we can't have MatMul/MatAdd on the top level
mat_class = {Mul: MatMul, Add: MatAdd}[cls]
nonmatrices = []
matrices = []
for term in expr.args:
if isinstance(term, MatrixExpr):
matrices.append(term)
else:
nonmatrices.append(term)
if not matrices:
return cls._from_args(nonmatrices)
if nonmatrices:
if cls == Mul:
for i in range(len(matrices)):
if not matrices[i].is_MatrixExpr:
# If one of the matrices explicit, absorb the scalar into it
# (doit will combine all explicit matrices into one, so it
# doesn't matter which)
matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
nonmatrices = []
break
else:
# Maintain the ability to create Add(scalar, matrix) without
# raising an exception. That way different algorithms can
# replace matrix expressions with non-commutative symbols to
# manipulate them like non-commutative scalars.
return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
if mat_class == MatAdd:
return mat_class(*matrices).doit(deep=False)
return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
return _postprocessor
Basic._constructor_postprocessor_mapping[MatrixExpr] = {
"Mul": [get_postprocessor(Mul)],
"Add": [get_postprocessor(Add)],
}
def _matrix_derivative(expr, x):
from sympy.tensor.array.array_derivatives import ArrayDerivative
lines = expr._eval_derivative_matrix_lines(x)
parts = [i.build() for i in lines]
from sympy.codegen.array_utils import recognize_matrix_expression
parts = [[recognize_matrix_expression(j).doit() for j in i] for i in parts]
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return 1, 1
def get_rank(parts):
return sum([j not in (1, None) for i in parts for j in _get_shape(i)])
ranks = [get_rank(i) for i in parts]
rank = ranks[0]
def contract_one_dims(parts):
if len(parts) == 1:
return parts[0]
else:
p1, p2 = parts[:2]
if p2.is_Matrix:
p2 = p2.T
if p1 == Identity(1):
pbase = p2
elif p2 == Identity(1):
pbase = p1
else:
pbase = p1*p2
if len(parts) == 2:
return pbase
else: # len(parts) > 2
if pbase.is_Matrix:
raise ValueError("")
return pbase*Mul.fromiter(parts[2:])
if rank <= 2:
return Add.fromiter([contract_one_dims(i) for i in parts])
return ArrayDerivative(expr, x)
class MatrixElement(Expr):
parent = property(lambda self: self.args[0])
i = property(lambda self: self.args[1])
j = property(lambda self: self.args[2])
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, n, m):
n, m = map(_sympify, (n, m))
from sympy import MatrixBase
if isinstance(name, (MatrixBase,)):
if n.is_Integer and m.is_Integer:
return name[n, m]
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
obj = Expr.__new__(cls, name, n, m)
return obj
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
return args[0][args[1], args[2]]
@property
def indices(self):
return self.args[1:]
def _eval_derivative(self, v):
from sympy import Sum, symbols, Dummy
if not isinstance(v, MatrixElement):
from sympy import MatrixBase
if isinstance(self.parent, MatrixBase):
return self.parent.diff(v)[self.i, self.j]
return S.Zero
M = self.args[0]
m, n = self.parent.shape
if M == v.args[0]:
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
if isinstance(M, Inverse):
i, j = self.args[1:]
i1, i2 = symbols("z1, z2", cls=Dummy)
Y = M.args[0]
r1, r2 = Y.shape
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
if self.has(v.args[0]):
return None
return S.Zero
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
can be included in Matrix Expressions
Examples
========
>>> from sympy import MatrixSymbol, Identity
>>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
>>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
>>> A.shape
(3, 4)
>>> 2*A*B + Identity(3)
I + 2*A*B
"""
is_commutative = False
is_symbol = True
_diff_wrt = True
def __new__(cls, name, n, m):
n, m = _sympify(n), _sympify(m)
cls._check_dim(m)
cls._check_dim(n)
if isinstance(name, str):
name = Str(name)
obj = Basic.__new__(cls, name, n, m)
return obj
@property
def shape(self):
return self.args[1], self.args[2]
@property
def name(self):
return self.args[0].name
def _entry(self, i, j, **kwargs):
return MatrixElement(self, i, j)
@property
def free_symbols(self):
return {self}
def _eval_simplify(self, **kwargs):
return self
def _eval_derivative(self, x):
# x is a scalar:
return ZeroMatrix(self.shape[0], self.shape[1])
def _eval_derivative_matrix_lines(self, x):
if self != x:
first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
return [_LeftRightArgs(
[first, second],
)]
else:
first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
return [_LeftRightArgs(
[first, second],
)]
def matrix_symbols(expr):
return [sym for sym in expr.free_symbols if sym.is_Matrix]
class _LeftRightArgs:
r"""
Helper class to compute matrix derivatives.
The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
matrix multiplications are created: the one contracted to `m` (first line),
and the one contracted to `n` (second line).
Transposition flips the side by which new matrices are connected to the
lines.
The trace connects the end of the two lines.
"""
def __init__(self, lines, higher=S.One):
self._lines = [i for i in lines]
self._first_pointer_parent = self._lines
self._first_pointer_index = 0
self._first_line_index = 0
self._second_pointer_parent = self._lines
self._second_pointer_index = 1
self._second_line_index = 1
self.higher = higher
@property
def first_pointer(self):
return self._first_pointer_parent[self._first_pointer_index]
@first_pointer.setter
def first_pointer(self, value):
self._first_pointer_parent[self._first_pointer_index] = value
@property
def second_pointer(self):
return self._second_pointer_parent[self._second_pointer_index]
@second_pointer.setter
def second_pointer(self, value):
self._second_pointer_parent[self._second_pointer_index] = value
def __repr__(self):
built = [self._build(i) for i in self._lines]
return "_LeftRightArgs(lines=%s, higher=%s)" % (
built,
self.higher,
)
def transpose(self):
self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
return self
@staticmethod
def _build(expr):
from sympy.core.expr import ExprBuilder
if isinstance(expr, ExprBuilder):
return expr.build()
if isinstance(expr, list):
if len(expr) == 1:
return expr[0]
else:
return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
else:
return expr
def build(self):
data = [self._build(i) for i in self._lines]
if self.higher != 1:
data += [self._build(self.higher)]
data = [i.doit() for i in data]
return data
def matrix_form(self):
if self.first != 1 and self.higher != 1:
raise ValueError("higher dimensional array cannot be represented")
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return (None, None)
if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
# Remove one-dimensional identity matrices:
# (this is needed by `a.diff(a)` where `a` is a vector)
if _get_shape(self.second) == (1, 1):
return self.first*self.second[0, 0]
if _get_shape(self.first) == (1, 1):
return self.first[1, 1]*self.second.T
raise ValueError("incompatible shapes")
if self.first != 1:
return self.first*self.second.T
else:
return self.higher
def rank(self):
"""
Number of dimensions different from trivial (warning: not related to
matrix rank).
"""
rank = 0
if self.first != 1:
rank += sum([i != 1 for i in self.first.shape])
if self.second != 1:
rank += sum([i != 1 for i in self.second.shape])
if self.higher != 1:
rank += 2
return rank
def _multiply_pointer(self, pointer, other):
from sympy.core.expr import ExprBuilder
from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
subexpr = ExprBuilder(
CodegenArrayContraction,
[
ExprBuilder(
CodegenArrayTensorProduct,
[
pointer,
other
]
),
(1, 2)
],
validator=CodegenArrayContraction._validate
)
return subexpr
def append_first(self, other):
self.first_pointer *= other
def append_second(self, other):
self.second_pointer *= other
def _make_matrix(x):
from sympy import ImmutableDenseMatrix
if isinstance(x, MatrixExpr):
return x
return ImmutableDenseMatrix([[x]])
from .matmul import MatMul
from .matadd import MatAdd
from .matpow import MatPow
from .transpose import Transpose
from .inverse import Inverse
from .special import ZeroMatrix, Identity
|
7d72525b34bca63d21c7c0adf3adeea4e8fc47475fcd26e8c66a72cd3f2d2ccb | from sympy.functions import adjoint, conjugate, transpose
from sympy.matrices.expressions import MatrixSymbol, Adjoint, trace, Transpose
from sympy.matrices import eye, Matrix
from sympy import symbols, S
from sympy import refine, Q
n, m, l, k, p = symbols('n m l k p', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
def test_transpose():
Sq = MatrixSymbol('Sq', n, n)
assert transpose(A) == Transpose(A)
assert Transpose(A).shape == (m, n)
assert Transpose(A*B).shape == (l, n)
assert transpose(Transpose(A)) == A
assert isinstance(Transpose(Transpose(A)), Transpose)
assert adjoint(Transpose(A)) == Adjoint(Transpose(A))
assert conjugate(Transpose(A)) == Adjoint(A)
assert Transpose(eye(3)).doit() == eye(3)
assert Transpose(S(5)).doit() == S(5)
assert Transpose(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]])
assert transpose(trace(Sq)) == trace(Sq)
assert trace(Transpose(Sq)) == trace(Sq)
assert Transpose(Sq)[0, 1] == Sq[1, 0]
assert Transpose(A*B).doit() == Transpose(B) * Transpose(A)
def test_transpose_MatAdd_MatMul():
# Issue 16807
from sympy.functions.elementary.trigonometric import cos
x = symbols('x')
M = MatrixSymbol('M', 3, 3)
N = MatrixSymbol('N', 3, 3)
assert (N + (cos(x) * M)).T == cos(x)*M.T + N.T
def test_refine():
assert refine(C.T, Q.symmetric(C)) == C
def test_transpose1x1():
m = MatrixSymbol('m', 1, 1)
assert m == refine(m.T)
assert m == refine(m.T.T)
def test_issue_9817():
from sympy.matrices.expressions import Identity
v = MatrixSymbol('v', 3, 1)
A = MatrixSymbol('A', 3, 3)
x = Matrix([i + 1 for i in range(3)])
X = Identity(3)
quadratic = v.T * A * v
subbed = quadratic.xreplace({v:x, A:X})
assert subbed.as_explicit() == Matrix([[14]])
|
59f4ffbcbace92f3ea460da67fb833895b3fe9c2e0d24393105bfe35bd7322fa | from sympy.core.relational import Eq, is_eq
from sympy.core.basic import Basic
from sympy.core.logic import fuzzy_and, fuzzy_bool
from sympy.logic.boolalg import And
from sympy.multipledispatch import dispatch
from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set
@dispatch(Interval, FiniteSet) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(FiniteSet, Interval) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(Interval, Interval) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
return And(Eq(lhs.left, rhs.left),
Eq(lhs.right, rhs.right),
lhs.left_open == rhs.left_open,
lhs.right_open == rhs.right_open)
@dispatch(FiniteSet, FiniteSet) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
def all_in_both():
s_set = set(lhs.args)
o_set = set(rhs.args)
yield fuzzy_and(lhs._contains(e) for e in o_set - s_set)
yield fuzzy_and(rhs._contains(e) for e in s_set - o_set)
return tfn[fuzzy_and(all_in_both())]
@dispatch(ProductSet, ProductSet) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
if len(lhs.sets) != len(rhs.sets):
return False
eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets))
return tfn[fuzzy_and(map(fuzzy_bool, eqs))]
@dispatch(Set, Basic) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(Set, Set) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa: F811
return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])]
|
6b2e6ccc07487cac310ae4832d6e080e05ad115c3c61478a50b2b590a4f25bda | from sympy import S, Symbol
from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or
from sympy.core.relational import Eq
from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet
from sympy.sets.fancysets import Complexes, Reals, Range, Rationals
from sympy.multipledispatch import dispatch
_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes]
@dispatch(Set, Set) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return None
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
# This is correct but can be made more comprehensive...
if fuzzy_bool(a.start < b.start):
return False
if fuzzy_bool(a.end > b.end):
return False
if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))):
return False
if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))):
return False
@dispatch(Interval, FiniteSet) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_fs): # noqa:F811
# An Interval can only be a subset of a finite set if it is finite
# which can only happen if it has zero measure.
if fuzzy_not(a_interval.measure.is_zero):
return False
@dispatch(Interval, Union) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_u): # noqa:F811
if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args):
intervals = [s for s in b_u.args if isinstance(s, Interval)]
if all(fuzzy_bool(a_interval.start < s.start) for s in intervals):
return False
if all(fuzzy_bool(a_interval.end > s.end) for s in intervals):
return False
if a_interval.measure.is_nonzero:
no_overlap = lambda s1, s2: fuzzy_or([
fuzzy_bool(s1.end <= s2.start),
fuzzy_bool(s1.start >= s2.end),
])
if all(no_overlap(s, a_interval) for s in intervals):
return False
@dispatch(Range, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
if a.step == b.step == 1:
return fuzzy_and([fuzzy_bool(a.start >= b.start),
fuzzy_bool(a.stop <= b.stop)])
@dispatch(Range, Interval) # type: ignore # noqa:F811
def is_subset_sets(a_range, b_interval): # noqa:F811
if a_range.step.is_positive:
if b_interval.left_open and a_range.inf.is_finite:
cond_left = a_range.inf > b_interval.left
else:
cond_left = a_range.inf >= b_interval.left
if b_interval.right_open and a_range.sup.is_finite:
cond_right = a_range.sup < b_interval.right
else:
cond_right = a_range.sup <= b_interval.right
return fuzzy_and([cond_left, cond_right])
@dispatch(Range, FiniteSet) # type: ignore # noqa:F811
def is_subset_sets(a_range, b_finiteset): # noqa:F811
try:
a_size = a_range.size
except ValueError:
# symbolic Range of unknown size
return None
if a_size > len(b_finiteset):
return False
elif any(arg.has(Symbol) for arg in a_range.args):
return fuzzy_and(b_finiteset.contains(x) for x in a_range)
else:
# Checking A \ B == EmptySet is more efficient than repeated naive
# membership checks on an arbitrary FiniteSet.
a_set = set(a_range)
b_remaining = len(b_finiteset)
# Symbolic expressions and numbers of unknown type (integer or not) are
# all counted as "candidates", i.e. *potentially* matching some a in
# a_range.
cnt_candidate = 0
for b in b_finiteset:
if b.is_Integer:
a_set.discard(b)
elif fuzzy_not(b.is_integer):
pass
else:
cnt_candidate += 1
b_remaining -= 1
if len(a_set) > b_remaining + cnt_candidate:
return False
if len(a_set) == 0:
return True
return None
@dispatch(Interval, Range) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_range): # noqa:F811
if a_interval.measure.is_extended_nonzero:
return False
@dispatch(Interval, Rationals) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_rationals): # noqa:F811
if a_interval.measure.is_extended_nonzero:
return False
@dispatch(Range, Complexes) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return True
@dispatch(Complexes, Interval) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Complexes, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Complexes, Rationals) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Rationals, Reals) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return True
@dispatch(Rationals, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(ProductSet, FiniteSet) # type: ignore # noqa:F811
def is_subset_sets(a_ps, b_fs): # noqa:F811
return fuzzy_and(b_fs.contains(x) for x in a_ps)
|
1ef5e893fcdf980b4929306d42e420528a996caf3b423c2ab8bf5315863755c0 | from sympy import (Symbol, Set, Union, Interval, oo, S, sympify, nan,
Max, Min, Float, DisjointUnion,
FiniteSet, Intersection, imageset, I, true, false, ProductSet,
sqrt, Complement, EmptySet, sin, cos, Lambda, ImageSet, pi,
Pow, Contains, Sum, rootof, SymmetricDifference, Piecewise,
Matrix, Range, Add, symbols, zoo, Rational)
from mpmath import mpi
from sympy.core.expr import unchanged
from sympy.core.relational import Eq, Ne, Le, Lt, LessThan
from sympy.logic import And, Or, Xor
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.abc import x, y, z, m, n
def test_imageset():
ints = S.Integers
assert imageset(x, x - 1, S.Naturals) is S.Naturals0
assert imageset(x, x + 1, S.Naturals0) is S.Naturals
assert imageset(x, abs(x), S.Naturals0) is S.Naturals0
assert imageset(x, abs(x), S.Naturals) is S.Naturals
assert imageset(x, abs(x), S.Integers) is S.Naturals0
# issue 16878a
r = symbols('r', real=True)
assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None
assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False
assert (r, r) in imageset(x, (x, x), S.Reals)
assert 1 + I in imageset(x, x + I, S.Reals)
assert {1} not in imageset(x, (x,), S.Reals)
assert (1, 1) not in imageset(x, (x,) , S.Reals)
raises(TypeError, lambda: imageset(x, ints))
raises(ValueError, lambda: imageset(x, y, z, ints))
raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y))
assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints)
raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints))
assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints)
def f(x):
return cos(x)
assert imageset(f, ints) == imageset(x, cos(x), ints)
f = lambda x: cos(x)
assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints)
assert imageset(x, 1, ints) == FiniteSet(1)
assert imageset(x, y, ints) == {y}
assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)}
clash = Symbol('x', integer=true)
assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr)
in ('x0 + x', 'x + x0'))
x1, x2 = symbols("x1, x2")
assert imageset(lambda x, y:
Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq(
ImageSet(Lambda((x1, x2), x1 + x2),
Interval(1, 2), Interval(2, 3)))
def test_is_empty():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_empty is False
assert S.EmptySet.is_empty is True
def test_is_finiteset():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_finite_set is False
assert S.EmptySet.is_finite_set is True
assert FiniteSet(1, 2).is_finite_set is True
assert Interval(1, 2).is_finite_set is False
assert Interval(x, y).is_finite_set is None
assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False
assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True
assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None
assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True
assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True
assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None
assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False
assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False
assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True
def test_deprecated_is_EmptySet():
with warns_deprecated_sympy():
S.EmptySet.is_EmptySet
def test_interval_arguments():
assert Interval(0, oo) == Interval(0, oo, False, True)
assert Interval(0, oo).right_open is true
assert Interval(-oo, 0) == Interval(-oo, 0, True, False)
assert Interval(-oo, 0).left_open is true
assert Interval(oo, -oo) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(-oo, -oo) == S.EmptySet
assert Interval(oo, x) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(x, -oo) == S.EmptySet
assert Interval(x, x) == {x}
assert isinstance(Interval(1, 1), FiniteSet)
e = Sum(x, (x, 1, 3))
assert isinstance(Interval(e, e), FiniteSet)
assert Interval(1, 0) == S.EmptySet
assert Interval(1, 1).measure == 0
assert Interval(1, 1, False, True) == S.EmptySet
assert Interval(1, 1, True, False) == S.EmptySet
assert Interval(1, 1, True, True) == S.EmptySet
assert isinstance(Interval(0, Symbol('a')), Interval)
assert Interval(Symbol('a', real=True, positive=True), 0) == S.EmptySet
raises(ValueError, lambda: Interval(0, S.ImaginaryUnit))
raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False)))
raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit))
raises(NotImplementedError, lambda: Interval(0, 1, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y)))
def test_interval_symbolic_end_points():
a = Symbol('a', real=True)
assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3)
assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a)
assert Interval(0, a).contains(1) == LessThan(1, a)
def test_interval_is_empty():
x, y = symbols('x, y')
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
nn = Symbol('nn', nonnegative=True)
assert Interval(1, 2).is_empty == False
assert Interval(3, 3).is_empty == False # FiniteSet
assert Interval(r, r).is_empty == False # FiniteSet
assert Interval(r, r + nn).is_empty == False
assert Interval(x, x).is_empty == False
assert Interval(1, oo).is_empty == False
assert Interval(-oo, oo).is_empty == False
assert Interval(-oo, 1).is_empty == False
assert Interval(x, y).is_empty == None
assert Interval(r, oo).is_empty == False # real implies finite
assert Interval(n, 0).is_empty == False
assert Interval(n, 0, left_open=True).is_empty == False
assert Interval(p, 0).is_empty == True # EmptySet
assert Interval(nn, 0).is_empty == None
assert Interval(n, p).is_empty == False
assert Interval(0, p, left_open=True).is_empty == False
assert Interval(0, p, right_open=True).is_empty == False
assert Interval(0, nn, left_open=True).is_empty == None
assert Interval(0, nn, right_open=True).is_empty == None
def test_union():
assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4)
assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \
Interval(1, 3, False, True)
assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \
Interval(1, 3, True, True)
assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \
Interval(1, 3)
assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \
Interval(1, 3)
assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2)
assert Union(S.EmptySet) == S.EmptySet
assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \
Interval(0, 1)
# issue #18241:
x = Symbol('x')
assert Union(Interval(0, 1), FiniteSet(1, x)) == Union(
Interval(0, 1), FiniteSet(x))
assert unchanged(Union, Interval(0, 1), FiniteSet(2, x))
assert Interval(1, 2).union(Interval(2, 3)) == \
Interval(1, 2) + Interval(2, 3)
assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3)
assert Union(Set()) == Set()
assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3)
assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs')
assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3)
assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3)
assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4)
assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet
assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3)
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \
FiniteSet(x, FiniteSet(y, z))
# Test that Intervals and FiniteSets play nicely
assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3)
assert Interval(1, 3, True, True) + FiniteSet(3) == \
Interval(1, 3, True, False)
X = Interval(1, 3) + FiniteSet(5)
Y = Interval(1, 2) + FiniteSet(3)
XandY = X.intersect(Y)
assert 2 in X and 3 in X and 3 in XandY
assert XandY.is_subset(X) and XandY.is_subset(Y)
raises(TypeError, lambda: Union(1, 2, 3))
assert X.is_iterable is False
# issue 7843
assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \
FiniteSet(-sqrt(-I), sqrt(-I))
assert Union(S.Reals, S.Integers) == S.Reals
def test_union_iter():
# Use Range because it is ordered
u = Union(Range(3), Range(5), Range(4), evaluate=False)
# Round robin
assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4]
def test_union_is_empty():
assert (Interval(x, y) + FiniteSet(1)).is_empty == False
assert (Interval(x, y) + Interval(-x, y)).is_empty == None
def test_difference():
assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True)
assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True)
assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True)
assert Interval(1, 3, True) - Interval(2, 3, True) == \
Interval(1, 2, True, False)
assert Interval(0, 2) - FiniteSet(1) == \
Union(Interval(0, 1, False, True), Interval(1, 2, True, False))
# issue #18119
assert S.Reals - FiniteSet(I) == S.Reals
assert S.Reals - FiniteSet(-I, I) == S.Reals
assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10)
assert Interval(0, 10) - FiniteSet(1, I) == Union(
Interval.Ropen(0, 1), Interval.Lopen(1, 10))
assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement(
Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2),
evaluate=False)
assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3)
assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \
FiniteSet(1, 2)
assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4)
assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert -1 in S.Reals - S.Naturals
def test_Complement():
A = FiniteSet(1, 3, 4)
B = FiniteSet(3, 4)
C = Interval(1, 3)
D = Interval(1, 2)
assert Complement(A, B, evaluate=False).is_iterable is True
assert Complement(A, C, evaluate=False).is_iterable is True
assert Complement(C, D, evaluate=False).is_iterable is None
assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1)
assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4)
raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False)))
assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True)
assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1)
assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)),
Interval(1, 3)) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False)
assert -1 in Complement(S.Reals, S.Naturals, evaluate=False)
assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False)
assert Complement(S.Integers, S.UniversalSet) == EmptySet
assert S.UniversalSet.complement(S.Integers) == EmptySet
assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0)))
assert S.EmptySet - S.Integers == S.EmptySet
assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1)
assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \
Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi))
# issue 12712
assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \
Complement(FiniteSet(x, y), Interval(-10, 10))
A = FiniteSet(*symbols('a:c'))
B = FiniteSet(*symbols('d:f'))
assert unchanged(Complement, ProductSet(A, A), B)
A2 = ProductSet(A, A)
B3 = ProductSet(B, B, B)
assert A2 - B3 == A2
assert B3 - A2 == B3
def test_set_operations_nonsets():
'''Tests that e.g. FiniteSet(1) * 2 raises TypeError'''
ops = [
lambda a, b: a + b,
lambda a, b: a - b,
lambda a, b: a * b,
lambda a, b: a / b,
lambda a, b: a // b,
lambda a, b: a | b,
lambda a, b: a & b,
lambda a, b: a ^ b,
# FiniteSet(1) ** 2 gives a ProductSet
#lambda a, b: a ** b,
]
Sx = FiniteSet(x)
Sy = FiniteSet(y)
sets = [
{1},
FiniteSet(1),
Interval(1, 2),
Union(Sx, Interval(1, 2)),
Intersection(Sx, Sy),
Complement(Sx, Sy),
ProductSet(Sx, Sy),
S.EmptySet,
]
nums = [0, 1, 2, S(0), S(1), S(2)]
for si in sets:
for ni in nums:
for op in ops:
raises(TypeError, lambda : op(si, ni))
raises(TypeError, lambda : op(ni, si))
raises(TypeError, lambda: si ** object())
raises(TypeError, lambda: si ** {1})
def test_complement():
assert Interval(0, 1).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True))
assert Interval(0, 1, True, False).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True))
assert Interval(0, 1, False, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True))
assert Interval(0, 1, True, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True))
assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet
assert S.UniversalSet.complement(S.Reals) == S.EmptySet
assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet
assert S.EmptySet.complement(S.Reals) == S.Reals
assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True),
Interval(3, oo, True, True))
assert FiniteSet(0).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True))
assert (FiniteSet(5) + Interval(S.NegativeInfinity,
0)).complement(S.Reals) == \
Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True)
assert FiniteSet(1, 2, 3).complement(S.Reals) == \
Interval(S.NegativeInfinity, 1, True, True) + \
Interval(1, 2, True, True) + Interval(2, 3, True, True) +\
Interval(3, S.Infinity, True, True)
assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x))
assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) +
Interval(0, oo, True, True)
, FiniteSet(x), evaluate=False)
square = Interval(0, 1) * Interval(0, 1)
notsquare = square.complement(S.Reals*S.Reals)
assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(
pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)])
assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)])
def test_intersect1():
assert all(S.Integers.intersection(i) is i for i in
(S.Naturals, S.Naturals0))
assert all(i.intersection(S.Integers) is i for i in
(S.Naturals, S.Naturals0))
s = S.Naturals0
assert S.Naturals.intersection(s) is S.Naturals
assert s.intersection(S.Naturals) is S.Naturals
x = Symbol('x')
assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2)
assert Interval(0, 2).intersect(Interval(1, 2, True)) == \
Interval(1, 2, True)
assert Interval(0, 2, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, False)
assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, True)
assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \
Union(Interval(0, 1), Interval(2, 2))
assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2)
assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x)
assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \
FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet
assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \
Union(Interval(0, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \
S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \
S.EmptySet
assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \
Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5)))
assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \
Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False)
assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
# XXX: Is the real=True necessary here?
# https://github.com/sympy/sympy/issues/17532
m, n = symbols('m, n', real=True)
assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \
FiniteSet(m)
# issue 8217
assert Intersection(FiniteSet(x), FiniteSet(y)) == \
Intersection(FiniteSet(x), FiniteSet(y), evaluate=False)
assert FiniteSet(x).intersect(S.Reals) == \
Intersection(S.Reals, FiniteSet(x), evaluate=False)
# tests for the intersection alias
assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
def test_intersection():
# iterable
i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
assert i.is_iterable
assert set(i) == {S(2), S(3)}
# challenging intervals
x = Symbol('x', real=True)
i = Intersection(Interval(0, 3), Interval(x, 6))
assert (5 in i) is False
raises(TypeError, lambda: 2 in i)
# Singleton special cases
assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet
assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x)
# Products
line = Interval(0, 5)
i = Intersection(line**2, line**3, evaluate=False)
assert (2, 2) not in i
assert (2, 2, 2) not in i
raises(TypeError, lambda: list(i))
a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False)
assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals])
assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet
# issue 12178
assert Intersection() == S.UniversalSet
# issue 16987
assert Intersection({1}, {1}, {x}) == Intersection({1}, {x})
def test_issue_9623():
n = Symbol('n')
a = S.Reals
b = Interval(0, oo)
c = FiniteSet(n)
assert Intersection(a, b, c) == Intersection(b, c)
assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet
def test_is_disjoint():
assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True
def test_ProductSet__len__():
A = FiniteSet(1, 2)
B = FiniteSet(1, 2, 3)
assert ProductSet(A).__len__() == 2
assert ProductSet(A).__len__() is not S(2)
assert ProductSet(A, B).__len__() == 6
assert ProductSet(A, B).__len__() is not S(6)
def test_ProductSet():
# ProductSet is always a set of Tuples
assert ProductSet(S.Reals) == S.Reals ** 1
assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2
assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3
assert ProductSet(S.Reals) != S.Reals
assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten()
assert 1 not in ProductSet(S.Reals)
assert (1,) in ProductSet(S.Reals)
assert 1 not in ProductSet(S.Reals, S.Reals)
assert (1, 2) in ProductSet(S.Reals, S.Reals)
assert (1, I) not in ProductSet(S.Reals, S.Reals)
assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals)
assert (1, 2, 3) in S.Reals ** 3
assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals
assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals)
assert ProductSet() == FiniteSet(())
assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet
# See GH-17458
for ni in range(5):
Rn = ProductSet(*(S.Reals,) * ni)
assert (1,) * ni in Rn
assert 1 not in Rn
assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals)
S1 = S.Reals
S2 = S.Integers
x1 = pi
x2 = 3
assert x1 in S1
assert x2 in S2
assert (x1, x2) in S1 * S2
S3 = S1 * S2
x3 = (x1, x2)
assert x3 in S3
assert (x3, x3) in S3 * S3
assert x3 + x3 not in S3 * S3
raises(ValueError, lambda: S.Reals**-1)
with warns_deprecated_sympy():
ProductSet(FiniteSet(s) for s in range(2))
raises(TypeError, lambda: ProductSet(None))
S1 = FiniteSet(1, 2)
S2 = FiniteSet(3, 4)
S3 = ProductSet(S1, S2)
assert (S3.as_relational(x, y)
== And(S1.as_relational(x), S2.as_relational(y))
== And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4))))
raises(ValueError, lambda: S3.as_relational(x))
raises(ValueError, lambda: S3.as_relational(x, 1))
raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y))
Z2 = ProductSet(S.Integers, S.Integers)
assert Z2.contains((1, 2)) is S.true
assert Z2.contains((1,)) is S.false
assert Z2.contains(x) == Contains(x, Z2, evaluate=False)
assert Z2.contains(x).subs(x, 1) is S.false
assert Z2.contains((x, 1)).subs(x, 2) is S.true
assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False)
assert unchanged(Contains, (x, y), Z2)
assert Contains((1, 2), Z2) is S.true
def test_ProductSet_of_single_arg_is_not_arg():
assert unchanged(ProductSet, Interval(0, 1))
assert unchanged(ProductSet, ProductSet(Interval(0, 1)))
def test_ProductSet_is_empty():
assert ProductSet(S.Integers, S.Reals).is_empty == False
assert ProductSet(Interval(x, 1), S.Reals).is_empty == None
def test_interval_subs():
a = Symbol('a', real=True)
assert Interval(0, a).subs(a, 2) == Interval(0, 2)
assert Interval(a, 0).subs(a, 2) == S.EmptySet
def test_interval_to_mpi():
assert Interval(0, 1).to_mpi() == mpi(0, 1)
assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1)
assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1))
def test_set_evalf():
assert Interval(S(11)/64, S.Half).evalf() == Interval(
Float('0.171875'), Float('0.5'))
assert Interval(x, S.Half, right_open=True).evalf() == Interval(
x, Float('0.5'), right_open=True)
assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5'))
assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x)
def test_measure():
a = Symbol('a', real=True)
assert Interval(1, 3).measure == 2
assert Interval(0, a).measure == a
assert Interval(1, a).measure == a - 1
assert Union(Interval(1, 2), Interval(3, 4)).measure == 2
assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \
== 2
assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0
assert S.EmptySet.measure == 0
square = Interval(0, 10) * Interval(0, 10)
offsetsquare = Interval(5, 15) * Interval(5, 15)
band = Interval(-oo, oo) * Interval(2, 4)
assert square.measure == offsetsquare.measure == 100
assert (square + offsetsquare).measure == 175 # there is some overlap
assert (square - offsetsquare).measure == 75
assert (square * FiniteSet(1, 2, 3)).measure == 0
assert (square.intersect(band)).measure == 20
assert (square + band).measure is oo
assert (band * FiniteSet(1, 2, 3)).measure is nan
def test_is_subset():
assert Interval(0, 1).is_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_subset(Interval(0, 2)) is False
assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False
assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4))
assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False
assert FiniteSet(1).is_subset(Interval(0, 2))
assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False
assert (Interval(1, 2) + FiniteSet(3)).is_subset(
Interval(0, 2, False, True) + FiniteSet(2, 3))
assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True
assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False
assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True
assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True
assert Interval(0, 1).is_subset(S.EmptySet) is False
assert S.EmptySet.is_subset(S.EmptySet) is True
raises(ValueError, lambda: S.EmptySet.is_subset(1))
# tests for the issubset alias
assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True
assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True
assert S.Naturals.is_subset(S.Integers)
assert S.Naturals0.is_subset(S.Integers)
assert FiniteSet(x).is_subset(FiniteSet(y)) is None
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False
assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False
assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False
n = Symbol('n', integer=True)
assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False
assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False
assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True
assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False
assert Range(-oo, 1).is_subset(FiniteSet(1)) is False
assert Range(3).is_subset(FiniteSet(0, 1, n)) is None
assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True
assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False
def test_is_proper_subset():
assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False
assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0))
def test_is_superset():
assert Interval(0, 1).is_superset(Interval(0, 2)) == False
assert Interval(0, 3).is_superset(Interval(0, 2))
assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(1).is_superset(Interval(0, 2)) == False
assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False
assert (Interval(1, 2) + FiniteSet(3)).is_superset(
Interval(0, 2, False, True) + FiniteSet(2, 3)) == False
assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False
assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False
assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False
assert Interval(0, 1).is_superset(S.EmptySet) == True
assert S.EmptySet.is_superset(S.EmptySet) == True
raises(ValueError, lambda: S.EmptySet.is_superset(1))
# tests for the issuperset alias
assert Interval(0, 1).issuperset(S.EmptySet) == True
assert S.EmptySet.issuperset(S.EmptySet) == True
def test_is_proper_superset():
assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False
assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True
assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0))
def test_contains():
assert Interval(0, 2).contains(1) is S.true
assert Interval(0, 2).contains(3) is S.false
assert Interval(0, 2, True, False).contains(0) is S.false
assert Interval(0, 2, True, False).contains(2) is S.true
assert Interval(0, 2, False, True).contains(0) is S.true
assert Interval(0, 2, False, True).contains(2) is S.false
assert Interval(0, 2, True, True).contains(0) is S.false
assert Interval(0, 2, True, True).contains(2) is S.false
assert (Interval(0, 2) in Interval(0, 2)) is False
assert FiniteSet(1, 2, 3).contains(2) is S.true
assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true
assert FiniteSet(y)._contains(x) is None
raises(TypeError, lambda: x in FiniteSet(y))
assert FiniteSet({x, y})._contains({x}) is None
assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True
assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False
# issue 8197
from sympy.abc import a, b
assert isinstance(FiniteSet(b).contains(-a), Contains)
assert isinstance(FiniteSet(b).contains(a), Contains)
assert isinstance(FiniteSet(a).contains(1), Contains)
raises(TypeError, lambda: 1 in FiniteSet(a))
# issue 8209
rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3))
rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3))
s1 = FiniteSet(rad1)
s2 = FiniteSet(rad2)
assert s1 - s2 == S.EmptySet
items = [1, 2, S.Infinity, S('ham'), -1.1]
fset = FiniteSet(*items)
assert all(item in fset for item in items)
assert all(fset.contains(item) is S.true for item in items)
assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true
assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false
assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false
assert S.EmptySet.contains(1) is S.false
assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false
assert rootof(x**5 + x**3 + 1, 0) in S.Reals
assert not rootof(x**5 + x**3 + 1, 1) in S.Reals
# non-bool results
assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \
Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4))
assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \
And(y <= 3, y <= x, S.One <= y, S(2) <= y)
assert (S.Complexes).contains(S.ComplexInfinity) == S.false
def test_interval_symbolic():
x = Symbol('x')
e = Interval(0, 1)
assert e.contains(x) == And(S.Zero <= x, x <= 1)
raises(TypeError, lambda: x in e)
e = Interval(0, 1, True, True)
assert e.contains(x) == And(S.Zero < x, x < 1)
c = Symbol('c', real=False)
assert Interval(x, x + 1).contains(c) == False
e = Symbol('e', extended_real=True)
assert Interval(-oo, oo).contains(e) == And(
S.NegativeInfinity < e, e < S.Infinity)
def test_union_contains():
x = Symbol('x')
i1 = Interval(0, 1)
i2 = Interval(2, 3)
i3 = Union(i1, i2)
assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3))
raises(TypeError, lambda: x in i3)
e = i3.contains(x)
assert e == i3.as_relational(x)
assert e.subs(x, -0.5) is false
assert e.subs(x, 0.5) is true
assert e.subs(x, 1.5) is false
assert e.subs(x, 2.5) is true
assert e.subs(x, 3.5) is false
U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6)
assert all(el not in U for el in [0, 4, -oo])
assert all(el in U for el in [2, 5, 10])
def test_is_number():
assert Interval(0, 1).is_number is False
assert Set().is_number is False
def test_Interval_is_left_unbounded():
assert Interval(3, 4).is_left_unbounded is False
assert Interval(-oo, 3).is_left_unbounded is True
assert Interval(Float("-inf"), 3).is_left_unbounded is True
def test_Interval_is_right_unbounded():
assert Interval(3, 4).is_right_unbounded is False
assert Interval(3, oo).is_right_unbounded is True
assert Interval(3, Float("+inf")).is_right_unbounded is True
def test_Interval_as_relational():
x = Symbol('x')
assert Interval(-1, 2, False, False).as_relational(x) == \
And(Le(-1, x), Le(x, 2))
assert Interval(-1, 2, True, False).as_relational(x) == \
And(Lt(-1, x), Le(x, 2))
assert Interval(-1, 2, False, True).as_relational(x) == \
And(Le(-1, x), Lt(x, 2))
assert Interval(-1, 2, True, True).as_relational(x) == \
And(Lt(-1, x), Lt(x, 2))
assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2))
assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2))
assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo))
assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo))
assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo))
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert Interval(x, y).as_relational(x) == (x <= y)
assert Interval(y, x).as_relational(x) == (y <= x)
def test_Finite_as_relational():
x = Symbol('x')
y = Symbol('y')
assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
def test_Union_as_relational():
x = Symbol('x')
assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
And(Lt(0, x), Le(x, 1))
def test_Intersection_as_relational():
x = Symbol('x')
assert (Intersection(Interval(0, 1), FiniteSet(2),
evaluate=False).as_relational(x)
== And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
def test_Complement_as_relational():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == \
And(Le(0, x), Le(x, 1), Ne(x, 2))
@XFAIL
def test_Complement_as_relational_fail():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
# XXX This example fails because 0 <= x changes to x >= 0
# during the evaluation.
assert expr.as_relational(x) == \
(0 <= x) & (x <= 1) & Ne(x, 2)
def test_SymmetricDifference_as_relational():
x = Symbol('x')
expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1))
def test_EmptySet():
assert S.EmptySet.as_relational(Symbol('x')) is S.false
assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet
assert S.EmptySet.boundary == S.EmptySet
def test_finite_basic():
x = Symbol('x')
A = FiniteSet(1, 2, 3)
B = FiniteSet(3, 4, 5)
AorB = Union(A, B)
AandB = A.intersect(B)
assert A.is_subset(AorB) and B.is_subset(AorB)
assert AandB.is_subset(A)
assert AandB == FiniteSet(3)
assert A.inf == 1 and A.sup == 3
assert AorB.inf == 1 and AorB.sup == 5
assert FiniteSet(x, 1, 5).sup == Max(x, 5)
assert FiniteSet(x, 1, 5).inf == Min(x, 1)
# issue 7335
assert FiniteSet(S.EmptySet) != S.EmptySet
assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3)
assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3)
# Ensure a variety of types can exist in a FiniteSet
assert FiniteSet((1, 2), Float, A, -5, x, 'eggs', x**2, Interval)
assert (A > B) is False
assert (A >= B) is False
assert (A < B) is False
assert (A <= B) is False
assert AorB > A and AorB > B
assert AorB >= A and AorB >= B
assert A >= A and A <= A
assert A >= AandB and B >= AandB
assert A > AandB and B > AandB
assert FiniteSet(1.0) == FiniteSet(1)
def test_product_basic():
H, T = 'H', 'T'
unit_line = Interval(0, 1)
d6 = FiniteSet(1, 2, 3, 4, 5, 6)
d4 = FiniteSet(1, 2, 3, 4)
coin = FiniteSet(H, T)
square = unit_line * unit_line
assert (0, 0) in square
assert 0 not in square
assert (H, T) in coin ** 2
assert (.5, .5, .5) in (square * unit_line).flatten()
assert ((.5, .5), .5) in square * unit_line
assert (H, 3, 3) in (coin * d6 * d6).flatten()
assert ((H, 3), 3) in coin * d6 * d6
HH, TT = sympify(H), sympify(T)
assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}
assert (d4*d4).is_subset(d6*d6)
assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True))*Interval(-oo, oo),
Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True)))
assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)
assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square
assert len(coin*coin*coin) == 8
assert len(S.EmptySet*S.EmptySet) == 0
assert len(S.EmptySet*coin) == 0
raises(TypeError, lambda: len(coin*Interval(0, 2)))
def test_real():
x = Symbol('x', real=True, finite=True)
I = Interval(0, 5)
J = Interval(10, 20)
A = FiniteSet(1, 2, 30, x, S.Pi)
B = FiniteSet(-4, 0)
C = FiniteSet(100)
D = FiniteSet('Ham', 'Eggs')
assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C])
assert not D.is_subset(S.Reals)
assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C])
assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D])
assert not (I + A + D).is_subset(S.Reals)
def test_supinf():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert (Interval(0, 1) + FiniteSet(2)).sup == 2
assert (Interval(0, 1) + FiniteSet(2)).inf == 0
assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x)
assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x)
assert FiniteSet(5, 1, x).sup == Max(5, x)
assert FiniteSet(5, 1, x).inf == Min(1, x)
assert FiniteSet(5, 1, x, y).sup == Max(5, x, y)
assert FiniteSet(5, 1, x, y).inf == Min(1, x, y)
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \
S.Infinity
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \
S.NegativeInfinity
assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs')
def test_universalset():
U = S.UniversalSet
x = Symbol('x')
assert U.as_relational(x) is S.true
assert U.union(Interval(2, 4)) == U
assert U.intersect(Interval(2, 4)) == Interval(2, 4)
assert U.measure is S.Infinity
assert U.boundary == S.EmptySet
assert U.contains(0) is S.true
def test_Union_of_ProductSets_shares():
line = Interval(0, 2)
points = FiniteSet(0, 1, 2)
assert Union(line * line, line * points) == line * line
def test_Interval_free_symbols():
# issue 6211
assert Interval(0, 1).free_symbols == set()
x = Symbol('x', real=True)
assert Interval(0, x).free_symbols == {x}
def test_image_interval():
from sympy.core.numbers import Rational
x = Symbol('x', real=True)
a = Symbol('a', real=True)
assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
Interval(-4, 2, True, False)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
Interval(0, 4, False, True)
assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
Interval(-35, 0) # Multiple Maxima
assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
+ Interval(2, oo) # Single Infinite discontinuity
assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities
# Test for Python lambda
assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
ImageSet(Lambda(x, a*x), Interval(0, 1))
assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
def test_image_piecewise():
f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True))
f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True))
assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo))
assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1)
@XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826
def test_image_Intersection():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \
Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2)))
def test_image_FiniteSet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6)
def test_image_Union():
x = Symbol('x', real=True)
assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \
(Interval(0, 4) + FiniteSet(9))
def test_image_EmptySet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, S.EmptySet) == S.EmptySet
def test_issue_5724_7680():
assert I not in S.Reals # issue 7680
assert Interval(-oo, oo).contains(I) is S.false
def test_boundary():
assert FiniteSet(1).boundary == FiniteSet(1)
assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1)
for left_open in (true, false) for right_open in (true, false))
def test_boundary_Union():
assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3)
assert ((Interval(0, 1, False, True)
+ Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2))
assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2)
assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \
== FiniteSet(0, 10)
assert Union(Interval(0, 10, True, True),
Interval(10, 15, True, True), evaluate=False).boundary \
== FiniteSet(0, 10, 15)
@XFAIL
def test_union_boundary_of_joining_sets():
""" Testing the boundary of unions is a hard problem """
assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
def test_boundary_ProductSet():
open_square = Interval(0, 1, True, True) ** 2
assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1))
second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True)
assert (open_square + second_square).boundary == (
FiniteSet(0, 1) * Interval(0, 1)
+ FiniteSet(1, 2) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1)
+ Interval(1, 2) * FiniteSet(0, 1))
def test_boundary_ProductSet_line():
line_in_r2 = Interval(0, 1) * FiniteSet(0)
assert line_in_r2.boundary == line_in_r2
def test_is_open():
assert Interval(0, 1, False, False).is_open is False
assert Interval(0, 1, True, False).is_open is False
assert Interval(0, 1, True, True).is_open is True
assert FiniteSet(1, 2, 3).is_open is False
def test_is_closed():
assert Interval(0, 1, False, False).is_closed is True
assert Interval(0, 1, True, False).is_closed is False
assert FiniteSet(1, 2, 3).is_closed is True
def test_closure():
assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False)
def test_interior():
assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True)
def test_issue_7841():
raises(TypeError, lambda: x in S.Reals)
def test_Eq():
assert Eq(Interval(0, 1), Interval(0, 1))
assert Eq(Interval(0, 1), Interval(0, 2)) == False
s1 = FiniteSet(0, 1)
s2 = FiniteSet(1, 2)
assert Eq(s1, s1)
assert Eq(s1, s2) == False
assert Eq(s1*s2, s1*s2)
assert Eq(s1*s2, s2*s1) == False
assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x}))
assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true
assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false
assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false
assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false
assert Eq(FiniteSet(()), FiniteSet(1)) is S.false
assert Eq(ProductSet(), FiniteSet(1)) is S.false
i1 = Interval(0, 1)
i2 = Interval(x, y)
assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2))
def test_SymmetricDifference():
A = FiniteSet(0, 1, 2, 3, 4, 5)
B = FiniteSet(2, 4, 6, 8, 10)
C = Interval(8, 10)
assert SymmetricDifference(A, B, evaluate=False).is_iterable is True
assert SymmetricDifference(A, C, evaluate=False).is_iterable is None
assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \
FiniteSet(0, 1, 3, 5, 6, 8, 10)
raises(TypeError,
lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False)))
assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \
FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10)
assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3 , 4 , 5)) \
== FiniteSet(5)
assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \
FiniteSet(3, 4, 6)
assert Set(1, 2 , 3) ^ Set(2, 3, 4) == Union(Set(1, 2, 3) - Set(2, 3, 4), \
Set(2, 3, 4) - Set(1, 2, 3))
assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \
Interval(2, 5), Interval(2, 5) - Interval(0, 4))
def test_issue_9536():
from sympy.functions.elementary.exponential import log
a = Symbol('a', real=True)
assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
def test_issue_9637():
n = Symbol('n')
a = FiniteSet(n)
b = FiniteSet(2, n)
assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
assert Complement(Interval(1, 3), b) == \
Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
def test_issue_9808():
# See https://github.com/sympy/sympy/issues/16342
assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
def test_issue_9956():
assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
assert Interval(-oo, oo).contains(1) is S.true
def test_issue_Symbol_inter():
i = Interval(0, oo)
r = S.Reals
mat = Matrix([0, 0, 0])
assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \
Intersection(i, FiniteSet(m))
assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \
Intersection(i, FiniteSet(m, n))
assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \
Intersection(Intersection({m, z}, {m, n, x}), r)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \
Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \
Intersection(FiniteSet(3, m, n), r)
assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \
Intersection(r, FiniteSet(n))
assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \
Intersection(r, FiniteSet(sin(x), cos(x)))
assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
Intersection(r, FiniteSet(x**2, sin(x)))
def test_issue_11827():
assert S.Naturals0**4
def test_issue_10113():
f = x**2/(x**2 - 4)
assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo))
def test_issue_10248():
raises(
TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x)))
)
A = Symbol('A', real=True)
assert list(Intersection(S.Reals, FiniteSet(A))) == [A]
def test_issue_9447():
a = Interval(0, 1) + Interval(2, 3)
assert Complement(S.UniversalSet, a) == Complement(
S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
assert Complement(S.Naturals, a) == Complement(
S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
def test_issue_10337():
assert (FiniteSet(2) == 3) is False
assert (FiniteSet(2) != 3) is True
raises(TypeError, lambda: FiniteSet(2) < 3)
raises(TypeError, lambda: FiniteSet(2) <= 3)
raises(TypeError, lambda: FiniteSet(2) > 3)
raises(TypeError, lambda: FiniteSet(2) >= 3)
def test_issue_10326():
bad = [
EmptySet,
FiniteSet(1),
Interval(1, 2),
S.ComplexInfinity,
S.ImaginaryUnit,
S.Infinity,
S.NaN,
S.NegativeInfinity,
]
interval = Interval(0, 5)
for i in bad:
assert i not in interval
x = Symbol('x', real=True)
nr = Symbol('nr', extended_real=False)
assert x + 1 in Interval(x, x + 4)
assert nr not in Interval(x, x + 4)
assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2))
assert Interval(-oo, oo).contains(oo) is S.false
assert Interval(-oo, oo).contains(-oo) is S.false
def test_issue_2799():
U = S.UniversalSet
a = Symbol('a', real=True)
inf_interval = Interval(a, oo)
R = S.Reals
assert U + inf_interval == inf_interval + U
assert U + R == R + U
assert R + inf_interval == inf_interval + R
def test_issue_9706():
assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False)
assert Interval(0, oo).closure == Interval(0, oo, False, True)
assert Interval(-oo, oo).closure == Interval(-oo, oo)
def test_issue_8257():
reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo))
reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo))
assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity
assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity
assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity
assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity
def test_issue_10931():
assert S.Integers - S.Integers == EmptySet
assert S.Integers - S.Reals == EmptySet
def test_issue_11174():
soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False)
assert Intersection(FiniteSet(-x), S.Reals) == soln
soln = Intersection(S.Reals, FiniteSet(x), evaluate=False)
assert Intersection(FiniteSet(x), S.Reals) == soln
def test_issue_18505():
assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \
Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers))
def test_finite_set_intersection():
# The following should not produce recursion errors
# Note: some of these are not completely correct. See
# https://github.com/sympy/sympy/issues/16342.
assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \
Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y))
assert FiniteSet(1+x-y) & FiniteSet(1) == \
FiniteSet(1) & FiniteSet(1+x-y) == \
Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False)
assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \
Intersection(FiniteSet(1), FiniteSet(x), evaluate=False)
assert FiniteSet({x}) & FiniteSet({x, y}) == \
Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False)
def test_union_intersection_constructor():
# The actual exception does not matter here, so long as these fail
sets = [FiniteSet(1), FiniteSet(2)]
raises(Exception, lambda: Union(sets))
raises(Exception, lambda: Intersection(sets))
raises(Exception, lambda: Union(tuple(sets)))
raises(Exception, lambda: Intersection(tuple(sets)))
raises(Exception, lambda: Union(i for i in sets))
raises(Exception, lambda: Intersection(i for i in sets))
# Python sets are treated the same as FiniteSet
# The union of a single set (of sets) is the set (of sets) itself
assert Union(set(sets)) == FiniteSet(*sets)
assert Intersection(set(sets)) == FiniteSet(*sets)
assert Union({1}, {2}) == FiniteSet(1, 2)
assert Intersection({1, 2}, {2, 3}) == FiniteSet(2)
def test_Union_contains():
assert zoo not in Union(
Interval.open(-oo, 0), Interval.open(0, oo))
@XFAIL
def test_issue_16878b():
# in intersection_sets for (ImageSet, Set) there is no code
# that handles the base_set of S.Reals like there is
# for Integers
assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True
def test_DisjointUnion():
assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2))
assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1))
assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1))
assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1)
assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0)
assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet
assert DisjointUnion().rewrite(Union) == S.EmptySet
raises(TypeError, lambda: DisjointUnion(Symbol('n')))
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1))
def test_DisjointUnion_is_empty():
assert DisjointUnion(S.EmptySet).is_empty is True
assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True
assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False
def test_DisjointUnion_is_iterable():
assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True
assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False
assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True
assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False
def test_DisjointUnion_contains():
assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5))
assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
def test_DisjointUnion_iter():
D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))
it = iter(D)
L1 = [(x, 1), (y, 1), (z, 1)]
L2 = [(3, 0), (5, 0), (7, 0), (9, 0)]
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
raises(StopIteration, lambda: next(it))
raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet)))
def test_DisjointUnion_len():
assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7
assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3
raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet)))
def test_issue_20089():
B = FiniteSet(FiniteSet(1, 2), FiniteSet(1))
assert not 1 in B
assert not 1.0 in B
assert not Eq(1, FiniteSet(1, 2))
assert FiniteSet(1) in B
A = FiniteSet(1, 2)
assert A in B
assert B.issubset(B)
assert not A.issubset(B)
assert 1 in A
C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2)
assert A.issubset(C)
assert B.issubset(C)
def test_issue_19378():
a = FiniteSet(1, 2)
b = ProductSet(a, a)
c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2))
assert b.is_subset(c) is True
d = FiniteSet(1)
assert b.is_subset(d) is False
assert Eq(c, b).simplify() is S.true
assert Eq(a, c).simplify() is S.false
assert Eq({1}, {x}).simplify() == Eq({1}, {x})
def test_issue_20379():
#https://github.com/sympy/sympy/issues/20379
x = pi - 3.14159265358979
assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2))
def test_finiteset_simplify():
S = FiniteSet(1, cos(1)**2 + sin(1)**2)
assert S.simplify() == {1}
|
56e11a7af4bd44130b5135e542cc8881444127c18ba178959191b48c76619e4a | #!/usr/bin/env python
"""Distutils based setup script for SymPy.
This uses Distutils (https://python.org/sigs/distutils-sig/) the standard
python mechanism for installing packages. Optionally, you can use
Setuptools (https://setuptools.readthedocs.io/en/latest/)
to automatically handle dependencies. For the easiest installation
just type the command (you'll probably need root privileges for that):
python setup.py install
This will install the library in the default location. For instructions on
how to customize the install procedure read the output of:
python setup.py --help install
In addition, there are some other commands:
python setup.py clean -> will clean all trash (*.pyc and stuff)
python setup.py test -> will run the complete test suite
python setup.py bench -> will run the complete benchmark suite
python setup.py audit -> will run pyflakes checker on source code
To get a full list of available commands, read the output of:
python setup.py --help-commands
Or, if all else fails, feel free to write to the sympy list at
[email protected] and ask for help.
"""
import sys
import os
import shutil
import glob
import subprocess
from distutils.command.sdist import sdist
min_mpmath_version = '0.19'
# This directory
dir_setup = os.path.dirname(os.path.realpath(__file__))
extra_kwargs = {}
try:
from setuptools import setup, Command
extra_kwargs['zip_safe'] = False
extra_kwargs['entry_points'] = {
'console_scripts': [
'isympy = isympy:main',
]
}
except ImportError:
from distutils.core import setup, Command
extra_kwargs['scripts'] = ['bin/isympy']
# handle mpmath deps in the hard way:
from distutils.version import LooseVersion
try:
import mpmath
if mpmath.__version__ < LooseVersion(min_mpmath_version):
raise ImportError
except ImportError:
print("Please install the mpmath package with a version >= %s"
% min_mpmath_version)
sys.exit(-1)
if sys.version_info < (3, 6):
print("SymPy requires Python 3.6 or newer. Python %d.%d detected"
% sys.version_info[:2])
sys.exit(-1)
# Check that this list is uptodate against the result of the command:
# python bin/generate_module_list.py
modules = [
'sympy.algebras',
'sympy.assumptions',
'sympy.assumptions.handlers',
'sympy.assumptions.predicates',
'sympy.benchmarks',
'sympy.calculus',
'sympy.categories',
'sympy.codegen',
'sympy.combinatorics',
'sympy.concrete',
'sympy.core',
'sympy.core.benchmarks',
'sympy.crypto',
'sympy.deprecated',
'sympy.diffgeom',
'sympy.discrete',
'sympy.external',
'sympy.functions',
'sympy.functions.combinatorial',
'sympy.functions.elementary',
'sympy.functions.elementary.benchmarks',
'sympy.functions.special',
'sympy.functions.special.benchmarks',
'sympy.geometry',
'sympy.holonomic',
'sympy.integrals',
'sympy.integrals.benchmarks',
'sympy.integrals.rubi',
'sympy.integrals.rubi.parsetools',
'sympy.integrals.rubi.rubi_tests',
'sympy.integrals.rubi.rules',
'sympy.interactive',
'sympy.liealgebras',
'sympy.logic',
'sympy.logic.algorithms',
'sympy.logic.utilities',
'sympy.matrices',
'sympy.matrices.benchmarks',
'sympy.matrices.expressions',
'sympy.multipledispatch',
'sympy.ntheory',
'sympy.parsing',
'sympy.parsing.autolev',
'sympy.parsing.autolev._antlr',
'sympy.parsing.c',
'sympy.parsing.fortran',
'sympy.parsing.latex',
'sympy.parsing.latex._antlr',
'sympy.physics',
'sympy.physics.continuum_mechanics',
'sympy.physics.control',
'sympy.physics.hep',
'sympy.physics.mechanics',
'sympy.physics.optics',
'sympy.physics.quantum',
'sympy.physics.units',
'sympy.physics.units.definitions',
'sympy.physics.units.systems',
'sympy.physics.vector',
'sympy.plotting',
'sympy.plotting.intervalmath',
'sympy.plotting.pygletplot',
'sympy.polys',
'sympy.polys.agca',
'sympy.polys.benchmarks',
'sympy.polys.domains',
'sympy.polys.matrices',
'sympy.printing',
'sympy.printing.pretty',
'sympy.sandbox',
'sympy.series',
'sympy.series.benchmarks',
'sympy.sets',
'sympy.sets.handlers',
'sympy.simplify',
'sympy.solvers',
'sympy.solvers.benchmarks',
'sympy.solvers.diophantine',
'sympy.solvers.ode',
'sympy.stats',
'sympy.stats.sampling',
'sympy.strategies',
'sympy.strategies.branch',
'sympy.tensor',
'sympy.tensor.array',
'sympy.tensor.array.expressions',
'sympy.testing',
'sympy.unify',
'sympy.utilities',
'sympy.utilities._compilation',
'sympy.utilities.mathml',
'sympy.vector',
]
class audit(Command):
"""Audits SymPy's source code for following issues:
- Names which are used but not defined or used before they are defined.
- Names which are redefined without having been used.
"""
description = "Audit SymPy source with PyFlakes"
user_options = []
def initialize_options(self):
self.all = None
def finalize_options(self):
pass
def run(self):
import os
try:
import pyflakes.scripts.pyflakes as flakes
except ImportError:
print("In order to run the audit, you need to have PyFlakes installed.")
sys.exit(-1)
dirs = (os.path.join(*d) for d in (m.split('.') for m in modules))
warns = 0
for dir in dirs:
for filename in os.listdir(dir):
if filename.endswith('.py') and filename != '__init__.py':
warns += flakes.checkPath(os.path.join(dir, filename))
if warns > 0:
print("Audit finished with total %d warnings" % warns)
class clean(Command):
"""Cleans *.pyc and debian trashs, so you should get the same copy as
is in the VCS.
"""
description = "remove build files"
user_options = [("all", "a", "the same")]
def initialize_options(self):
self.all = None
def finalize_options(self):
pass
def run(self):
curr_dir = os.getcwd()
for root, dirs, files in os.walk(dir_setup):
for file in files:
if file.endswith('.pyc') and os.path.isfile:
os.remove(os.path.join(root, file))
os.chdir(dir_setup)
names = ["python-build-stamp-2.4", "MANIFEST", "build",
"dist", "doc/_build", "sample.tex"]
for f in names:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
for name in glob.glob(os.path.join(dir_setup, "doc", "src", "modules",
"physics", "vector", "*.pdf")):
if os.path.isfile(name):
os.remove(name)
os.chdir(curr_dir)
class test_sympy(Command):
"""Runs all tests under the sympy/ folder
"""
description = "run all tests and doctests; also see bin/test and bin/doctest"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
def run(self):
from sympy.utilities import runtests
runtests.run_all_tests()
class run_benchmarks(Command):
"""Runs all SymPy benchmarks"""
description = "run all benchmarks"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
# we use py.test like architecture:
#
# o collector -- collects benchmarks
# o runner -- executes benchmarks
# o presenter -- displays benchmarks results
#
# this is done in sympy.utilities.benchmarking on top of py.test
def run(self):
from sympy.utilities import benchmarking
benchmarking.main(['sympy'])
class antlr(Command):
"""Generate code with antlr4"""
description = "generate parser code from antlr grammars"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
def run(self):
from sympy.parsing.latex._build_latex_antlr import build_parser
if not build_parser():
sys.exit(-1)
class sdist_sympy(sdist):
def run(self):
# Fetch git commit hash and write down to commit_hash.txt before
# shipped in tarball.
commit_hash = None
commit_hash_filepath = 'doc/commit_hash.txt'
try:
commit_hash = \
subprocess.check_output(['git', 'rev-parse', 'HEAD'])
commit_hash = commit_hash.decode('ascii')
commit_hash = commit_hash.rstrip()
print('Commit hash found : {}.'.format(commit_hash))
print('Writing it to {}.'.format(commit_hash_filepath))
except:
pass
if commit_hash:
with open(commit_hash_filepath, 'w') as f:
f.write(commit_hash)
super(sdist_sympy, self).run()
try:
os.remove(commit_hash_filepath)
print(
'Successfully removed temporary file {}.'
.format(commit_hash_filepath))
except OSError as e:
print("Error deleting %s - %s." % (e.filename, e.strerror))
# Check that this list is uptodate against the result of the command:
# python bin/generate_test_list.py
tests = [
'sympy.algebras.tests',
'sympy.assumptions.tests',
'sympy.calculus.tests',
'sympy.categories.tests',
'sympy.codegen.tests',
'sympy.combinatorics.tests',
'sympy.concrete.tests',
'sympy.core.tests',
'sympy.crypto.tests',
'sympy.deprecated.tests',
'sympy.diffgeom.tests',
'sympy.discrete.tests',
'sympy.external.tests',
'sympy.functions.combinatorial.tests',
'sympy.functions.elementary.tests',
'sympy.functions.special.tests',
'sympy.geometry.tests',
'sympy.holonomic.tests',
'sympy.integrals.rubi.parsetools.tests',
'sympy.integrals.rubi.rubi_tests.tests',
'sympy.integrals.rubi.tests',
'sympy.integrals.tests',
'sympy.interactive.tests',
'sympy.liealgebras.tests',
'sympy.logic.tests',
'sympy.matrices.expressions.tests',
'sympy.matrices.tests',
'sympy.multipledispatch.tests',
'sympy.ntheory.tests',
'sympy.parsing.tests',
'sympy.physics.continuum_mechanics.tests',
'sympy.physics.control.tests',
'sympy.physics.hep.tests',
'sympy.physics.mechanics.tests',
'sympy.physics.optics.tests',
'sympy.physics.quantum.tests',
'sympy.physics.tests',
'sympy.physics.units.tests',
'sympy.physics.vector.tests',
'sympy.plotting.intervalmath.tests',
'sympy.plotting.pygletplot.tests',
'sympy.plotting.tests',
'sympy.polys.agca.tests',
'sympy.polys.domains.tests',
'sympy.polys.matrices.tests',
'sympy.polys.tests',
'sympy.printing.pretty.tests',
'sympy.printing.tests',
'sympy.sandbox.tests',
'sympy.series.tests',
'sympy.sets.tests',
'sympy.simplify.tests',
'sympy.solvers.diophantine.tests',
'sympy.solvers.ode.tests',
'sympy.solvers.tests',
'sympy.stats.sampling.tests',
'sympy.stats.tests',
'sympy.strategies.branch.tests',
'sympy.strategies.tests',
'sympy.tensor.array.expressions.tests',
'sympy.tensor.array.tests',
'sympy.tensor.tests',
'sympy.testing.tests',
'sympy.unify.tests',
'sympy.utilities._compilation.tests',
'sympy.utilities.tests',
'sympy.vector.tests',
]
with open(os.path.join(dir_setup, 'sympy', 'release.py')) as f:
# Defines __version__
exec(f.read())
if __name__ == '__main__':
setup(name='sympy',
version=__version__,
description='Computer algebra system (CAS) in Python',
author='SymPy development team',
author_email='[email protected]',
license='BSD',
keywords="Math CAS",
url='https://sympy.org',
py_modules=['isympy'],
packages=['sympy'] + modules + tests,
ext_modules=[],
package_data={
'sympy.utilities.mathml': ['data/*.xsl'],
'sympy.logic.benchmarks': ['input/*.cnf'],
'sympy.parsing.autolev': [
'*.g4', 'test-examples/*.al', 'test-examples/*.py',
'test-examples/pydy-example-repo/*.al',
'test-examples/pydy-example-repo/*.py',
'test-examples/README.txt',
],
'sympy.parsing.latex': ['*.txt', '*.g4'],
'sympy.integrals.rubi.parsetools': ['header.py.txt'],
'sympy.plotting.tests': ['test_region_*.png'],
},
data_files=[('share/man/man1', ['doc/man/isympy.1'])],
cmdclass={'test': test_sympy,
'bench': run_benchmarks,
'clean': clean,
'audit': audit,
'antlr': antlr,
'sdist': sdist_sympy,
},
python_requires='>=3.6',
classifiers=[
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
install_requires=[
'mpmath>=%s' % min_mpmath_version,
],
**extra_kwargs
)
|
8ed3cd2f3c5c87911b7fe90578dbd0bac14fff843c09c1456ddf589a3a32a806 | """
SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple
as possible in order to be comprehensible and easily extensible. SymPy is
written entirely in Python. It depends on mpmath, and other external libraries
may be optionally for things like plotting support.
See the webpage for more information and documentation:
https://sympy.org
"""
import sys
if sys.version_info < (3, 6):
raise ImportError("Python version 3.6 or above is required for SymPy.")
del sys
try:
import mpmath
except ImportError:
raise ImportError("SymPy now depends on mpmath as an external library. "
"See https://docs.sympy.org/latest/install.html#mpmath for more information.")
del mpmath
from sympy.release import __version__
if 'dev' in __version__:
def enable_warnings():
import warnings
warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
del warnings
enable_warnings()
del enable_warnings
def __sympy_debug():
# helper function so we don't import os globally
import os
debug_str = os.getenv('SYMPY_DEBUG', 'False')
if debug_str in ('True', 'False'):
return eval(debug_str)
else:
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
debug_str)
SYMPY_DEBUG = __sympy_debug() # type: bool
from .core import (sympify, SympifyError, cacheit, Basic, Atom,
preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol,
Wild, Dummy, symbols, var, Number, Float, Rational, Integer,
NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo,
AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log,
Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality,
GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan,
vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass,
Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log,
expand_func, expand_trig, expand_complex, expand_multinomial, nfloat,
expand_power_base, expand_power_exp, arity, PrecisionExhausted, N,
evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate,
Catalan, EulerGamma, GoldenRatio, TribonacciConstant)
from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor,
Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map,
true, false, satisfiable)
from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext,
assuming, Q, ask, register_handler, remove_handler, refine)
from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr,
degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo,
pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert,
subresultants, resultant, discriminant, cofactors, gcd_list, gcd,
lcm_list, lcm, terms_gcd, 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,
is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner,
interpolate, rational_interpolate, viete, together,
BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed,
OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed,
IsomorphismFailed, ExtraneousFactors, EvaluationFailed,
RefinementFailed, CoercionFailed, NotInvertible, NotReversible,
NotAlgebraic, DomainError, PolynomialError, UnificationFailed,
GeneratorsError, GeneratorsNeeded, ComputationFailed,
UnivariatePolynomialError, MultivariatePolynomialError,
PolificationFailed, OptionError, FlagError, minpoly,
minimal_polynomial, primitive_element, field_isomorphism,
to_number_field, isolate, itermonomials, Monomial, lex, grlex,
grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf,
ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing,
RationalField, RealField, ComplexField, PythonFiniteField,
GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational,
GMPYRationalField, AlgebraicField, PolynomialRing, FractionField,
ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python,
QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, construct_domain,
swinnerton_dyer_poly, cyclotomic_poly, symmetric_poly, random_poly,
interpolating_poly, jacobi_poly, chebyshevt_poly, chebyshevu_poly,
hermite_poly, legendre_poly, laguerre_poly, apart, apart_list,
assemble_partfrac_list, Options, ring, xring, vring, sring, field,
xfield, vfield, sfield)
from .series import (Order, O, limit, Limit, gruntz, series, approximants,
residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul,
fourier_series, fps, difference_delta, limit_seq)
from .functions import (factorial, factorial2, rf, ff, binomial,
RisingFactorial, FallingFactorial, subfactorial, carmichael,
fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler,
catalan, genocchi, partition, sqrt, root, Min, Max, Id, real_root,
cbrt, re, im, sign, Abs, conjugate, arg, polar_lift,
periodic_argument, unbranched_argument, principal_branch, transpose,
adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc,
asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log,
LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh,
acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold,
erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, Ei, expint, E1, li,
Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, lowergamma,
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma,
dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, LeviCivita,
KroneckerDelta, SingularityFunction, DiracDelta, Heaviside,
bspline_basis, bspline_basis_set, interpolating_spline, besselj,
bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1,
hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper,
meijerg, appellf1, legendre, assoc_legendre, hermite, chebyshevt,
chebyshevu, chebyshevu_root, chebyshevt_root, laguerre,
assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c,
Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus,
mathieuc, mathieusprime, mathieucprime)
from .ntheory import (nextprime, prevprime, prime, primepi, primerange,
randprime, Sieve, sieve, primorial, cycle_length, composite,
compositepi, isprime, divisors, proper_divisors, factorint,
multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors,
totient, trailing, divisor_count, proper_divisor_count, divisor_sigma,
factorrat, reduced_totient, primenu, primeomega,
mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
is_deficient, is_amicable, abundance, npartitions, is_primitive_root,
is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod,
quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue,
sqrt_mod_iter, mobius, discrete_log, quadratic_congruence,
binomial_coefficients, binomial_coefficients_list,
multinomial_coefficients, continued_fraction_periodic,
continued_fraction_iterator, continued_fraction_reduce,
continued_fraction_convergents, continued_fraction, egyptian_fraction)
from .concrete import product, Product, summation, Sum
from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform,
inverse_mobius_transform, convolution, covering_product,
intersecting_product)
from .simplify import (simplify, hypersimp, hypersimilar, logcombine,
separatevars, posify, besselsimp, kroneckersimp, signsimp, bottom_up,
nsimplify, FU, fu, sqrtdenest, cse, use, epath, EPath, hyperexpand,
collect, rcollect, radsimp, collect_const, fraction, numer, denom,
trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp,
ratsimp, ratsimpmodprime)
from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet,
Range, ComplexRegion, Reals, Contains, ConditionSet, Ordinal,
OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet,
Integers, Rationals)
from .solvers import (solve, solve_linear_system, solve_linear_system_LU,
solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick,
inv_quick, check_assumptions, failing_assumptions, diophantine,
rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol,
classify_ode, dsolve, homogeneous_order, solve_poly_system,
solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul,
pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities,
reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality,
solve_rational_inequalities, solve_univariate_inequality, decompogen,
solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution,
Complexes)
from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt,
casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix,
DeferredVector, MatrixBase, Matrix, MutableMatrix,
MutableSparseMatrix, banded, ImmutableDenseMatrix,
ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice,
BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse,
MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose,
ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols,
Adjoint, hadamard_product, HadamardProduct, HadamardPower,
Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix,
DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct,
PermutationMatrix, MatrixPermute, Permanent, per)
from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D,
Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle,
Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid,
convex_hull, idiff, intersection, closest_points, farthest_points,
GeometryError, Curve, Parabola)
from .utilities import (flatten, group, take, subsets, variations,
numbered_symbols, cartes, capture, dict_merge, postorder_traversal,
interactive_traversal, prefixes, postfixes, sift, topological_sort,
unflatten, has_dups, has_variety, reshape, default_sort_key, ordered,
rotations, filldedent, lambdify, source, threaded, xthreaded, public,
memoize_property, timed)
from .integrals import (integrate, Integral, line_integrate, mellin_transform,
inverse_mellin_transform, MellinTransform, InverseMellinTransform,
laplace_transform, inverse_laplace_transform, LaplaceTransform,
InverseLaplaceTransform, fourier_transform, inverse_fourier_transform,
FourierTransform, InverseFourierTransform, sine_transform,
inverse_sine_transform, SineTransform, InverseSineTransform,
cosine_transform, inverse_cosine_transform, CosineTransform,
InverseCosineTransform, hankel_transform, inverse_hankel_transform,
HankelTransform, InverseHankelTransform, singularityintegrate)
from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure,
get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray,
MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray,
tensorproduct, tensorcontraction, tensordiagonal, derive_by_array,
permutedims, Array, DenseNDimArray, SparseNDimArray)
from .parsing import parse_expr
from .calculus import (euler_equations, singularities, is_increasing,
is_strictly_increasing, is_decreasing, is_strictly_decreasing,
is_monotonic, finite_diff_weights, apply_finite_diff, as_finite_diff,
differentiate_finite, periodicity, not_empty_in, AccumBounds,
is_convex, stationary_points, minimum, maximum)
from .algebras import Quaternion
from .printing import (pager_print, pretty, pretty_print, pprint,
pprint_use_unicode, pprint_try_use_unicode, latex, print_latex,
multiline_latex, mathml, print_mathml, python, print_python, pycode,
ccode, print_ccode, glsl_code, print_glsl, cxxcode, fcode,
print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code,
mathematica_code, octave_code, rust_code, print_gtk, preview, srepr,
print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint,
maple_code, print_maple_code)
from .testing import test, doctest
# This module causes conflicts with other modules:
# from .stats import *
# Adds about .04-.05 seconds of import time
# from combinatorics import *
# This module is slow to import:
#from physics import units
from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
from .interactive import init_session, init_printing
evalf._create_evalf_table()
# This is slow to import:
#import abc
from .deprecated import C, ClassRegistry, class_registry
__all__ = [
# sympy.core
'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom',
'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float',
'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm',
'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp',
'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod',
'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality',
'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan',
'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative',
'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError',
'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig',
'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base',
'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple',
'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan',
'EulerGamma', 'GoldenRatio', 'TribonacciConstant',
# sympy.logic
'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
'bool_map', 'true', 'false', 'satisfiable',
# sympy.assumptions
'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q',
'ask', 'register_handler', 'remove_handler', 'refine',
# sympy.polys
'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
'gcd', 'lcm_list', 'lcm', 'terms_gcd', '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',
'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner',
'interpolate', 'rational_interpolate', 'viete', 'together',
'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
'UnivariatePolynomialError', 'MultivariatePolynomialError',
'PolificationFailed', 'OptionError', 'FlagError', 'minpoly',
'minimal_polynomial', 'primitive_element', 'field_isomorphism',
'to_number_field', 'isolate', 'itermonomials', 'Monomial', 'lex', 'grlex',
'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf',
'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField',
'IntegerRing', 'RationalField', 'RealField', 'ComplexField',
'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain',
'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'construct_domain',
'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly',
'random_poly', 'interpolating_poly', 'jacobi_poly', 'chebyshevt_poly',
'chebyshevu_poly', 'hermite_poly', 'legendre_poly', 'laguerre_poly',
'apart', 'apart_list', 'assemble_partfrac_list', 'Options', 'ring',
'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', 'sfield',
# sympy.series
'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd',
'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq',
# sympy.functions
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas',
'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan',
'genocchi', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root',
'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
'periodic_argument', 'unbranched_argument', 'principal_branch',
'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan',
'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc',
'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh',
'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise',
'piecewise_fold', 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv',
'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi',
'fresnels', 'fresnelc', 'gamma', 'lowergamma', 'uppergamma', 'polygamma',
'loggamma', 'digamma', 'trigamma', 'multigamma', 'dirichlet_eta', 'zeta',
'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita',
'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside',
'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj',
'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn',
'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre',
'assoc_legendre', 'hermite', 'chebyshevt', 'chebyshevu',
'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm',
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta',
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
# sympy.ntheory
'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity',
'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient',
'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma',
'factorrat', 'reduced_totient', 'primenu', 'primeomega',
'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime',
'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions',
'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients',
'binomial_coefficients_list', 'multinomial_coefficients',
'continued_fraction_periodic', 'continued_fraction_iterator',
'continued_fraction_reduce', 'continued_fraction_convergents',
'continued_fraction', 'egyptian_fraction',
# sympy.concrete
'product', 'Product', 'summation', 'Sum',
# sympy.discrete
'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
'inverse_mobius_transform', 'convolution', 'covering_product',
'intersecting_product',
# sympy.simplify
'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
'posify', 'besselsimp', 'kroneckersimp', 'signsimp', 'bottom_up',
'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'use', 'epath', 'EPath',
'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const',
'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp',
'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime',
# sympy.sets
'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference',
'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet',
'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Reals', 'Naturals',
'Naturals0', 'UniversalSet', 'Integers', 'Rationals',
# sympy.solvers
'solve', 'solve_linear_system', 'solve_linear_system_LU',
'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
'solve_poly_system', 'solve_triangulated', 'pde_separate',
'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde',
'checkpdesol', 'ode_order', 'reduce_inequalities',
'reduce_abs_inequality', 'reduce_abs_inequalities',
'solve_poly_inequality', 'solve_rational_inequalities',
'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve',
'linear_eq_to_matrix', 'nonlinsolve', 'substitution', 'Complexes',
# sympy.matrices
'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag',
'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy',
'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1',
'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros',
'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix',
'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix',
'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice',
'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse',
'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace',
'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse',
'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct',
'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix',
'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct',
'kronecker_product', 'KroneckerProduct', 'PermutationMatrix',
'MatrixPermute', 'Permanent', 'per',
# sympy.geometry
'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D',
'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse',
'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola',
# sympy.utilities
'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
'cartes', 'capture', 'dict_merge', 'postorder_traversal',
'interactive_traversal', 'prefixes', 'postfixes', 'sift',
'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
'default_sort_key', 'ordered', 'rotations', 'filldedent', 'lambdify',
'source', 'threaded', 'xthreaded', 'public', 'memoize_property', 'test',
'doctest', 'timed',
# sympy.integrals
'integrate', 'Integral', 'line_integrate', 'mellin_transform',
'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform',
'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform',
'InverseLaplaceTransform', 'fourier_transform',
'inverse_fourier_transform', 'FourierTransform',
'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
'SineTransform', 'InverseSineTransform', 'cosine_transform',
'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
'InverseHankelTransform', 'singularityintegrate',
# sympy.tensor
'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure',
'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray',
# sympy.parsing
'parse_expr',
# sympy.calculus
'euler_equations', 'singularities', 'is_increasing',
'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing',
'is_monotonic', 'finite_diff_weights', 'apply_finite_diff',
'as_finite_diff', 'differentiate_finite', 'periodicity', 'not_empty_in',
'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum',
# sympy.algebras
'Quaternion',
# sympy.printing
'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex',
'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode',
'print_ccode', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode',
'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode',
'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk',
'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr',
'TableForm', 'dotprint', 'maple_code', 'print_maple_code',
# sympy.plotting
'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric',
# sympy.interactive
'init_session', 'init_printing',
# sympy.testing
'test', 'doctest',
# sympy.deprecated:
'C', 'ClassRegistry', 'class_registry',
]
#===========================================================================#
# #
# XXX: The names below were importable before sympy 1.6 using #
# #
# from sympy import * #
# #
# This happened implicitly because there was no __all__ defined in this #
# __init__.py file. Not every package is imported. The list matches what #
# would have been imported before. It is possible that these packages will #
# not be imported by a star-import from sympy in future. #
# #
#===========================================================================#
__all__.extend([
'algebras',
'assumptions',
'calculus',
'concrete',
'deprecated',
'discrete',
'external',
'functions',
'geometry',
'interactive',
'multipledispatch',
'ntheory',
'parsing',
'plotting',
'polys',
'printing',
'release',
'strategies',
'tensor',
'utilities',
])
|
a3673e10a3c2d896cfa32ed64758a5bc39d4059a8ab7750d0df0f6b1b6bfe9f6 | """
Continuous Random Variables - Prebuilt variables
Contains
========
Arcsin
Benini
Beta
BetaNoncentral
BetaPrime
BoundedPareto
Cauchy
Chi
ChiNoncentral
ChiSquared
Dagum
Erlang
ExGaussian
Exponential
ExponentialPower
FDistribution
FisherZ
Frechet
Gamma
GammaInverse
Gumbel
Gompertz
Kumaraswamy
Laplace
Levy
LogCauchy
Logistic
LogLogistic
LogitNormal
LogNormal
Lomax
Maxwell
Moyal
Nakagami
Normal
Pareto
PowerFunction
QuadraticU
RaisedCosine
Rayleigh
Reciprocal
ShiftedGompertz
StudentT
Trapezoidal
Triangular
Uniform
UniformSum
VonMises
Wald
Weibull
WignerSemicircle
"""
from sympy import beta as beta_fn
from sympy import cos, sin, tan, atan, exp, besseli, besselj, besselk
from sympy import (log, sqrt, pi, S, Dummy, Interval, sympify, gamma, sign,
Piecewise, And, Eq, binomial, factorial, Sum, floor, Abs,
Lambda, Basic, lowergamma, erf, erfc, erfi, erfinv, I, asin,
hyper, uppergamma, sinh, Ne, expint, Rational, integrate)
from sympy.matrices import MatrixBase, MatrixExpr
from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDistribution
from sympy.stats.rv import _value_check, is_random
oo = S.Infinity
__all__ = ['ContinuousRV',
'Arcsin',
'Benini',
'Beta',
'BetaNoncentral',
'BetaPrime',
'BoundedPareto',
'Cauchy',
'Chi',
'ChiNoncentral',
'ChiSquared',
'Dagum',
'Erlang',
'ExGaussian',
'Exponential',
'ExponentialPower',
'FDistribution',
'FisherZ',
'Frechet',
'Gamma',
'GammaInverse',
'Gompertz',
'Gumbel',
'Kumaraswamy',
'Laplace',
'Levy',
'LogCauchy',
'Logistic',
'LogLogistic',
'LogitNormal',
'LogNormal',
'Lomax',
'Maxwell',
'Moyal',
'Nakagami',
'Normal',
'GaussianInverse',
'Pareto',
'PowerFunction',
'QuadraticU',
'RaisedCosine',
'Rayleigh',
'Reciprocal',
'StudentT',
'ShiftedGompertz',
'Trapezoidal',
'Triangular',
'Uniform',
'UniformSum',
'VonMises',
'Wald',
'Weibull',
'WignerSemicircle',
]
@is_random.register(MatrixBase)
def _(x):
return any([is_random(i) for i in x])
def rv(symbol, cls, args, **kwargs):
args = list(map(sympify, args))
dist = cls(*args)
if kwargs.pop('check', True):
dist.check(*args)
pspace = SingleContinuousPSpace(symbol, dist)
if any(is_random(arg) for arg in args):
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
pspace = CompoundPSpace(symbol, CompoundDistribution(dist))
return pspace.value
class ContinuousDistributionHandmade(SingleContinuousDistribution):
_argnames = ('pdf',)
def __new__(cls, pdf, set=Interval(-oo, oo)):
return Basic.__new__(cls, pdf, set)
@property
def set(self):
return self.args[1]
@staticmethod
def check(pdf, set):
x = Dummy('x')
val = integrate(pdf(x), (x, set))
_value_check(Eq(val, 1) != S.false, "The pdf on the given set is incorrect.")
def ContinuousRV(symbol, density, set=Interval(-oo, oo), **kwargs):
"""
Create a Continuous Random Variable given the following:
Parameters
==========
symbol : Symbol
Represents name of the random variable.
density : Expression containing symbol
Represents probability density function.
set : set/Interval
Represents the region where the pdf is valid, by default is real line.
check : bool
If True, it will check whether the given density
integrates to 1 over the given set. If False, it
will not perform this check. Default is False.
Returns
=======
RandomSymbol
Many common continuous random variable types are already implemented.
This function should be necessary only very rarely.
Examples
========
>>> from sympy import Symbol, sqrt, exp, pi
>>> from sympy.stats import ContinuousRV, P, E
>>> x = Symbol("x")
>>> pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution
>>> X = ContinuousRV(x, pdf)
>>> E(X)
0
>>> P(X>0)
1/2
"""
pdf = Piecewise((density, set.as_relational(symbol)), (0, True))
pdf = Lambda(symbol, pdf)
# have a default of False while `rv` should have a default of True
kwargs['check'] = kwargs.pop('check', False)
return rv(symbol.name, ContinuousDistributionHandmade, (pdf, set), **kwargs)
########################################
# Continuous Probability Distributions #
########################################
#-------------------------------------------------------------------------------
# Arcsin distribution ----------------------------------------------------------
class ArcsinDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b')
@property
def set(self):
return Interval(self.a, self.b)
def pdf(self, x):
a, b = self.a, self.b
return 1/(pi*sqrt((x - a)*(b - x)))
def _cdf(self, x):
a, b = self.a, self.b
return Piecewise(
(S.Zero, x < a),
(2*asin(sqrt((x - a)/(b - a)))/pi, x <= b),
(S.One, True))
def Arcsin(name, a=0, b=1):
r"""
Create a Continuous Random Variable with an arcsin distribution.
The density of the arcsin distribution is given by
.. math::
f(x) := \frac{1}{\pi\sqrt{(x-a)(b-x)}}
with :math:`x \in (a,b)`. It must hold that :math:`-\infty < a < b < \infty`.
Parameters
==========
a : Real number, the left interval boundary
b : Real number, the right interval boundary
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Arcsin, density, cdf
>>> from sympy import Symbol
>>> a = Symbol("a", real=True)
>>> b = Symbol("b", real=True)
>>> z = Symbol("z")
>>> X = Arcsin("x", a, b)
>>> density(X)(z)
1/(pi*sqrt((-a + z)*(b - z)))
>>> cdf(X)(z)
Piecewise((0, a > z),
(2*asin(sqrt((-a + z)/(-a + b)))/pi, b >= z),
(1, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Arcsine_distribution
"""
return rv(name, ArcsinDistribution, (a, b))
#-------------------------------------------------------------------------------
# Benini distribution ----------------------------------------------------------
class BeniniDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta', 'sigma')
@staticmethod
def check(alpha, beta, sigma):
_value_check(alpha > 0, "Shape parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
_value_check(sigma > 0, "Scale parameter Sigma must be positive.")
@property
def set(self):
return Interval(self.sigma, oo)
def pdf(self, x):
alpha, beta, sigma = self.alpha, self.beta, self.sigma
return (exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2)
*(alpha/x + 2*beta*log(x/sigma)/x))
def _moment_generating_function(self, t):
raise NotImplementedError('The moment generating function of the '
'Benini distribution does not exist.')
def Benini(name, alpha, beta, sigma):
r"""
Create a Continuous Random Variable with a Benini distribution.
The density of the Benini distribution is given by
.. math::
f(x) := e^{-\alpha\log{\frac{x}{\sigma}}
-\beta\log^2\left[{\frac{x}{\sigma}}\right]}
\left(\frac{\alpha}{x}+\frac{2\beta\log{\frac{x}{\sigma}}}{x}\right)
This is a heavy-tailed distribution and is also known as the log-Rayleigh
distribution.
Parameters
==========
alpha : Real number, `\alpha > 0`, a shape
beta : Real number, `\beta > 0`, a shape
sigma : Real number, `\sigma > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Benini, density, cdf
>>> from sympy import Symbol, pprint
>>> alpha = Symbol("alpha", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> sigma = Symbol("sigma", positive=True)
>>> z = Symbol("z")
>>> X = Benini("x", alpha, beta, sigma)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
/ / z \\ / z \ 2/ z \
| 2*beta*log|-----|| - alpha*log|-----| - beta*log |-----|
|alpha \sigma/| \sigma/ \sigma/
|----- + -----------------|*e
\ z z /
>>> cdf(X)(z)
Piecewise((1 - exp(-alpha*log(z/sigma) - beta*log(z/sigma)**2), sigma <= z),
(0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Benini_distribution
.. [2] http://reference.wolfram.com/legacy/v8/ref/BeniniDistribution.html
"""
return rv(name, BeniniDistribution, (alpha, beta, sigma))
#-------------------------------------------------------------------------------
# Beta distribution ------------------------------------------------------------
class BetaDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta')
set = Interval(0, 1)
@staticmethod
def check(alpha, beta):
_value_check(alpha > 0, "Shape parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
def pdf(self, x):
alpha, beta = self.alpha, self.beta
return x**(alpha - 1) * (1 - x)**(beta - 1) / beta_fn(alpha, beta)
def _characteristic_function(self, t):
return hyper((self.alpha,), (self.alpha + self.beta,), I*t)
def _moment_generating_function(self, t):
return hyper((self.alpha,), (self.alpha + self.beta,), t)
def Beta(name, alpha, beta):
r"""
Create a Continuous Random Variable with a Beta distribution.
The density of the Beta distribution is given by
.. math::
f(x) := \frac{x^{\alpha-1}(1-x)^{\beta-1}} {\mathrm{B}(\alpha,\beta)}
with :math:`x \in [0,1]`.
Parameters
==========
alpha : Real number, `\alpha > 0`, a shape
beta : Real number, `\beta > 0`, a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Beta, density, E, variance
>>> from sympy import Symbol, simplify, pprint, factor
>>> alpha = Symbol("alpha", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> z = Symbol("z")
>>> X = Beta("x", alpha, beta)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
alpha - 1 beta - 1
z *(1 - z)
--------------------------
B(alpha, beta)
>>> simplify(E(X))
alpha/(alpha + beta)
>>> factor(simplify(variance(X)))
alpha*beta/((alpha + beta)**2*(alpha + beta + 1))
References
==========
.. [1] https://en.wikipedia.org/wiki/Beta_distribution
.. [2] http://mathworld.wolfram.com/BetaDistribution.html
"""
return rv(name, BetaDistribution, (alpha, beta))
#-------------------------------------------------------------------------------
# Noncentral Beta distribution ------------------------------------------------------------
class BetaNoncentralDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta', 'lamda')
set = Interval(0, 1)
@staticmethod
def check(alpha, beta, lamda):
_value_check(alpha > 0, "Shape parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
_value_check(lamda >= 0, "Noncentrality parameter Lambda must be positive")
def pdf(self, x):
alpha, beta, lamda = self.alpha, self.beta, self.lamda
k = Dummy("k")
return Sum(exp(-lamda / 2) * (lamda / 2)**k * x**(alpha + k - 1) *(
1 - x)**(beta - 1) / (factorial(k) * beta_fn(alpha + k, beta)), (k, 0, oo))
def BetaNoncentral(name, alpha, beta, lamda):
r"""
Create a Continuous Random Variable with a Type I Noncentral Beta distribution.
The density of the Noncentral Beta distribution is given by
.. math::
f(x) := \sum_{k=0}^\infty e^{-\lambda/2}\frac{(\lambda/2)^k}{k!}
\frac{x^{\alpha+k-1}(1-x)^{\beta-1}}{\mathrm{B}(\alpha+k,\beta)}
with :math:`x \in [0,1]`.
Parameters
==========
alpha : Real number, `\alpha > 0`, a shape
beta : Real number, `\beta > 0`, a shape
lamda: Real number, `\lambda >= 0`, noncentrality parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import BetaNoncentral, density, cdf
>>> from sympy import Symbol, pprint
>>> alpha = Symbol("alpha", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> lamda = Symbol("lamda", nonnegative=True)
>>> z = Symbol("z")
>>> X = BetaNoncentral("x", alpha, beta, lamda)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
oo
_____
\ `
\ -lamda
\ k -------
\ k + alpha - 1 /lamda\ beta - 1 2
) z *|-----| *(1 - z) *e
/ \ 2 /
/ ------------------------------------------------
/ B(k + alpha, beta)*k!
/____,
k = 0
Compute cdf with specific 'x', 'alpha', 'beta' and 'lamda' values as follows :
>>> cdf(BetaNoncentral("x", 1, 1, 1), evaluate=False)(2).doit()
2*exp(1/2)
The argument evaluate=False prevents an attempt at evaluation
of the sum for general x, before the argument 2 is passed.
References
==========
.. [1] https://en.wikipedia.org/wiki/Noncentral_beta_distribution
.. [2] https://reference.wolfram.com/language/ref/NoncentralBetaDistribution.html
"""
return rv(name, BetaNoncentralDistribution, (alpha, beta, lamda))
#-------------------------------------------------------------------------------
# Beta prime distribution ------------------------------------------------------
class BetaPrimeDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta')
@staticmethod
def check(alpha, beta):
_value_check(alpha > 0, "Shape parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
set = Interval(0, oo)
def pdf(self, x):
alpha, beta = self.alpha, self.beta
return x**(alpha - 1)*(1 + x)**(-alpha - beta)/beta_fn(alpha, beta)
def BetaPrime(name, alpha, beta):
r"""
Create a continuous random variable with a Beta prime distribution.
The density of the Beta prime distribution is given by
.. math::
f(x) := \frac{x^{\alpha-1} (1+x)^{-\alpha -\beta}}{B(\alpha,\beta)}
with :math:`x > 0`.
Parameters
==========
alpha : Real number, `\alpha > 0`, a shape
beta : Real number, `\beta > 0`, a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import BetaPrime, density
>>> from sympy import Symbol, pprint
>>> alpha = Symbol("alpha", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> z = Symbol("z")
>>> X = BetaPrime("x", alpha, beta)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
alpha - 1 -alpha - beta
z *(z + 1)
-------------------------------
B(alpha, beta)
References
==========
.. [1] https://en.wikipedia.org/wiki/Beta_prime_distribution
.. [2] http://mathworld.wolfram.com/BetaPrimeDistribution.html
"""
return rv(name, BetaPrimeDistribution, (alpha, beta))
#-------------------------------------------------------------------------------
# Bounded Pareto Distribution --------------------------------------------------
class BoundedParetoDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'left', 'right')
@property
def set(self):
return Interval(self.left , self.right)
@staticmethod
def check(alpha, left, right):
_value_check (alpha.is_positive, "Shape must be positive.")
_value_check (left.is_positive, "Left value should be positive.")
_value_check (right > left, "Right should be greater than left.")
def pdf(self, x):
alpha, left, right = self.alpha, self.left, self.right
num = alpha * (left**alpha) * x**(- alpha -1)
den = 1 - (left/right)**alpha
return num/den
def BoundedPareto(name, alpha, left, right):
r"""
Create a continuous random variable with a Bounded Pareto distribution.
The density of the Bounded Pareto distribution is given by
.. math::
f(x) := \frac{\alpha L^{\alpha}x^{-\alpha-1}}{1-(\frac{L}{H})^{\alpha}}
Parameters
==========
alpha : Real Number, `alpha > 0`
Shape parameter
left : Real Number, `left > 0`
Location parameter
right : Real Number, `right > left`
Location parameter
Examples
========
>>> from sympy.stats import BoundedPareto, density, cdf, E
>>> from sympy import symbols
>>> L, H = symbols('L, H', positive=True)
>>> X = BoundedPareto('X', 2, L, H)
>>> x = symbols('x')
>>> density(X)(x)
2*L**2/(x**3*(1 - L**2/H**2))
>>> cdf(X)(x)
Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) + H**2/(H**2 - L**2), L <= x), (0, True))
>>> E(X).simplify()
2*H*L/(H + L)
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Pareto_distribution#Bounded_Pareto_distribution
"""
return rv (name, BoundedParetoDistribution, (alpha, left, right))
# ------------------------------------------------------------------------------
# Cauchy distribution ----------------------------------------------------------
class CauchyDistribution(SingleContinuousDistribution):
_argnames = ('x0', 'gamma')
@staticmethod
def check(x0, gamma):
_value_check(gamma > 0, "Scale parameter Gamma must be positive.")
_value_check(x0.is_real, "Location parameter must be real.")
def pdf(self, x):
return 1/(pi*self.gamma*(1 + ((x - self.x0)/self.gamma)**2))
def _cdf(self, x):
x0, gamma = self.x0, self.gamma
return (1/pi)*atan((x - x0)/gamma) + S.Half
def _characteristic_function(self, t):
return exp(self.x0 * I * t - self.gamma * Abs(t))
def _moment_generating_function(self, t):
raise NotImplementedError("The moment generating function for the "
"Cauchy distribution does not exist.")
def _quantile(self, p):
return self.x0 + self.gamma*tan(pi*(p - S.Half))
def Cauchy(name, x0, gamma):
r"""
Create a continuous random variable with a Cauchy distribution.
The density of the Cauchy distribution is given by
.. math::
f(x) := \frac{1}{\pi \gamma [1 + {(\frac{x-x_0}{\gamma})}^2]}
Parameters
==========
x0 : Real number, the location
gamma : Real number, `\gamma > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Cauchy, density
>>> from sympy import Symbol
>>> x0 = Symbol("x0")
>>> gamma = Symbol("gamma", positive=True)
>>> z = Symbol("z")
>>> X = Cauchy("x", x0, gamma)
>>> density(X)(z)
1/(pi*gamma*(1 + (-x0 + z)**2/gamma**2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Cauchy_distribution
.. [2] http://mathworld.wolfram.com/CauchyDistribution.html
"""
return rv(name, CauchyDistribution, (x0, gamma))
#-------------------------------------------------------------------------------
# Chi distribution -------------------------------------------------------------
class ChiDistribution(SingleContinuousDistribution):
_argnames = ('k',)
@staticmethod
def check(k):
_value_check(k > 0, "Number of degrees of freedom (k) must be positive.")
_value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.")
set = Interval(0, oo)
def pdf(self, x):
return 2**(1 - self.k/2)*x**(self.k - 1)*exp(-x**2/2)/gamma(self.k/2)
def _characteristic_function(self, t):
k = self.k
part_1 = hyper((k/2,), (S.Half,), -t**2/2)
part_2 = I*t*sqrt(2)*gamma((k+1)/2)/gamma(k/2)
part_3 = hyper(((k+1)/2,), (Rational(3, 2),), -t**2/2)
return part_1 + part_2*part_3
def _moment_generating_function(self, t):
k = self.k
part_1 = hyper((k / 2,), (S.Half,), t ** 2 / 2)
part_2 = t * sqrt(2) * gamma((k + 1) / 2) / gamma(k / 2)
part_3 = hyper(((k + 1) / 2,), (S(3) / 2,), t ** 2 / 2)
return part_1 + part_2 * part_3
def Chi(name, k):
r"""
Create a continuous random variable with a Chi distribution.
The density of the Chi distribution is given by
.. math::
f(x) := \frac{2^{1-k/2}x^{k-1}e^{-x^2/2}}{\Gamma(k/2)}
with :math:`x \geq 0`.
Parameters
==========
k : Positive integer, The number of degrees of freedom
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Chi, density, E
>>> from sympy import Symbol, simplify
>>> k = Symbol("k", integer=True)
>>> z = Symbol("z")
>>> X = Chi("x", k)
>>> density(X)(z)
2**(1 - k/2)*z**(k - 1)*exp(-z**2/2)/gamma(k/2)
>>> simplify(E(X))
sqrt(2)*gamma(k/2 + 1/2)/gamma(k/2)
References
==========
.. [1] https://en.wikipedia.org/wiki/Chi_distribution
.. [2] http://mathworld.wolfram.com/ChiDistribution.html
"""
return rv(name, ChiDistribution, (k,))
#-------------------------------------------------------------------------------
# Non-central Chi distribution -------------------------------------------------
class ChiNoncentralDistribution(SingleContinuousDistribution):
_argnames = ('k', 'l')
@staticmethod
def check(k, l):
_value_check(k > 0, "Number of degrees of freedom (k) must be positive.")
_value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.")
_value_check(l > 0, "Shift parameter Lambda must be positive.")
set = Interval(0, oo)
def pdf(self, x):
k, l = self.k, self.l
return exp(-(x**2+l**2)/2)*x**k*l / (l*x)**(k/2) * besseli(k/2-1, l*x)
def ChiNoncentral(name, k, l):
r"""
Create a continuous random variable with a non-central Chi distribution.
The density of the non-central Chi distribution is given by
.. math::
f(x) := \frac{e^{-(x^2+\lambda^2)/2} x^k\lambda}
{(\lambda x)^{k/2}} I_{k/2-1}(\lambda x)
with `x \geq 0`. Here, `I_\nu (x)` is the
:ref:`modified Bessel function of the first kind <besseli>`.
Parameters
==========
k : A positive Integer, `k > 0`, the number of degrees of freedom
lambda : Real number, `\lambda > 0`, Shift parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ChiNoncentral, density
>>> from sympy import Symbol
>>> k = Symbol("k", integer=True)
>>> l = Symbol("l")
>>> z = Symbol("z")
>>> X = ChiNoncentral("x", k, l)
>>> density(X)(z)
l*z**k*(l*z)**(-k/2)*exp(-l**2/2 - z**2/2)*besseli(k/2 - 1, l*z)
References
==========
.. [1] https://en.wikipedia.org/wiki/Noncentral_chi_distribution
"""
return rv(name, ChiNoncentralDistribution, (k, l))
#-------------------------------------------------------------------------------
# Chi squared distribution -----------------------------------------------------
class ChiSquaredDistribution(SingleContinuousDistribution):
_argnames = ('k',)
@staticmethod
def check(k):
_value_check(k > 0, "Number of degrees of freedom (k) must be positive.")
_value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.")
set = Interval(0, oo)
def pdf(self, x):
k = self.k
return 1/(2**(k/2)*gamma(k/2))*x**(k/2 - 1)*exp(-x/2)
def _cdf(self, x):
k = self.k
return Piecewise(
(S.One/gamma(k/2)*lowergamma(k/2, x/2), x >= 0),
(0, True)
)
def _characteristic_function(self, t):
return (1 - 2*I*t)**(-self.k/2)
def _moment_generating_function(self, t):
return (1 - 2*t)**(-self.k/2)
def ChiSquared(name, k):
r"""
Create a continuous random variable with a Chi-squared distribution.
The density of the Chi-squared distribution is given by
.. math::
f(x) := \frac{1}{2^{\frac{k}{2}}\Gamma\left(\frac{k}{2}\right)}
x^{\frac{k}{2}-1} e^{-\frac{x}{2}}
with :math:`x \geq 0`.
Parameters
==========
k : Positive integer, The number of degrees of freedom
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ChiSquared, density, E, variance, moment
>>> from sympy import Symbol
>>> k = Symbol("k", integer=True, positive=True)
>>> z = Symbol("z")
>>> X = ChiSquared("x", k)
>>> density(X)(z)
2**(-k/2)*z**(k/2 - 1)*exp(-z/2)/gamma(k/2)
>>> E(X)
k
>>> variance(X)
2*k
>>> moment(X, 3)
k**3 + 6*k**2 + 8*k
References
==========
.. [1] https://en.wikipedia.org/wiki/Chi_squared_distribution
.. [2] http://mathworld.wolfram.com/Chi-SquaredDistribution.html
"""
return rv(name, ChiSquaredDistribution, (k, ))
#-------------------------------------------------------------------------------
# Dagum distribution -----------------------------------------------------------
class DagumDistribution(SingleContinuousDistribution):
_argnames = ('p', 'a', 'b')
set = Interval(0, oo)
@staticmethod
def check(p, a, b):
_value_check(p > 0, "Shape parameter p must be positive.")
_value_check(a > 0, "Shape parameter a must be positive.")
_value_check(b > 0, "Scale parameter b must be positive.")
def pdf(self, x):
p, a, b = self.p, self.a, self.b
return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1)))
def _cdf(self, x):
p, a, b = self.p, self.a, self.b
return Piecewise(((S.One + (S(x)/b)**-a)**-p, x>=0),
(S.Zero, True))
def Dagum(name, p, a, b):
r"""
Create a continuous random variable with a Dagum distribution.
The density of the Dagum distribution is given by
.. math::
f(x) := \frac{a p}{x} \left( \frac{\left(\tfrac{x}{b}\right)^{a p}}
{\left(\left(\tfrac{x}{b}\right)^a + 1 \right)^{p+1}} \right)
with :math:`x > 0`.
Parameters
==========
p : Real number, `p > 0`, a shape
a : Real number, `a > 0`, a shape
b : Real number, `b > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Dagum, density, cdf
>>> from sympy import Symbol
>>> p = Symbol("p", positive=True)
>>> a = Symbol("a", positive=True)
>>> b = Symbol("b", positive=True)
>>> z = Symbol("z")
>>> X = Dagum("x", p, a, b)
>>> density(X)(z)
a*p*(z/b)**(a*p)*((z/b)**a + 1)**(-p - 1)/z
>>> cdf(X)(z)
Piecewise(((1 + (z/b)**(-a))**(-p), z >= 0), (0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Dagum_distribution
"""
return rv(name, DagumDistribution, (p, a, b))
#-------------------------------------------------------------------------------
# Erlang distribution ----------------------------------------------------------
def Erlang(name, k, l):
r"""
Create a continuous random variable with an Erlang distribution.
The density of the Erlang distribution is given by
.. math::
f(x) := \frac{\lambda^k x^{k-1} e^{-\lambda x}}{(k-1)!}
with :math:`x \in [0,\infty]`.
Parameters
==========
k : Positive integer
l : Real number, `\lambda > 0`, the rate
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Erlang, density, cdf, E, variance
>>> from sympy import Symbol, simplify, pprint
>>> k = Symbol("k", integer=True, positive=True)
>>> l = Symbol("l", positive=True)
>>> z = Symbol("z")
>>> X = Erlang("x", k, l)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
k k - 1 -l*z
l *z *e
---------------
Gamma(k)
>>> C = cdf(X)(z)
>>> pprint(C, use_unicode=False)
/lowergamma(k, l*z)
|------------------ for z > 0
< Gamma(k)
|
\ 0 otherwise
>>> E(X)
k/l
>>> simplify(variance(X))
k/l**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Erlang_distribution
.. [2] http://mathworld.wolfram.com/ErlangDistribution.html
"""
return rv(name, GammaDistribution, (k, S.One/l))
# -------------------------------------------------------------------------------
# ExGaussian distribution -----------------------------------------------------
class ExGaussianDistribution(SingleContinuousDistribution):
_argnames = ('mean', 'std', 'rate')
set = Interval(-oo, oo)
@staticmethod
def check(mean, std, rate):
_value_check(
std > 0, "Standard deviation of ExGaussian must be positive.")
_value_check(rate > 0, "Rate of ExGaussian must be positive.")
def pdf(self, x):
mean, std, rate = self.mean, self.std, self.rate
term1 = rate/2
term2 = exp(rate * (2 * mean + rate * std**2 - 2*x)/2)
term3 = erfc((mean + rate*std**2 - x)/(sqrt(2)*std))
return term1*term2*term3
def _cdf(self, x):
from sympy.stats import cdf
mean, std, rate = self.mean, self.std, self.rate
u = rate*(x - mean)
v = rate*std
GaussianCDF1 = cdf(Normal('x', 0, v))(u)
GaussianCDF2 = cdf(Normal('x', v**2, v))(u)
return GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2))
def _characteristic_function(self, t):
mean, std, rate = self.mean, self.std, self.rate
term1 = (1 - I*t/rate)**(-1)
term2 = exp(I*mean*t - std**2*t**2/2)
return term1 * term2
def _moment_generating_function(self, t):
mean, std, rate = self.mean, self.std, self.rate
term1 = (1 - t/rate)**(-1)
term2 = exp(mean*t + std**2*t**2/2)
return term1*term2
def ExGaussian(name, mean, std, rate):
r"""
Create a continuous random variable with an Exponentially modified
Gaussian (EMG) distribution.
The density of the exponentially modified Gaussian distribution is given by
.. math::
f(x) := \frac{\lambda}{2}e^{\frac{\lambda}{2}(2\mu+\lambda\sigma^2-2x)}
\text{erfc}(\frac{\mu + \lambda\sigma^2 - x}{\sqrt{2}\sigma})
with `x > 0`. Note that the expected value is `1/\lambda`.
Parameters
==========
mu : A Real number, the mean of Gaussian component
std: A positive Real number,
:math: `\sigma^2 > 0` the variance of Gaussian component
lambda: A positive Real number,
:math: `\lambda > 0` the rate of Exponential component
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ExGaussian, density, cdf, E
>>> from sympy.stats import variance, skewness
>>> from sympy import Symbol, pprint, simplify
>>> mean = Symbol("mu")
>>> std = Symbol("sigma", positive=True)
>>> rate = Symbol("lamda", positive=True)
>>> z = Symbol("z")
>>> X = ExGaussian("x", mean, std, rate)
>>> pprint(density(X)(z), use_unicode=False)
/ 2 \
lamda*\lamda*sigma + 2*mu - 2*z/
--------------------------------- / ___ / 2 \\
2 |\/ 2 *\lamda*sigma + mu - z/|
lamda*e *erfc|-----------------------------|
\ 2*sigma /
----------------------------------------------------------------------------
2
>>> cdf(X)(z)
-(erf(sqrt(2)*(-lamda**2*sigma**2 + lamda*(-mu + z))/(2*lamda*sigma))/2 + 1/2)*exp(lamda**2*sigma**2/2 - lamda*(-mu + z)) + erf(sqrt(2)*(-mu + z)/(2*sigma))/2 + 1/2
>>> E(X)
(lamda*mu + 1)/lamda
>>> simplify(variance(X))
sigma**2 + lamda**(-2)
>>> simplify(skewness(X))
2/(lamda**2*sigma**2 + 1)**(3/2)
References
==========
.. [1] https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution
"""
return rv(name, ExGaussianDistribution, (mean, std, rate))
#-------------------------------------------------------------------------------
# Exponential distribution -----------------------------------------------------
class ExponentialDistribution(SingleContinuousDistribution):
_argnames = ('rate',)
set = Interval(0, oo)
@staticmethod
def check(rate):
_value_check(rate > 0, "Rate must be positive.")
def pdf(self, x):
return self.rate * exp(-self.rate*x)
def _cdf(self, x):
return Piecewise(
(S.One - exp(-self.rate*x), x >= 0),
(0, True),
)
def _characteristic_function(self, t):
rate = self.rate
return rate / (rate - I*t)
def _moment_generating_function(self, t):
rate = self.rate
return rate / (rate - t)
def _quantile(self, p):
return -log(1-p)/self.rate
def Exponential(name, rate):
r"""
Create a continuous random variable with an Exponential distribution.
The density of the exponential distribution is given by
.. math::
f(x) := \lambda \exp(-\lambda x)
with `x > 0`. Note that the expected value is `1/\lambda`.
Parameters
==========
rate : A positive Real number, `\lambda > 0`, the rate (or inverse scale/inverse mean)
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Exponential, density, cdf, E
>>> from sympy.stats import variance, std, skewness, quantile
>>> from sympy import Symbol
>>> l = Symbol("lambda", positive=True)
>>> z = Symbol("z")
>>> p = Symbol("p")
>>> X = Exponential("x", l)
>>> density(X)(z)
lambda*exp(-lambda*z)
>>> cdf(X)(z)
Piecewise((1 - exp(-lambda*z), z >= 0), (0, True))
>>> quantile(X)(p)
-log(1 - p)/lambda
>>> E(X)
1/lambda
>>> variance(X)
lambda**(-2)
>>> skewness(X)
2
>>> X = Exponential('x', 10)
>>> density(X)(z)
10*exp(-10*z)
>>> E(X)
1/10
>>> std(X)
1/10
References
==========
.. [1] https://en.wikipedia.org/wiki/Exponential_distribution
.. [2] http://mathworld.wolfram.com/ExponentialDistribution.html
"""
return rv(name, ExponentialDistribution, (rate, ))
# -------------------------------------------------------------------------------
# Exponential Power distribution -----------------------------------------------------
class ExponentialPowerDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'alpha', 'beta')
set = Interval(-oo, oo)
@staticmethod
def check(mu, alpha, beta):
_value_check(alpha > 0, "Scale parameter alpha must be positive.")
_value_check(beta > 0, "Shape parameter beta must be positive.")
def pdf(self, x):
mu, alpha, beta = self.mu, self.alpha, self.beta
num = beta*exp(-(Abs(x - mu)/alpha)**beta)
den = 2*alpha*gamma(1/beta)
return num/den
def _cdf(self, x):
mu, alpha, beta = self.mu, self.alpha, self.beta
num = lowergamma(1/beta, (Abs(x - mu) / alpha)**beta)
den = 2*gamma(1/beta)
return sign(x - mu)*num/den + S.Half
def ExponentialPower(name, mu, alpha, beta):
r"""
Create a Continuous Random Variable with Exponential Power distribution.
This distribution is known also as Generalized Normal
distribution version 1
The density of the Exponential Power distribution is given by
.. math::
f(x) := \frac{\beta}{2\alpha\Gamma(\frac{1}{\beta})}
e^{{-(\frac{|x - \mu|}{\alpha})^{\beta}}}
with :math:`x \in [ - \infty, \infty ]`.
Parameters
==========
mu : Real number, 'mu' is a location
alpha : Real number, 'alpha > 0' is a scale
beta : Real number, 'beta > 0' is a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ExponentialPower, density, cdf
>>> from sympy import Symbol, pprint
>>> z = Symbol("z")
>>> mu = Symbol("mu")
>>> alpha = Symbol("alpha", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> X = ExponentialPower("x", mu, alpha, beta)
>>> pprint(density(X)(z), use_unicode=False)
beta
/|mu - z|\
-|--------|
\ alpha /
beta*e
---------------------
/ 1 \
2*alpha*Gamma|----|
\beta/
>>> cdf(X)(z)
1/2 + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/(2*gamma(1/beta))
References
==========
.. [1] https://reference.wolfram.com/language/ref/ExponentialPowerDistribution.html
.. [2] https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1
"""
return rv(name, ExponentialPowerDistribution, (mu, alpha, beta))
#-------------------------------------------------------------------------------
# F distribution ---------------------------------------------------------------
class FDistributionDistribution(SingleContinuousDistribution):
_argnames = ('d1', 'd2')
set = Interval(0, oo)
@staticmethod
def check(d1, d2):
_value_check((d1 > 0, d1.is_integer),
"Degrees of freedom d1 must be positive integer.")
_value_check((d2 > 0, d2.is_integer),
"Degrees of freedom d2 must be positive integer.")
def pdf(self, x):
d1, d2 = self.d1, self.d2
return (sqrt((d1*x)**d1*d2**d2 / (d1*x+d2)**(d1+d2))
/ (x * beta_fn(d1/2, d2/2)))
def _moment_generating_function(self, t):
raise NotImplementedError('The moment generating function for the '
'F-distribution does not exist.')
def FDistribution(name, d1, d2):
r"""
Create a continuous random variable with a F distribution.
The density of the F distribution is given by
.. math::
f(x) := \frac{\sqrt{\frac{(d_1 x)^{d_1} d_2^{d_2}}
{(d_1 x + d_2)^{d_1 + d_2}}}}
{x \mathrm{B} \left(\frac{d_1}{2}, \frac{d_2}{2}\right)}
with :math:`x > 0`.
Parameters
==========
d1 : `d_1 > 0`, where d_1 is the degrees of freedom (n_1 - 1)
d2 : `d_2 > 0`, where d_2 is the degrees of freedom (n_2 - 1)
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import FDistribution, density
>>> from sympy import Symbol, pprint
>>> d1 = Symbol("d1", positive=True)
>>> d2 = Symbol("d2", positive=True)
>>> z = Symbol("z")
>>> X = FDistribution("x", d1, d2)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
d2
-- ______________________________
2 / d1 -d1 - d2
d2 *\/ (d1*z) *(d1*z + d2)
--------------------------------------
/d1 d2\
z*B|--, --|
\2 2 /
References
==========
.. [1] https://en.wikipedia.org/wiki/F-distribution
.. [2] http://mathworld.wolfram.com/F-Distribution.html
"""
return rv(name, FDistributionDistribution, (d1, d2))
#-------------------------------------------------------------------------------
# Fisher Z distribution --------------------------------------------------------
class FisherZDistribution(SingleContinuousDistribution):
_argnames = ('d1', 'd2')
set = Interval(-oo, oo)
@staticmethod
def check(d1, d2):
_value_check(d1 > 0, "Degree of freedom d1 must be positive.")
_value_check(d2 > 0, "Degree of freedom d2 must be positive.")
def pdf(self, x):
d1, d2 = self.d1, self.d2
return (2*d1**(d1/2)*d2**(d2/2) / beta_fn(d1/2, d2/2) *
exp(d1*x) / (d1*exp(2*x)+d2)**((d1+d2)/2))
def FisherZ(name, d1, d2):
r"""
Create a Continuous Random Variable with an Fisher's Z distribution.
The density of the Fisher's Z distribution is given by
.. math::
f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)}
\frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\left(d_1+d_2\right)/2}}
.. TODO - What is the difference between these degrees of freedom?
Parameters
==========
d1 : `d_1 > 0`, degree of freedom
d2 : `d_2 > 0`, degree of freedom
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import FisherZ, density
>>> from sympy import Symbol, pprint
>>> d1 = Symbol("d1", positive=True)
>>> d2 = Symbol("d2", positive=True)
>>> z = Symbol("z")
>>> X = FisherZ("x", d1, d2)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
d1 d2
d1 d2 - -- - --
-- -- 2 2
2 2 / 2*z \ d1*z
2*d1 *d2 *\d1*e + d2/ *e
-----------------------------------------
/d1 d2\
B|--, --|
\2 2 /
References
==========
.. [1] https://en.wikipedia.org/wiki/Fisher%27s_z-distribution
.. [2] http://mathworld.wolfram.com/Fishersz-Distribution.html
"""
return rv(name, FisherZDistribution, (d1, d2))
#-------------------------------------------------------------------------------
# Frechet distribution ---------------------------------------------------------
class FrechetDistribution(SingleContinuousDistribution):
_argnames = ('a', 's', 'm')
set = Interval(0, oo)
@staticmethod
def check(a, s, m):
_value_check(a > 0, "Shape parameter alpha must be positive.")
_value_check(s > 0, "Scale parameter s must be positive.")
def __new__(cls, a, s=1, m=0):
a, s, m = list(map(sympify, (a, s, m)))
return Basic.__new__(cls, a, s, m)
def pdf(self, x):
a, s, m = self.a, self.s, self.m
return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a))
def _cdf(self, x):
a, s, m = self.a, self.s, self.m
return Piecewise((exp(-((x-m)/s)**(-a)), x >= m),
(S.Zero, True))
def Frechet(name, a, s=1, m=0):
r"""
Create a continuous random variable with a Frechet distribution.
The density of the Frechet distribution is given by
.. math::
f(x) := \frac{\alpha}{s} \left(\frac{x-m}{s}\right)^{-1-\alpha}
e^{-(\frac{x-m}{s})^{-\alpha}}
with :math:`x \geq m`.
Parameters
==========
a : Real number, :math:`a \in \left(0, \infty\right)` the shape
s : Real number, :math:`s \in \left(0, \infty\right)` the scale
m : Real number, :math:`m \in \left(-\infty, \infty\right)` the minimum
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Frechet, density, cdf
>>> from sympy import Symbol
>>> a = Symbol("a", positive=True)
>>> s = Symbol("s", positive=True)
>>> m = Symbol("m", real=True)
>>> z = Symbol("z")
>>> X = Frechet("x", a, s, m)
>>> density(X)(z)
a*((-m + z)/s)**(-a - 1)*exp(-((-m + z)/s)**(-a))/s
>>> cdf(X)(z)
Piecewise((exp(-((-m + z)/s)**(-a)), m <= z), (0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Fr%C3%A9chet_distribution
"""
return rv(name, FrechetDistribution, (a, s, m))
#-------------------------------------------------------------------------------
# Gamma distribution -----------------------------------------------------------
class GammaDistribution(SingleContinuousDistribution):
_argnames = ('k', 'theta')
set = Interval(0, oo)
@staticmethod
def check(k, theta):
_value_check(k > 0, "k must be positive")
_value_check(theta > 0, "Theta must be positive")
def pdf(self, x):
k, theta = self.k, self.theta
return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
def _cdf(self, x):
k, theta = self.k, self.theta
return Piecewise(
(lowergamma(k, S(x)/theta)/gamma(k), x > 0),
(S.Zero, True))
def _characteristic_function(self, t):
return (1 - self.theta*I*t)**(-self.k)
def _moment_generating_function(self, t):
return (1- self.theta*t)**(-self.k)
def Gamma(name, k, theta):
r"""
Create a continuous random variable with a Gamma distribution.
The density of the Gamma distribution is given by
.. math::
f(x) := \frac{1}{\Gamma(k) \theta^k} x^{k - 1} e^{-\frac{x}{\theta}}
with :math:`x \in [0,1]`.
Parameters
==========
k : Real number, `k > 0`, a shape
theta : Real number, `\theta > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Gamma, density, cdf, E, variance
>>> from sympy import Symbol, pprint, simplify
>>> k = Symbol("k", positive=True)
>>> theta = Symbol("theta", positive=True)
>>> z = Symbol("z")
>>> X = Gamma("x", k, theta)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
-z
-----
-k k - 1 theta
theta *z *e
---------------------
Gamma(k)
>>> C = cdf(X, meijerg=True)(z)
>>> pprint(C, use_unicode=False)
/ / z \
|k*lowergamma|k, -----|
| \ theta/
<---------------------- for z >= 0
| Gamma(k + 1)
|
\ 0 otherwise
>>> E(X)
k*theta
>>> V = simplify(variance(X))
>>> pprint(V, use_unicode=False)
2
k*theta
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_distribution
.. [2] http://mathworld.wolfram.com/GammaDistribution.html
"""
return rv(name, GammaDistribution, (k, theta))
#-------------------------------------------------------------------------------
# Inverse Gamma distribution ---------------------------------------------------
class GammaInverseDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b')
set = Interval(0, oo)
@staticmethod
def check(a, b):
_value_check(a > 0, "alpha must be positive")
_value_check(b > 0, "beta must be positive")
def pdf(self, x):
a, b = self.a, self.b
return b**a/gamma(a) * x**(-a-1) * exp(-b/x)
def _cdf(self, x):
a, b = self.a, self.b
return Piecewise((uppergamma(a,b/x)/gamma(a), x > 0),
(S.Zero, True))
def _characteristic_function(self, t):
a, b = self.a, self.b
return 2 * (-I*b*t)**(a/2) * besselk(a, sqrt(-4*I*b*t)) / gamma(a)
def _moment_generating_function(self, t):
raise NotImplementedError('The moment generating function for the '
'gamma inverse distribution does not exist.')
def GammaInverse(name, a, b):
r"""
Create a continuous random variable with an inverse Gamma distribution.
The density of the inverse Gamma distribution is given by
.. math::
f(x) := \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha - 1}
\exp\left(\frac{-\beta}{x}\right)
with :math:`x > 0`.
Parameters
==========
a : Real number, `a > 0` a shape
b : Real number, `b > 0` a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import GammaInverse, density, cdf
>>> from sympy import Symbol, pprint
>>> a = Symbol("a", positive=True)
>>> b = Symbol("b", positive=True)
>>> z = Symbol("z")
>>> X = GammaInverse("x", a, b)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
-b
---
a -a - 1 z
b *z *e
---------------
Gamma(a)
>>> cdf(X)(z)
Piecewise((uppergamma(a, b/z)/gamma(a), z > 0), (0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse-gamma_distribution
"""
return rv(name, GammaInverseDistribution, (a, b))
#-------------------------------------------------------------------------------
# Gumbel distribution (Maximum and Minimum) --------------------------------------------------------
class GumbelDistribution(SingleContinuousDistribution):
_argnames = ('beta', 'mu', 'minimum')
set = Interval(-oo, oo)
@staticmethod
def check(beta, mu, minimum):
_value_check(beta > 0, "Scale parameter beta must be positive.")
def pdf(self, x):
beta, mu = self.beta, self.mu
z = (x - mu)/beta
f_max = (1/beta)*exp(-z - exp(-z))
f_min = (1/beta)*exp(z - exp(z))
return Piecewise((f_min, self.minimum), (f_max, not self.minimum))
def _cdf(self, x):
beta, mu = self.beta, self.mu
z = (x - mu)/beta
F_max = exp(-exp(-z))
F_min = 1 - exp(-exp(z))
return Piecewise((F_min, self.minimum), (F_max, not self.minimum))
def _characteristic_function(self, t):
cf_max = gamma(1 - I*self.beta*t) * exp(I*self.mu*t)
cf_min = gamma(1 + I*self.beta*t) * exp(I*self.mu*t)
return Piecewise((cf_min, self.minimum), (cf_max, not self.minimum))
def _moment_generating_function(self, t):
mgf_max = gamma(1 - self.beta*t) * exp(self.mu*t)
mgf_min = gamma(1 + self.beta*t) * exp(self.mu*t)
return Piecewise((mgf_min, self.minimum), (mgf_max, not self.minimum))
def Gumbel(name, beta, mu, minimum=False):
r"""
Create a Continuous Random Variable with Gumbel distribution.
The density of the Gumbel distribution is given by
For Maximum
.. math::
f(x) := \dfrac{1}{\beta} \exp \left( -\dfrac{x-\mu}{\beta}
- \exp \left( -\dfrac{x - \mu}{\beta} \right) \right)
with :math:`x \in [ - \infty, \infty ]`.
For Minimum
.. math::
f(x) := \frac{e^{- e^{\frac{- \mu + x}{\beta}} + \frac{- \mu + x}{\beta}}}{\beta}
with :math:`x \in [ - \infty, \infty ]`.
Parameters
==========
mu : Real number, 'mu' is a location
beta : Real number, 'beta > 0' is a scale
minimum : Boolean, by default, False, set to True for enabling minimum distribution
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Gumbel, density, cdf
>>> from sympy import Symbol
>>> x = Symbol("x")
>>> mu = Symbol("mu")
>>> beta = Symbol("beta", positive=True)
>>> X = Gumbel("x", beta, mu)
>>> density(X)(x)
exp(-exp(-(-mu + x)/beta) - (-mu + x)/beta)/beta
>>> cdf(X)(x)
exp(-exp(-(-mu + x)/beta))
References
==========
.. [1] http://mathworld.wolfram.com/GumbelDistribution.html
.. [2] https://en.wikipedia.org/wiki/Gumbel_distribution
.. [3] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_max.html
.. [4] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_min.html
"""
return rv(name, GumbelDistribution, (beta, mu, minimum))
#-------------------------------------------------------------------------------
# Gompertz distribution --------------------------------------------------------
class GompertzDistribution(SingleContinuousDistribution):
_argnames = ('b', 'eta')
set = Interval(0, oo)
@staticmethod
def check(b, eta):
_value_check(b > 0, "b must be positive")
_value_check(eta > 0, "eta must be positive")
def pdf(self, x):
eta, b = self.eta, self.b
return b*eta*exp(b*x)*exp(eta)*exp(-eta*exp(b*x))
def _cdf(self, x):
eta, b = self.eta, self.b
return 1 - exp(eta)*exp(-eta*exp(b*x))
def _moment_generating_function(self, t):
eta, b = self.eta, self.b
return eta * exp(eta) * expint(t/b, eta)
def Gompertz(name, b, eta):
r"""
Create a Continuous Random Variable with Gompertz distribution.
The density of the Gompertz distribution is given by
.. math::
f(x) := b \eta e^{b x} e^{\eta} \exp \left(-\eta e^{bx} \right)
with :math: 'x \in [0, \inf)'.
Parameters
==========
b: Real number, 'b > 0' a scale
eta: Real number, 'eta > 0' a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Gompertz, density
>>> from sympy import Symbol
>>> b = Symbol("b", positive=True)
>>> eta = Symbol("eta", positive=True)
>>> z = Symbol("z")
>>> X = Gompertz("x", b, eta)
>>> density(X)(z)
b*eta*exp(eta)*exp(b*z)*exp(-eta*exp(b*z))
References
==========
.. [1] https://en.wikipedia.org/wiki/Gompertz_distribution
"""
return rv(name, GompertzDistribution, (b, eta))
#-------------------------------------------------------------------------------
# Kumaraswamy distribution -----------------------------------------------------
class KumaraswamyDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b')
set = Interval(0, oo)
@staticmethod
def check(a, b):
_value_check(a > 0, "a must be positive")
_value_check(b > 0, "b must be positive")
def pdf(self, x):
a, b = self.a, self.b
return a * b * x**(a-1) * (1-x**a)**(b-1)
def _cdf(self, x):
a, b = self.a, self.b
return Piecewise(
(S.Zero, x < S.Zero),
(1 - (1 - x**a)**b, x <= S.One),
(S.One, True))
def Kumaraswamy(name, a, b):
r"""
Create a Continuous Random Variable with a Kumaraswamy distribution.
The density of the Kumaraswamy distribution is given by
.. math::
f(x) := a b x^{a-1} (1-x^a)^{b-1}
with :math:`x \in [0,1]`.
Parameters
==========
a : Real number, `a > 0` a shape
b : Real number, `b > 0` a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Kumaraswamy, density, cdf
>>> from sympy import Symbol, pprint
>>> a = Symbol("a", positive=True)
>>> b = Symbol("b", positive=True)
>>> z = Symbol("z")
>>> X = Kumaraswamy("x", a, b)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
b - 1
a - 1 / a\
a*b*z *\1 - z /
>>> cdf(X)(z)
Piecewise((0, z < 0), (1 - (1 - z**a)**b, z <= 1), (1, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Kumaraswamy_distribution
"""
return rv(name, KumaraswamyDistribution, (a, b))
#-------------------------------------------------------------------------------
# Laplace distribution ---------------------------------------------------------
class LaplaceDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'b')
set = Interval(-oo, oo)
@staticmethod
def check(mu, b):
_value_check(b > 0, "Scale parameter b must be positive.")
_value_check(mu.is_real, "Location parameter mu should be real")
def pdf(self, x):
mu, b = self.mu, self.b
return 1/(2*b)*exp(-Abs(x - mu)/b)
def _cdf(self, x):
mu, b = self.mu, self.b
return Piecewise(
(S.Half*exp((x - mu)/b), x < mu),
(S.One - S.Half*exp(-(x - mu)/b), x >= mu)
)
def _characteristic_function(self, t):
return exp(self.mu*I*t) / (1 + self.b**2*t**2)
def _moment_generating_function(self, t):
return exp(self.mu*t) / (1 - self.b**2*t**2)
def Laplace(name, mu, b):
r"""
Create a continuous random variable with a Laplace distribution.
The density of the Laplace distribution is given by
.. math::
f(x) := \frac{1}{2 b} \exp \left(-\frac{|x-\mu|}b \right)
Parameters
==========
mu : Real number or a list/matrix, the location (mean) or the
location vector
b : Real number or a positive definite matrix, representing a scale
or the covariance matrix.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Laplace, density, cdf
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu")
>>> b = Symbol("b", positive=True)
>>> z = Symbol("z")
>>> X = Laplace("x", mu, b)
>>> density(X)(z)
exp(-Abs(mu - z)/b)/(2*b)
>>> cdf(X)(z)
Piecewise((exp((-mu + z)/b)/2, mu > z), (1 - exp((mu - z)/b)/2, True))
>>> L = Laplace('L', [1, 2], [[1, 0], [0, 1]])
>>> pprint(density(L)(1, 2), use_unicode=False)
5 / ____\
e *besselk\0, \/ 35 /
---------------------
pi
References
==========
.. [1] https://en.wikipedia.org/wiki/Laplace_distribution
.. [2] http://mathworld.wolfram.com/LaplaceDistribution.html
"""
if isinstance(mu, (list, MatrixBase)) and\
isinstance(b, (list, MatrixBase)):
from sympy.stats.joint_rv_types import MultivariateLaplace
return MultivariateLaplace(name, mu, b)
return rv(name, LaplaceDistribution, (mu, b))
#-------------------------------------------------------------------------------
# Levy distribution ---------------------------------------------------------
class LevyDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'c')
@property
def set(self):
return Interval(self.mu, oo)
@staticmethod
def check(mu, c):
_value_check(c > 0, "c (scale parameter) must be positive")
_value_check(mu.is_real, "mu (location paramater) must be real")
def pdf(self, x):
mu, c = self.mu, self.c
return sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half))
def _cdf(self, x):
mu, c = self.mu, self.c
return erfc(sqrt(c/(2*(x - mu))))
def _characteristic_function(self, t):
mu, c = self.mu, self.c
return exp(I * mu * t - sqrt(-2 * I * c * t))
def _moment_generating_function(self, t):
raise NotImplementedError('The moment generating function of Levy distribution does not exist.')
def Levy(name, mu, c):
r"""
Create a continuous random variable with a Levy distribution.
The density of the Levy distribution is given by
.. math::
f(x) := \sqrt(\frac{c}{2 \pi}) \frac{\exp -\frac{c}{2 (x - \mu)}}{(x - \mu)^{3/2}}
Parameters
==========
mu : Real number, the location parameter
c : Real number, `c > 0`, a scale parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Levy, density, cdf
>>> from sympy import Symbol
>>> mu = Symbol("mu", real=True)
>>> c = Symbol("c", positive=True)
>>> z = Symbol("z")
>>> X = Levy("x", mu, c)
>>> density(X)(z)
sqrt(2)*sqrt(c)*exp(-c/(-2*mu + 2*z))/(2*sqrt(pi)*(-mu + z)**(3/2))
>>> cdf(X)(z)
erfc(sqrt(c)*sqrt(1/(-2*mu + 2*z)))
References
==========
.. [1] https://en.wikipedia.org/wiki/L%C3%A9vy_distribution
.. [2] http://mathworld.wolfram.com/LevyDistribution.html
"""
return rv(name, LevyDistribution, (mu, c))
#-------------------------------------------------------------------------------
# Log-Cauchy distribution --------------------------------------------------------
class LogCauchyDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'sigma')
set = Interval.open(0, oo)
@staticmethod
def check(mu, sigma):
_value_check((sigma > 0) != False, "Scale parameter Gamma must be positive.")
_value_check(mu.is_real != False, "Location parameter must be real.")
def pdf(self, x):
mu, sigma = self.mu, self.sigma
return 1/(x*pi)*(sigma/((log(x) - mu)**2 + sigma**2))
def _cdf(self, x):
mu, sigma = self.mu, self.sigma
return (1/pi)*atan((log(x) - mu)/sigma) + S.Half
def _characteristic_function(self, t):
raise NotImplementedError("The characteristic function for the "
"Log-Cauchy distribution does not exist.")
def _moment_generating_function(self, t):
raise NotImplementedError("The moment generating function for the "
"Log-Cauchy distribution does not exist.")
def LogCauchy(name, mu, sigma):
r"""
Create a continuous random variable with a Log-Cauchy distribution.
The density of the Log-Cauchy distribution is given by
.. math::
f(x) := \frac{1}{\pi x} \frac{\sigma}{(log(x)-\mu^2) + \sigma^2}
Parameters
==========
mu : Real number, the location
sigma : Real number, `\sigma > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import LogCauchy, density, cdf
>>> from sympy import Symbol, S
>>> mu = 2
>>> sigma = S.One / 5
>>> z = Symbol("z")
>>> X = LogCauchy("x", mu, sigma)
>>> density(X)(z)
1/(5*pi*z*((log(z) - 2)**2 + 1/25))
>>> cdf(X)(z)
atan(5*log(z) - 10)/pi + 1/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Log-Cauchy_distribution
"""
return rv(name, LogCauchyDistribution, (mu, sigma))
#-------------------------------------------------------------------------------
# Logistic distribution --------------------------------------------------------
class LogisticDistribution(SingleContinuousDistribution):
_argnames = ('mu', 's')
set = Interval(-oo, oo)
@staticmethod
def check(mu, s):
_value_check(s > 0, "Scale parameter s must be positive.")
def pdf(self, x):
mu, s = self.mu, self.s
return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))**2)
def _cdf(self, x):
mu, s = self.mu, self.s
return S.One/(1 + exp(-(x - mu)/s))
def _characteristic_function(self, t):
return Piecewise((exp(I*t*self.mu) * pi*self.s*t / sinh(pi*self.s*t), Ne(t, 0)), (S.One, True))
def _moment_generating_function(self, t):
return exp(self.mu*t) * beta_fn(1 - self.s*t, 1 + self.s*t)
def _quantile(self, p):
return self.mu - self.s*log(-S.One + S.One/p)
def Logistic(name, mu, s):
r"""
Create a continuous random variable with a logistic distribution.
The density of the logistic distribution is given by
.. math::
f(x) := \frac{e^{-(x-\mu)/s}} {s\left(1+e^{-(x-\mu)/s}\right)^2}
Parameters
==========
mu : Real number, the location (mean)
s : Real number, `s > 0` a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Logistic, density, cdf
>>> from sympy import Symbol
>>> mu = Symbol("mu", real=True)
>>> s = Symbol("s", positive=True)
>>> z = Symbol("z")
>>> X = Logistic("x", mu, s)
>>> density(X)(z)
exp((mu - z)/s)/(s*(exp((mu - z)/s) + 1)**2)
>>> cdf(X)(z)
1/(exp((mu - z)/s) + 1)
References
==========
.. [1] https://en.wikipedia.org/wiki/Logistic_distribution
.. [2] http://mathworld.wolfram.com/LogisticDistribution.html
"""
return rv(name, LogisticDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Log-logistic distribution --------------------------------------------------------
class LogLogisticDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta')
set = Interval(0, oo)
@staticmethod
def check(alpha, beta):
_value_check(alpha > 0, "Scale parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
def pdf(self, x):
a, b = self.alpha, self.beta
return ((b/a)*(x/a)**(b - 1))/(1 + (x/a)**b)**2
def _cdf(self, x):
a, b = self.alpha, self.beta
return 1/(1 + (x/a)**(-b))
def _quantile(self, p):
a, b = self.alpha, self.beta
return a*((p/(1 - p))**(1/b))
def expectation(self, expr, var, **kwargs):
a, b = self.args
return Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True))
def LogLogistic(name, alpha, beta):
r"""
Create a continuous random variable with a log-logistic distribution.
The distribution is unimodal when `beta > 1`.
The density of the log-logistic distribution is given by
.. math::
f(x) := \frac{(\frac{\beta}{\alpha})(\frac{x}{\alpha})^{\beta - 1}}
{(1 + (\frac{x}{\alpha})^{\beta})^2}
Parameters
==========
alpha : Real number, `\alpha > 0`, scale parameter and median of distribution
beta : Real number, `\beta > 0` a shape parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import LogLogistic, density, cdf, quantile
>>> from sympy import Symbol, pprint
>>> alpha = Symbol("alpha", real=True, positive=True)
>>> beta = Symbol("beta", real=True, positive=True)
>>> p = Symbol("p")
>>> z = Symbol("z", positive=True)
>>> X = LogLogistic("x", alpha, beta)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
beta - 1
/ z \
beta*|-----|
\alpha/
------------------------
2
/ beta \
|/ z \ |
alpha*||-----| + 1|
\\alpha/ /
>>> cdf(X)(z)
1/(1 + (z/alpha)**(-beta))
>>> quantile(X)(p)
alpha*(p/(1 - p))**(1/beta)
References
==========
.. [1] https://en.wikipedia.org/wiki/Log-logistic_distribution
"""
return rv(name, LogLogisticDistribution, (alpha, beta))
#-------------------------------------------------------------------------------
#Logit-Normal distribution------------------------------------------------------
class LogitNormalDistribution(SingleContinuousDistribution):
_argnames = ('mu', 's')
set = Interval.open(0, 1)
@staticmethod
def check(mu, s):
_value_check((s ** 2).is_real is not False and s ** 2 > 0, "Squared scale parameter s must be positive.")
_value_check(mu.is_real is not False, "Location parameter must be real")
def _logit(self, x):
return log(x / (1 - x))
def pdf(self, x):
mu, s = self.mu, self.s
return exp(-(self._logit(x) - mu)**2/(2*s**2))*(S.One/sqrt(2*pi*(s**2)))*(1/(x*(1 - x)))
def _cdf(self, x):
mu, s = self.mu, self.s
return (S.One/2)*(1 + erf((self._logit(x) - mu)/(sqrt(2*s**2))))
def LogitNormal(name, mu, s):
r"""
Create a continuous random variable with a Logit-Normal distribution.
The density of the logistic distribution is given by
.. math::
f(x) := \frac{1}{s \sqrt{2 \pi}} \frac{1}{x(1 - x)} e^{- \frac{(logit(x) - \mu)^2}{s^2}}
where logit(x) = \log(\frac{x}{1 - x})
Parameters
==========
mu : Real number, the location (mean)
s : Real number, `s > 0` a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import LogitNormal, density, cdf
>>> from sympy import Symbol,pprint
>>> mu = Symbol("mu", real=True)
>>> s = Symbol("s", positive=True)
>>> z = Symbol("z")
>>> X = LogitNormal("x",mu,s)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
/ / z \\
-|-mu + log|-----||
\ \1 - z//
---------------------
2
___ 2*s
\/ 2 *e
----------------------------
____
2*\/ pi *s*z*(1 - z)
>>> density(X)(z)
sqrt(2)*exp(-(-mu + log(z/(1 - z)))**2/(2*s**2))/(2*sqrt(pi)*s*z*(1 - z))
>>> cdf(X)(z)
erf(sqrt(2)*(-mu + log(z/(1 - z)))/(2*s))/2 + 1/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Logit-normal_distribution
"""
return rv(name, LogitNormalDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Log Normal distribution ------------------------------------------------------
class LogNormalDistribution(SingleContinuousDistribution):
_argnames = ('mean', 'std')
set = Interval(0, oo)
@staticmethod
def check(mean, std):
_value_check(std > 0, "Parameter std must be positive.")
def pdf(self, x):
mean, std = self.mean, self.std
return exp(-(log(x) - mean)**2 / (2*std**2)) / (x*sqrt(2*pi)*std)
def _cdf(self, x):
mean, std = self.mean, self.std
return Piecewise(
(S.Half + S.Half*erf((log(x) - mean)/sqrt(2)/std), x > 0),
(S.Zero, True)
)
def _moment_generating_function(self, t):
raise NotImplementedError('Moment generating function of the log-normal distribution is not defined.')
def LogNormal(name, mean, std):
r"""
Create a continuous random variable with a log-normal distribution.
The density of the log-normal distribution is given by
.. math::
f(x) := \frac{1}{x\sqrt{2\pi\sigma^2}}
e^{-\frac{\left(\ln x-\mu\right)^2}{2\sigma^2}}
with :math:`x \geq 0`.
Parameters
==========
mu : Real number, the log-scale
sigma : Real number, :math:`\sigma^2 > 0` a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import LogNormal, density
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu", real=True)
>>> sigma = Symbol("sigma", positive=True)
>>> z = Symbol("z")
>>> X = LogNormal("x", mu, sigma)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
-(-mu + log(z))
-----------------
2
___ 2*sigma
\/ 2 *e
------------------------
____
2*\/ pi *sigma*z
>>> X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1
>>> density(X)(z)
sqrt(2)*exp(-log(z)**2/2)/(2*sqrt(pi)*z)
References
==========
.. [1] https://en.wikipedia.org/wiki/Lognormal
.. [2] http://mathworld.wolfram.com/LogNormalDistribution.html
"""
return rv(name, LogNormalDistribution, (mean, std))
#-------------------------------------------------------------------------------
# Lomax Distribution -----------------------------------------------------------
class LomaxDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'lamda',)
set = Interval(0, oo)
@staticmethod
def check(alpha, lamda):
_value_check(alpha.is_real, "Shape parameter should be real.")
_value_check(lamda.is_real, "Scale parameter should be real.")
_value_check(alpha.is_positive, "Shape parameter should be positive.")
_value_check(lamda.is_positive, "Scale parameter should be positive.")
def pdf(self, x):
lamba, alpha = self.lamda, self.alpha
return (alpha/lamba) * (S.One + x/lamba)**(-alpha-1)
def Lomax(name, alpha, lamda):
r"""
Create a continuous random variable with a Lomax distribution.
The density of the Lomax distribution is given by
.. math::
f(x) := \frac{\alpha}{\lambda}\left[1+\frac{x}{\lambda}\right]^{-(\alpha+1)}
Parameters
==========
alpha : Real Number, `alpha > 0`
Shape parameter
lamda : Real Number, `lamda > 0`
Scale parameter
Examples
========
>>> from sympy.stats import Lomax, density, cdf, E
>>> from sympy import symbols
>>> a, l = symbols('a, l', positive=True)
>>> X = Lomax('X', a, l)
>>> x = symbols('x')
>>> density(X)(x)
a*(1 + x/l)**(-a - 1)/l
>>> cdf(X)(x)
Piecewise((1 - (1 + x/l)**(-a), x >= 0), (0, True))
>>> a = 2
>>> X = Lomax('X', a, l)
>>> E(X)
l
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Lomax_distribution
"""
return rv(name, LomaxDistribution, (alpha, lamda))
#-------------------------------------------------------------------------------
# Maxwell distribution ---------------------------------------------------------
class MaxwellDistribution(SingleContinuousDistribution):
_argnames = ('a',)
set = Interval(0, oo)
@staticmethod
def check(a):
_value_check(a > 0, "Parameter a must be positive.")
def pdf(self, x):
a = self.a
return sqrt(2/pi)*x**2*exp(-x**2/(2*a**2))/a**3
def _cdf(self, x):
a = self.a
return erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a)
def Maxwell(name, a):
r"""
Create a continuous random variable with a Maxwell distribution.
The density of the Maxwell distribution is given by
.. math::
f(x) := \sqrt{\frac{2}{\pi}} \frac{x^2 e^{-x^2/(2a^2)}}{a^3}
with :math:`x \geq 0`.
.. TODO - what does the parameter mean?
Parameters
==========
a : Real number, `a > 0`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Maxwell, density, E, variance
>>> from sympy import Symbol, simplify
>>> a = Symbol("a", positive=True)
>>> z = Symbol("z")
>>> X = Maxwell("x", a)
>>> density(X)(z)
sqrt(2)*z**2*exp(-z**2/(2*a**2))/(sqrt(pi)*a**3)
>>> E(X)
2*sqrt(2)*a/sqrt(pi)
>>> simplify(variance(X))
a**2*(-8 + 3*pi)/pi
References
==========
.. [1] https://en.wikipedia.org/wiki/Maxwell_distribution
.. [2] http://mathworld.wolfram.com/MaxwellDistribution.html
"""
return rv(name, MaxwellDistribution, (a, ))
#-------------------------------------------------------------------------------
# Moyal Distribution -----------------------------------------------------------
class MoyalDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'sigma')
@staticmethod
def check(mu, sigma):
_value_check(mu.is_real, "Location parameter must be real.")
_value_check(sigma.is_real and sigma > 0, "Scale parameter must be real\
and positive.")
def pdf(self, x):
mu, sigma = self.mu, self.sigma
num = exp(-(exp(-(x - mu)/sigma) + (x - mu)/(sigma))/2)
den = (sqrt(2*pi) * sigma)
return num/den
def _characteristic_function(self, t):
mu, sigma = self.mu, self.sigma
term1 = exp(I*t*mu)
term2 = (2**(-I*sigma*t) * gamma(Rational(1, 2) - I*t*sigma))
return (term1 * term2)/sqrt(pi)
def _moment_generating_function(self, t):
mu, sigma = self.mu, self.sigma
term1 = exp(t*mu)
term2 = (2**(-1*sigma*t) * gamma(Rational(1, 2) - t*sigma))
return (term1 * term2)/sqrt(pi)
def Moyal(name, mu, sigma):
r"""
Create a continuous random variable with a Moyal distribution.
The density of the Moyal distribution is given by
.. math::
f(x) := \frac{\exp-\frac{1}{2}\exp-\frac{x-\mu}{\sigma}-\frac{x-\mu}{2\sigma}}{\sqrt{2\pi}\sigma}
with :math:`x \in \mathbb{R}`.
Parameters
==========
mu : Real number
Location parameter
sigma : Real positive number
Scale parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Moyal, density, cdf
>>> from sympy import Symbol, simplify
>>> mu = Symbol("mu", real=True)
>>> sigma = Symbol("sigma", positive=True, real=True)
>>> z = Symbol("z")
>>> X = Moyal("x", mu, sigma)
>>> density(X)(z)
sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma)
>>> simplify(cdf(X)(z))
1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2)
References
==========
.. [1] https://reference.wolfram.com/language/ref/MoyalDistribution.html
.. [2] http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf
"""
return rv(name, MoyalDistribution, (mu, sigma))
#-------------------------------------------------------------------------------
# Nakagami distribution --------------------------------------------------------
class NakagamiDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'omega')
set = Interval(0, oo)
@staticmethod
def check(mu, omega):
_value_check(mu >= S.Half, "Shape parameter mu must be greater than equal to 1/2.")
_value_check(omega > 0, "Spread parameter omega must be positive.")
def pdf(self, x):
mu, omega = self.mu, self.omega
return 2*mu**mu/(gamma(mu)*omega**mu)*x**(2*mu - 1)*exp(-mu/omega*x**2)
def _cdf(self, x):
mu, omega = self.mu, self.omega
return Piecewise(
(lowergamma(mu, (mu/omega)*x**2)/gamma(mu), x > 0),
(S.Zero, True))
def Nakagami(name, mu, omega):
r"""
Create a continuous random variable with a Nakagami distribution.
The density of the Nakagami distribution is given by
.. math::
f(x) := \frac{2\mu^\mu}{\Gamma(\mu)\omega^\mu} x^{2\mu-1}
\exp\left(-\frac{\mu}{\omega}x^2 \right)
with :math:`x > 0`.
Parameters
==========
mu : Real number, `\mu \geq \frac{1}{2}` a shape
omega : Real number, `\omega > 0`, the spread
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Nakagami, density, E, variance, cdf
>>> from sympy import Symbol, simplify, pprint
>>> mu = Symbol("mu", positive=True)
>>> omega = Symbol("omega", positive=True)
>>> z = Symbol("z")
>>> X = Nakagami("x", mu, omega)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
-mu*z
-------
mu -mu 2*mu - 1 omega
2*mu *omega *z *e
----------------------------------
Gamma(mu)
>>> simplify(E(X))
sqrt(mu)*sqrt(omega)*gamma(mu + 1/2)/gamma(mu + 1)
>>> V = simplify(variance(X))
>>> pprint(V, use_unicode=False)
2
omega*Gamma (mu + 1/2)
omega - -----------------------
Gamma(mu)*Gamma(mu + 1)
>>> cdf(X)(z)
Piecewise((lowergamma(mu, mu*z**2/omega)/gamma(mu), z > 0),
(0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Nakagami_distribution
"""
return rv(name, NakagamiDistribution, (mu, omega))
#-------------------------------------------------------------------------------
# Normal distribution ----------------------------------------------------------
class NormalDistribution(SingleContinuousDistribution):
_argnames = ('mean', 'std')
@staticmethod
def check(mean, std):
_value_check(std > 0, "Standard deviation must be positive")
def pdf(self, x):
return exp(-(x - self.mean)**2 / (2*self.std**2)) / (sqrt(2*pi)*self.std)
def _cdf(self, x):
mean, std = self.mean, self.std
return erf(sqrt(2)*(-mean + x)/(2*std))/2 + S.Half
def _characteristic_function(self, t):
mean, std = self.mean, self.std
return exp(I*mean*t - std**2*t**2/2)
def _moment_generating_function(self, t):
mean, std = self.mean, self.std
return exp(mean*t + std**2*t**2/2)
def _quantile(self, p):
mean, std = self.mean, self.std
return mean + std*sqrt(2)*erfinv(2*p - 1)
def Normal(name, mean, std):
r"""
Create a continuous random variable with a Normal distribution.
The density of the Normal distribution is given by
.. math::
f(x) := \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} }
Parameters
==========
mu : Real number or a list representing the mean or the mean vector
sigma : Real number or a positive definite square matrix,
:math:`\sigma^2 > 0` the variance
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Normal, density, E, std, cdf, skewness, quantile, marginal_distribution
>>> from sympy import Symbol, simplify, pprint
>>> mu = Symbol("mu")
>>> sigma = Symbol("sigma", positive=True)
>>> z = Symbol("z")
>>> y = Symbol("y")
>>> p = Symbol("p")
>>> X = Normal("x", mu, sigma)
>>> density(X)(z)
sqrt(2)*exp(-(-mu + z)**2/(2*sigma**2))/(2*sqrt(pi)*sigma)
>>> C = simplify(cdf(X))(z) # it needs a little more help...
>>> pprint(C, use_unicode=False)
/ ___ \
|\/ 2 *(-mu + z)|
erf|---------------|
\ 2*sigma / 1
-------------------- + -
2 2
>>> quantile(X)(p)
mu + sqrt(2)*sigma*erfinv(2*p - 1)
>>> simplify(skewness(X))
0
>>> X = Normal("x", 0, 1) # Mean 0, standard deviation 1
>>> density(X)(z)
sqrt(2)*exp(-z**2/2)/(2*sqrt(pi))
>>> E(2*X + 1)
1
>>> simplify(std(2*X + 1))
2
>>> m = Normal('X', [1, 2], [[2, 1], [1, 2]])
>>> pprint(density(m)(y, z), use_unicode=False)
/1 y\ /2*y z\ / z\ / y 2*z \
|- - -|*|--- - -| + |1 - -|*|- - + --- - 1|
___ \2 2/ \ 3 3/ \ 2/ \ 3 3 /
\/ 3 *e
--------------------------------------------------
6*pi
>>> marginal_distribution(m, m[0])(1)
1/(2*sqrt(pi))
References
==========
.. [1] https://en.wikipedia.org/wiki/Normal_distribution
.. [2] http://mathworld.wolfram.com/NormalDistributionFunction.html
"""
if isinstance(mean, (list, MatrixBase, MatrixExpr)) and\
isinstance(std, (list, MatrixBase, MatrixExpr)):
from sympy.stats.joint_rv_types import MultivariateNormal
return MultivariateNormal(name, mean, std)
return rv(name, NormalDistribution, (mean, std))
#-------------------------------------------------------------------------------
# Inverse Gaussian distribution ----------------------------------------------------------
class GaussianInverseDistribution(SingleContinuousDistribution):
_argnames = ('mean', 'shape')
@property
def set(self):
return Interval(0, oo)
@staticmethod
def check(mean, shape):
_value_check(shape > 0, "Shape parameter must be positive")
_value_check(mean > 0, "Mean must be positive")
def pdf(self, x):
mu, s = self.mean, self.shape
return exp(-s*(x - mu)**2 / (2*x*mu**2)) * sqrt(s/(2*pi*x**3))
def _cdf(self, x):
from sympy.stats import cdf
mu, s = self.mean, self.shape
stdNormalcdf = cdf(Normal('x', 0, 1))
first_term = stdNormalcdf(sqrt(s/x) * ((x/mu) - S.One))
second_term = exp(2*s/mu) * stdNormalcdf(-sqrt(s/x)*(x/mu + S.One))
return first_term + second_term
def _characteristic_function(self, t):
mu, s = self.mean, self.shape
return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*I*t)/s)))
def _moment_generating_function(self, t):
mu, s = self.mean, self.shape
return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*t)/s)))
def GaussianInverse(name, mean, shape):
r"""
Create a continuous random variable with an Inverse Gaussian distribution.
Inverse Gaussian distribution is also known as Wald distribution.
The density of the Inverse Gaussian distribution is given by
.. math::
f(x) := \sqrt{\frac{\lambda}{2\pi x^3}} e^{-\frac{\lambda(x-\mu)^2}{2x\mu^2}}
Parameters
==========
mu : Positive number representing the mean
lambda : Positive number representing the shape parameter
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import GaussianInverse, density, E, std, skewness
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu", positive=True)
>>> lamda = Symbol("lambda", positive=True)
>>> z = Symbol("z", positive=True)
>>> X = GaussianInverse("x", mu, lamda)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
-lambda*(-mu + z)
-------------------
2
___ ________ 2*mu *z
\/ 2 *\/ lambda *e
-------------------------------------
____ 3/2
2*\/ pi *z
>>> E(X)
mu
>>> std(X).expand()
mu**(3/2)/sqrt(lambda)
>>> skewness(X).expand()
3*sqrt(mu)/sqrt(lambda)
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
.. [2] http://mathworld.wolfram.com/InverseGaussianDistribution.html
"""
return rv(name, GaussianInverseDistribution, (mean, shape))
Wald = GaussianInverse
#-------------------------------------------------------------------------------
# Pareto distribution ----------------------------------------------------------
class ParetoDistribution(SingleContinuousDistribution):
_argnames = ('xm', 'alpha')
@property
def set(self):
return Interval(self.xm, oo)
@staticmethod
def check(xm, alpha):
_value_check(xm > 0, "Xm must be positive")
_value_check(alpha > 0, "Alpha must be positive")
def pdf(self, x):
xm, alpha = self.xm, self.alpha
return alpha * xm**alpha / x**(alpha + 1)
def _cdf(self, x):
xm, alpha = self.xm, self.alpha
return Piecewise(
(S.One - xm**alpha/x**alpha, x>=xm),
(0, True),
)
def _moment_generating_function(self, t):
xm, alpha = self.xm, self.alpha
return alpha * (-xm*t)**alpha * uppergamma(-alpha, -xm*t)
def _characteristic_function(self, t):
xm, alpha = self.xm, self.alpha
return alpha * (-I * xm * t) ** alpha * uppergamma(-alpha, -I * xm * t)
def Pareto(name, xm, alpha):
r"""
Create a continuous random variable with the Pareto distribution.
The density of the Pareto distribution is given by
.. math::
f(x) := \frac{\alpha\,x_m^\alpha}{x^{\alpha+1}}
with :math:`x \in [x_m,\infty]`.
Parameters
==========
xm : Real number, `x_m > 0`, a scale
alpha : Real number, `\alpha > 0`, a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Pareto, density
>>> from sympy import Symbol
>>> xm = Symbol("xm", positive=True)
>>> beta = Symbol("beta", positive=True)
>>> z = Symbol("z")
>>> X = Pareto("x", xm, beta)
>>> density(X)(z)
beta*xm**beta*z**(-beta - 1)
References
==========
.. [1] https://en.wikipedia.org/wiki/Pareto_distribution
.. [2] http://mathworld.wolfram.com/ParetoDistribution.html
"""
return rv(name, ParetoDistribution, (xm, alpha))
#-------------------------------------------------------------------------------
# PowerFunction distribution ---------------------------------------------------
class PowerFunctionDistribution(SingleContinuousDistribution):
_argnames=('alpha','a','b')
@property
def set(self):
return Interval(self.a, self.b)
@staticmethod
def check(alpha, a, b):
_value_check(a.is_real, "Continuous Boundary parameter should be real.")
_value_check(b.is_real, "Continuous Boundary parameter should be real.")
_value_check(a < b, " 'a' the left Boundary must be smaller than 'b' the right Boundary." )
_value_check(alpha.is_positive, "Continuous Shape parameter should be positive.")
def pdf(self, x):
alpha, a, b = self.alpha, self.a, self.b
num = alpha*(x - a)**(alpha - 1)
den = (b - a)**alpha
return num/den
def PowerFunction(name, alpha, a, b):
r"""
Creates a continuous random variable with a Power Function Distribution
The density of PowerFunction distribution is given by
.. math::
f(x) := \frac{{\alpha}(x - a)^{\alpha - 1}}{(b - a)^{\alpha}}
with :math:`x \in [a,b]`.
Parameters
==========
alpha: Positive number, `0 < alpha` the shape paramater
a : Real number, :math:`-\infty < a` the left boundary
b : Real number, :math:`a < b < \infty` the right boundary
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import PowerFunction, density, cdf, E, variance
>>> from sympy import Symbol
>>> alpha = Symbol("alpha", positive=True)
>>> a = Symbol("a", real=True)
>>> b = Symbol("b", real=True)
>>> z = Symbol("z")
>>> X = PowerFunction("X", 2, a, b)
>>> density(X)(z)
(-2*a + 2*z)/(-a + b)**2
>>> 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))
>>> alpha = 2
>>> a = 0
>>> b = 1
>>> Y = PowerFunction("Y", alpha, a, b)
>>> E(Y)
2/3
>>> variance(Y)
1/18
References
==========
.. [1] http://www.mathwave.com/help/easyfit/html/analyses/distributions/power_func.html
"""
return rv(name, PowerFunctionDistribution, (alpha, a, b))
#-------------------------------------------------------------------------------
# QuadraticU distribution ------------------------------------------------------
class QuadraticUDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b')
@property
def set(self):
return Interval(self.a, self.b)
@staticmethod
def check(a, b):
_value_check(b > a, "Parameter b must be in range (%s, oo)."%(a))
def pdf(self, x):
a, b = self.a, self.b
alpha = 12 / (b-a)**3
beta = (a+b) / 2
return Piecewise(
(alpha * (x-beta)**2, And(a<=x, x<=b)),
(S.Zero, True))
def _moment_generating_function(self, t):
a, b = self.a, self.b
return -3 * (exp(a*t) * (4 + (a**2 + 2*a*(-2 + b) + b**2) * t) \
- exp(b*t) * (4 + (-4*b + (a + b)**2) * t)) / ((a-b)**3 * t**2)
def _characteristic_function(self, t):
a, b = self.a, self.b
return -3*I*(exp(I*a*t*exp(I*b*t)) * (4*I - (-4*b + (a+b)**2)*t)) \
/ ((a-b)**3 * t**2)
def QuadraticU(name, a, b):
r"""
Create a Continuous Random Variable with a U-quadratic distribution.
The density of the U-quadratic distribution is given by
.. math::
f(x) := \alpha (x-\beta)^2
with :math:`x \in [a,b]`.
Parameters
==========
a : Real number
b : Real number, :math:`a < b`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import QuadraticU, density
>>> from sympy import Symbol, pprint
>>> a = Symbol("a", real=True)
>>> b = Symbol("b", real=True)
>>> z = Symbol("z")
>>> X = QuadraticU("x", a, b)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
/ 2
| / a b \
|12*|- - - - + z|
| \ 2 2 /
<----------------- for And(b >= z, a <= z)
| 3
| (-a + b)
|
\ 0 otherwise
References
==========
.. [1] https://en.wikipedia.org/wiki/U-quadratic_distribution
"""
return rv(name, QuadraticUDistribution, (a, b))
#-------------------------------------------------------------------------------
# RaisedCosine distribution ----------------------------------------------------
class RaisedCosineDistribution(SingleContinuousDistribution):
_argnames = ('mu', 's')
@property
def set(self):
return Interval(self.mu - self.s, self.mu + self.s)
@staticmethod
def check(mu, s):
_value_check(s > 0, "s must be positive")
def pdf(self, x):
mu, s = self.mu, self.s
return Piecewise(
((1+cos(pi*(x-mu)/s)) / (2*s), And(mu-s<=x, x<=mu+s)),
(S.Zero, True))
def _characteristic_function(self, t):
mu, s = self.mu, self.s
return Piecewise((exp(-I*pi*mu/s)/2, Eq(t, -pi/s)),
(exp(I*pi*mu/s)/2, Eq(t, pi/s)),
(pi**2*sin(s*t)*exp(I*mu*t) / (s*t*(pi**2 - s**2*t**2)), True))
def _moment_generating_function(self, t):
mu, s = self.mu, self.s
return pi**2 * sinh(s*t) * exp(mu*t) / (s*t*(pi**2 + s**2*t**2))
def RaisedCosine(name, mu, s):
r"""
Create a Continuous Random Variable with a raised cosine distribution.
The density of the raised cosine distribution is given by
.. math::
f(x) := \frac{1}{2s}\left(1+\cos\left(\frac{x-\mu}{s}\pi\right)\right)
with :math:`x \in [\mu-s,\mu+s]`.
Parameters
==========
mu : Real number
s : Real number, `s > 0`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import RaisedCosine, density
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu", real=True)
>>> s = Symbol("s", positive=True)
>>> z = Symbol("z")
>>> X = RaisedCosine("x", mu, s)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
/ /pi*(-mu + z)\
|cos|------------| + 1
| \ s /
<--------------------- for And(z >= mu - s, z <= mu + s)
| 2*s
|
\ 0 otherwise
References
==========
.. [1] https://en.wikipedia.org/wiki/Raised_cosine_distribution
"""
return rv(name, RaisedCosineDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Rayleigh distribution --------------------------------------------------------
class RayleighDistribution(SingleContinuousDistribution):
_argnames = ('sigma',)
set = Interval(0, oo)
@staticmethod
def check(sigma):
_value_check(sigma > 0, "Scale parameter sigma must be positive.")
def pdf(self, x):
sigma = self.sigma
return x/sigma**2*exp(-x**2/(2*sigma**2))
def _cdf(self, x):
sigma = self.sigma
return 1 - exp(-(x**2/(2*sigma**2)))
def _characteristic_function(self, t):
sigma = self.sigma
return 1 - sigma*t*exp(-sigma**2*t**2/2) * sqrt(pi/2) * (erfi(sigma*t/sqrt(2)) - I)
def _moment_generating_function(self, t):
sigma = self.sigma
return 1 + sigma*t*exp(sigma**2*t**2/2) * sqrt(pi/2) * (erf(sigma*t/sqrt(2)) + 1)
def Rayleigh(name, sigma):
r"""
Create a continuous random variable with a Rayleigh distribution.
The density of the Rayleigh distribution is given by
.. math ::
f(x) := \frac{x}{\sigma^2} e^{-x^2/2\sigma^2}
with :math:`x > 0`.
Parameters
==========
sigma : Real number, `\sigma > 0`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Rayleigh, density, E, variance
>>> from sympy import Symbol
>>> sigma = Symbol("sigma", positive=True)
>>> z = Symbol("z")
>>> X = Rayleigh("x", sigma)
>>> density(X)(z)
z*exp(-z**2/(2*sigma**2))/sigma**2
>>> E(X)
sqrt(2)*sqrt(pi)*sigma/2
>>> variance(X)
-pi*sigma**2/2 + 2*sigma**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Rayleigh_distribution
.. [2] http://mathworld.wolfram.com/RayleighDistribution.html
"""
return rv(name, RayleighDistribution, (sigma, ))
#-------------------------------------------------------------------------------
# Reciprocal distribution --------------------------------------------------------
class ReciprocalDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b')
@property
def set(self):
return Interval(self.a, self.b)
@staticmethod
def check(a, b):
_value_check(a > 0, "Parameter > 0. a = %s"%a)
_value_check((a < b),
"Parameter b must be in range (%s, +oo]. b = %s"%(a, b))
def pdf(self, x):
a, b = self.a, self.b
return 1/(x*(log(b) - log(a)))
def Reciprocal(name, a, b):
r"""Creates a continuous random variable with a reciprocal distribution.
Parameters
==========
a : Real number, :math:`0 < a`
b : Real number, :math:`a < b`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Reciprocal, density, cdf
>>> from sympy import symbols
>>> a, b, x = symbols('a, b, x', positive=True)
>>> R = Reciprocal('R', a, b)
>>> density(R)(x)
1/(x*(-log(a) + log(b)))
>>> cdf(R)(x)
Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True))
Reference
=========
.. [1] https://en.wikipedia.org/wiki/Reciprocal_distribution
"""
return rv(name, ReciprocalDistribution, (a, b))
#-------------------------------------------------------------------------------
# Shifted Gompertz distribution ------------------------------------------------
class ShiftedGompertzDistribution(SingleContinuousDistribution):
_argnames = ('b', 'eta')
set = Interval(0, oo)
@staticmethod
def check(b, eta):
_value_check(b > 0, "b must be positive")
_value_check(eta > 0, "eta must be positive")
def pdf(self, x):
b, eta = self.b, self.eta
return b*exp(-b*x)*exp(-eta*exp(-b*x))*(1+eta*(1-exp(-b*x)))
def ShiftedGompertz(name, b, eta):
r"""
Create a continuous random variable with a Shifted Gompertz distribution.
The density of the Shifted Gompertz distribution is given by
.. math::
f(x) := b e^{-b x} e^{-\eta \exp(-b x)} \left[1 + \eta(1 - e^(-bx)) \right]
with :math: 'x \in [0, \inf)'.
Parameters
==========
b: Real number, 'b > 0' a scale
eta: Real number, 'eta > 0' a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ShiftedGompertz, density
>>> from sympy import Symbol
>>> b = Symbol("b", positive=True)
>>> eta = Symbol("eta", positive=True)
>>> x = Symbol("x")
>>> X = ShiftedGompertz("x", b, eta)
>>> density(X)(x)
b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x))
References
==========
.. [1] https://en.wikipedia.org/wiki/Shifted_Gompertz_distribution
"""
return rv(name, ShiftedGompertzDistribution, (b, eta))
#-------------------------------------------------------------------------------
# StudentT distribution --------------------------------------------------------
class StudentTDistribution(SingleContinuousDistribution):
_argnames = ('nu',)
set = Interval(-oo, oo)
@staticmethod
def check(nu):
_value_check(nu > 0, "Degrees of freedom nu must be positive.")
def pdf(self, x):
nu = self.nu
return 1/(sqrt(nu)*beta_fn(S.Half, nu/2))*(1 + x**2/nu)**(-(nu + 1)/2)
def _cdf(self, x):
nu = self.nu
return S.Half + x*gamma((nu+1)/2)*hyper((S.Half, (nu+1)/2),
(Rational(3, 2),), -x**2/nu)/(sqrt(pi*nu)*gamma(nu/2))
def _moment_generating_function(self, t):
raise NotImplementedError('The moment generating function for the Student-T distribution is undefined.')
def StudentT(name, nu):
r"""
Create a continuous random variable with a student's t distribution.
The density of the student's t distribution is given by
.. math::
f(x) := \frac{\Gamma \left(\frac{\nu+1}{2} \right)}
{\sqrt{\nu\pi}\Gamma \left(\frac{\nu}{2} \right)}
\left(1+\frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}}
Parameters
==========
nu : Real number, `\nu > 0`, the degrees of freedom
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import StudentT, density, cdf
>>> from sympy import Symbol, pprint
>>> nu = Symbol("nu", positive=True)
>>> z = Symbol("z")
>>> X = StudentT("x", nu)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
nu 1
- -- - -
2 2
/ 2\
| z |
|1 + --|
\ nu/
-----------------
____ / nu\
\/ nu *B|1/2, --|
\ 2 /
>>> cdf(X)(z)
1/2 + z*gamma(nu/2 + 1/2)*hyper((1/2, nu/2 + 1/2), (3/2,),
-z**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Student_t-distribution
.. [2] http://mathworld.wolfram.com/Studentst-Distribution.html
"""
return rv(name, StudentTDistribution, (nu, ))
#-------------------------------------------------------------------------------
# Trapezoidal distribution ------------------------------------------------------
class TrapezoidalDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b', 'c', 'd')
@property
def set(self):
return Interval(self.a, self.d)
@staticmethod
def check(a, b, c, d):
_value_check(a < d, "Lower bound parameter a < %s. a = %s"%(d, a))
_value_check((a <= b, b < c),
"Level start parameter b must be in range [%s, %s). b = %s"%(a, c, b))
_value_check((b < c, c <= d),
"Level end parameter c must be in range (%s, %s]. c = %s"%(b, d, c))
_value_check(d >= c, "Upper bound parameter d > %s. d = %s"%(c, d))
def pdf(self, x):
a, b, c, d = self.a, self.b, self.c, self.d
return Piecewise(
(2*(x-a) / ((b-a)*(d+c-a-b)), And(a <= x, x < b)),
(2 / (d+c-a-b), And(b <= x, x < c)),
(2*(d-x) / ((d-c)*(d+c-a-b)), And(c <= x, x <= d)),
(S.Zero, True))
def Trapezoidal(name, a, b, c, d):
r"""
Create a continuous random variable with a trapezoidal distribution.
The density of the trapezoidal distribution is given by
.. math::
f(x) := \begin{cases}
0 & \mathrm{for\ } x < a, \\
\frac{2(x-a)}{(b-a)(d+c-a-b)} & \mathrm{for\ } a \le x < b, \\
\frac{2}{d+c-a-b} & \mathrm{for\ } b \le x < c, \\
\frac{2(d-x)}{(d-c)(d+c-a-b)} & \mathrm{for\ } c \le x < d, \\
0 & \mathrm{for\ } d < x.
\end{cases}
Parameters
==========
a : Real number, :math:`a < d`
b : Real number, :math:`a <= b < c`
c : Real number, :math:`b < c <= d`
d : Real number
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Trapezoidal, density
>>> from sympy import Symbol, pprint
>>> a = Symbol("a")
>>> b = Symbol("b")
>>> c = Symbol("c")
>>> d = Symbol("d")
>>> z = Symbol("z")
>>> X = Trapezoidal("x", a,b,c,d)
>>> pprint(density(X)(z), use_unicode=False)
/ -2*a + 2*z
|------------------------- for And(a <= z, b > z)
|(-a + b)*(-a - b + c + d)
|
| 2
| -------------- for And(b <= z, c > z)
< -a - b + c + d
|
| 2*d - 2*z
|------------------------- for And(d >= z, c <= z)
|(-c + d)*(-a - b + c + d)
|
\ 0 otherwise
References
==========
.. [1] https://en.wikipedia.org/wiki/Trapezoidal_distribution
"""
return rv(name, TrapezoidalDistribution, (a, b, c, d))
#-------------------------------------------------------------------------------
# Triangular distribution ------------------------------------------------------
class TriangularDistribution(SingleContinuousDistribution):
_argnames = ('a', 'b', 'c')
@property
def set(self):
return Interval(self.a, self.b)
@staticmethod
def check(a, b, c):
_value_check(b > a, "Parameter b > %s. b = %s"%(a, b))
_value_check((a <= c, c <= b),
"Parameter c must be in range [%s, %s]. c = %s"%(a, b, c))
def pdf(self, x):
a, b, c = self.a, self.b, self.c
return Piecewise(
(2*(x - a)/((b - a)*(c - a)), And(a <= x, x < c)),
(2/(b - a), Eq(x, c)),
(2*(b - x)/((b - a)*(b - c)), And(c < x, x <= b)),
(S.Zero, True))
def _characteristic_function(self, t):
a, b, c = self.a, self.b, self.c
return -2 *((b-c) * exp(I*a*t) - (b-a) * exp(I*c*t) + (c-a) * exp(I*b*t)) / ((b-a)*(c-a)*(b-c)*t**2)
def _moment_generating_function(self, t):
a, b, c = self.a, self.b, self.c
return 2 * ((b - c) * exp(a * t) - (b - a) * exp(c * t) + (c - a) * exp(b * t)) / (
(b - a) * (c - a) * (b - c) * t ** 2)
def Triangular(name, a, b, c):
r"""
Create a continuous random variable with a triangular distribution.
The density of the triangular distribution is given by
.. math::
f(x) := \begin{cases}
0 & \mathrm{for\ } x < a, \\
\frac{2(x-a)}{(b-a)(c-a)} & \mathrm{for\ } a \le x < c, \\
\frac{2}{b-a} & \mathrm{for\ } x = c, \\
\frac{2(b-x)}{(b-a)(b-c)} & \mathrm{for\ } c < x \le b, \\
0 & \mathrm{for\ } b < x.
\end{cases}
Parameters
==========
a : Real number, :math:`a \in \left(-\infty, \infty\right)`
b : Real number, :math:`a < b`
c : Real number, :math:`a \leq c \leq b`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Triangular, density
>>> from sympy import Symbol, pprint
>>> a = Symbol("a")
>>> b = Symbol("b")
>>> c = Symbol("c")
>>> z = Symbol("z")
>>> X = Triangular("x", a,b,c)
>>> pprint(density(X)(z), use_unicode=False)
/ -2*a + 2*z
|----------------- for And(a <= z, c > z)
|(-a + b)*(-a + c)
|
| 2
| ------ for c = z
< -a + b
|
| 2*b - 2*z
|---------------- for And(b >= z, c < z)
|(-a + b)*(b - c)
|
\ 0 otherwise
References
==========
.. [1] https://en.wikipedia.org/wiki/Triangular_distribution
.. [2] http://mathworld.wolfram.com/TriangularDistribution.html
"""
return rv(name, TriangularDistribution, (a, b, c))
#-------------------------------------------------------------------------------
# Uniform distribution ---------------------------------------------------------
class UniformDistribution(SingleContinuousDistribution):
_argnames = ('left', 'right')
@property
def set(self):
return Interval(self.left, self.right)
@staticmethod
def check(left, right):
_value_check(left < right, "Lower limit should be less than Upper limit.")
def pdf(self, x):
left, right = self.left, self.right
return Piecewise(
(S.One/(right - left), And(left <= x, x <= right)),
(S.Zero, True)
)
def _cdf(self, x):
left, right = self.left, self.right
return Piecewise(
(S.Zero, x < left),
((x - left)/(right - left), x <= right),
(S.One, True)
)
def _characteristic_function(self, t):
left, right = self.left, self.right
return Piecewise(((exp(I*t*right) - exp(I*t*left)) / (I*t*(right - left)), Ne(t, 0)),
(S.One, True))
def _moment_generating_function(self, t):
left, right = self.left, self.right
return Piecewise(((exp(t*right) - exp(t*left)) / (t * (right - left)), Ne(t, 0)),
(S.One, True))
def expectation(self, expr, var, **kwargs):
from sympy import Max, Min
kwargs['evaluate'] = True
result = SingleContinuousDistribution.expectation(self, expr, var, **kwargs)
result = result.subs({Max(self.left, self.right): self.right,
Min(self.left, self.right): self.left})
return result
def Uniform(name, left, right):
r"""
Create a continuous random variable with a uniform distribution.
The density of the uniform distribution is given by
.. math::
f(x) := \begin{cases}
\frac{1}{b - a} & \text{for } x \in [a,b] \\
0 & \text{otherwise}
\end{cases}
with :math:`x \in [a,b]`.
Parameters
==========
a : Real number, :math:`-\infty < a` the left boundary
b : Real number, :math:`a < b < \infty` the right boundary
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Uniform, density, cdf, E, variance
>>> from sympy import Symbol, simplify
>>> a = Symbol("a", negative=True)
>>> b = Symbol("b", positive=True)
>>> z = Symbol("z")
>>> X = Uniform("x", a, b)
>>> density(X)(z)
Piecewise((1/(-a + b), (b >= z) & (a <= z)), (0, True))
>>> cdf(X)(z)
Piecewise((0, a > z), ((-a + z)/(-a + b), b >= z), (1, True))
>>> E(X)
a/2 + b/2
>>> simplify(variance(X))
a**2/12 - a*b/6 + b**2/12
References
==========
.. [1] https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29
.. [2] http://mathworld.wolfram.com/UniformDistribution.html
"""
return rv(name, UniformDistribution, (left, right))
#-------------------------------------------------------------------------------
# UniformSum distribution ------------------------------------------------------
class UniformSumDistribution(SingleContinuousDistribution):
_argnames = ('n',)
@property
def set(self):
return Interval(0, self.n)
@staticmethod
def check(n):
_value_check((n > 0, n.is_integer),
"Parameter n must be positive integer.")
def pdf(self, x):
n = self.n
k = Dummy("k")
return 1/factorial(
n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x)))
def _cdf(self, x):
n = self.n
k = Dummy("k")
return Piecewise((S.Zero, x < 0),
(1/factorial(n)*Sum((-1)**k*binomial(n, k)*(x - k)**(n),
(k, 0, floor(x))), x <= n),
(S.One, True))
def _characteristic_function(self, t):
return ((exp(I*t) - 1) / (I*t))**self.n
def _moment_generating_function(self, t):
return ((exp(t) - 1) / t)**self.n
def UniformSum(name, n):
r"""
Create a continuous random variable with an Irwin-Hall distribution.
The probability distribution function depends on a single parameter
`n` which is an integer.
The density of the Irwin-Hall distribution is given by
.. math ::
f(x) := \frac{1}{(n-1)!}\sum_{k=0}^{\left\lfloor x\right\rfloor}(-1)^k
\binom{n}{k}(x-k)^{n-1}
Parameters
==========
n : A positive Integer, `n > 0`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import UniformSum, density, cdf
>>> from sympy import Symbol, pprint
>>> n = Symbol("n", integer=True)
>>> z = Symbol("z")
>>> X = UniformSum("x", n)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
floor(z)
___
\ `
\ k n - 1 /n\
) (-1) *(-k + z) *| |
/ \k/
/__,
k = 0
--------------------------------
(n - 1)!
>>> cdf(X)(z)
Piecewise((0, z < 0), (Sum((-1)**_k*(-_k + z)**n*binomial(n, _k),
(_k, 0, floor(z)))/factorial(n), n >= z), (1, True))
Compute cdf with specific 'x' and 'n' values as follows :
>>> cdf(UniformSum("x", 5), evaluate=False)(2).doit()
9/40
The argument evaluate=False prevents an attempt at evaluation
of the sum for general n, before the argument 2 is passed.
References
==========
.. [1] https://en.wikipedia.org/wiki/Uniform_sum_distribution
.. [2] http://mathworld.wolfram.com/UniformSumDistribution.html
"""
return rv(name, UniformSumDistribution, (n, ))
#-------------------------------------------------------------------------------
# VonMises distribution --------------------------------------------------------
class VonMisesDistribution(SingleContinuousDistribution):
_argnames = ('mu', 'k')
set = Interval(0, 2*pi)
@staticmethod
def check(mu, k):
_value_check(k > 0, "k must be positive")
def pdf(self, x):
mu, k = self.mu, self.k
return exp(k*cos(x-mu)) / (2*pi*besseli(0, k))
def VonMises(name, mu, k):
r"""
Create a Continuous Random Variable with a von Mises distribution.
The density of the von Mises distribution is given by
.. math::
f(x) := \frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)}
with :math:`x \in [0,2\pi]`.
Parameters
==========
mu : Real number, measure of location
k : Real number, measure of concentration
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import VonMises, density
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu")
>>> k = Symbol("k", positive=True)
>>> z = Symbol("z")
>>> X = VonMises("x", mu, k)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
k*cos(mu - z)
e
------------------
2*pi*besseli(0, k)
References
==========
.. [1] https://en.wikipedia.org/wiki/Von_Mises_distribution
.. [2] http://mathworld.wolfram.com/vonMisesDistribution.html
"""
return rv(name, VonMisesDistribution, (mu, k))
#-------------------------------------------------------------------------------
# Weibull distribution ---------------------------------------------------------
class WeibullDistribution(SingleContinuousDistribution):
_argnames = ('alpha', 'beta')
set = Interval(0, oo)
@staticmethod
def check(alpha, beta):
_value_check(alpha > 0, "Alpha must be positive")
_value_check(beta > 0, "Beta must be positive")
def pdf(self, x):
alpha, beta = self.alpha, self.beta
return beta * (x/alpha)**(beta - 1) * exp(-(x/alpha)**beta) / alpha
def Weibull(name, alpha, beta):
r"""
Create a continuous random variable with a Weibull distribution.
The density of the Weibull distribution is given by
.. math::
f(x) := \begin{cases}
\frac{k}{\lambda}\left(\frac{x}{\lambda}\right)^{k-1}
e^{-(x/\lambda)^{k}} & x\geq0\\
0 & x<0
\end{cases}
Parameters
==========
lambda : Real number, :math:`\lambda > 0` a scale
k : Real number, `k > 0` a shape
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Weibull, density, E, variance
>>> from sympy import Symbol, simplify
>>> l = Symbol("lambda", positive=True)
>>> k = Symbol("k", positive=True)
>>> z = Symbol("z")
>>> X = Weibull("x", l, k)
>>> density(X)(z)
k*(z/lambda)**(k - 1)*exp(-(z/lambda)**k)/lambda
>>> simplify(E(X))
lambda*gamma(1 + 1/k)
>>> simplify(variance(X))
lambda**2*(-gamma(1 + 1/k)**2 + gamma(1 + 2/k))
References
==========
.. [1] https://en.wikipedia.org/wiki/Weibull_distribution
.. [2] http://mathworld.wolfram.com/WeibullDistribution.html
"""
return rv(name, WeibullDistribution, (alpha, beta))
#-------------------------------------------------------------------------------
# Wigner semicircle distribution -----------------------------------------------
class WignerSemicircleDistribution(SingleContinuousDistribution):
_argnames = ('R',)
@property
def set(self):
return Interval(-self.R, self.R)
@staticmethod
def check(R):
_value_check(R > 0, "Radius R must be positive.")
def pdf(self, x):
R = self.R
return 2/(pi*R**2)*sqrt(R**2 - x**2)
def _characteristic_function(self, t):
return Piecewise((2 * besselj(1, self.R*t) / (self.R*t), Ne(t, 0)),
(S.One, True))
def _moment_generating_function(self, t):
return Piecewise((2 * besseli(1, self.R*t) / (self.R*t), Ne(t, 0)),
(S.One, True))
def WignerSemicircle(name, R):
r"""
Create a continuous random variable with a Wigner semicircle distribution.
The density of the Wigner semicircle distribution is given by
.. math::
f(x) := \frac2{\pi R^2}\,\sqrt{R^2-x^2}
with :math:`x \in [-R,R]`.
Parameters
==========
R : Real number, `R > 0`, the radius
Returns
=======
A `RandomSymbol`.
Examples
========
>>> from sympy.stats import WignerSemicircle, density, E
>>> from sympy import Symbol
>>> R = Symbol("R", positive=True)
>>> z = Symbol("z")
>>> X = WignerSemicircle("x", R)
>>> density(X)(z)
2*sqrt(R**2 - z**2)/(pi*R**2)
>>> E(X)
0
References
==========
.. [1] https://en.wikipedia.org/wiki/Wigner_semicircle_distribution
.. [2] http://mathworld.wolfram.com/WignersSemicircleLaw.html
"""
return rv(name, WignerSemicircleDistribution, (R,))
|
f5dcfa7fb088eee67c0dd8d32b494d90476237a9c5927741f3725c09117322e1 | """
Finite Discrete Random Variables - Prebuilt variable types
Contains
========
FiniteRV
DiscreteUniform
Die
Bernoulli
Coin
Binomial
BetaBinomial
Hypergeometric
Rademacher
IdealSoliton
RobustSoliton
"""
from sympy import (S, sympify, Rational, binomial, cacheit, Integer,
Dummy, Eq, Intersection, Interval, log, Range,
Symbol, Lambda, Piecewise, Or, Gt, Lt, Ge, Le, Contains)
from sympy import beta as beta_fn
from sympy.stats.frv import (SingleFiniteDistribution,
SingleFinitePSpace)
from sympy.stats.rv import _value_check, Density, is_random
__all__ = ['FiniteRV',
'DiscreteUniform',
'Die',
'Bernoulli',
'Coin',
'Binomial',
'BetaBinomial',
'Hypergeometric',
'Rademacher',
'IdealSoliton',
'RobustSoliton',
]
def rv(name, cls, *args, **kwargs):
args = list(map(sympify, args))
dist = cls(*args)
if kwargs.pop('check', True):
dist.check(*args)
pspace = SingleFinitePSpace(name, dist)
if any(is_random(arg) for arg in args):
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
pspace = CompoundPSpace(name, CompoundDistribution(dist))
return pspace.value
class FiniteDistributionHandmade(SingleFiniteDistribution):
@property
def dict(self):
return self.args[0]
def pmf(self, x):
x = Symbol('x')
return Lambda(x, Piecewise(*(
[(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)])))
@property
def set(self):
return set(self.dict.keys())
@staticmethod
def check(density):
for p in density.values():
_value_check((p >= 0, p <= 1),
"Probability at a point must be between 0 and 1.")
val = sum(density.values())
_value_check(Eq(val, 1) != S.false, "Total Probability must be 1.")
def FiniteRV(name, density, **kwargs):
r"""
Create a Finite Random Variable given a dict representing the density.
Parameters
==========
name : Symbol
Represents name of the random variable.
density: A dict
Dictionary conatining the pdf of finite distribution
check : bool
If True, it will check whether the given density
integrates to 1 over the given set. If False, it
will not perform this check. Default is False.
Examples
========
>>> from sympy.stats import FiniteRV, P, E
>>> density = {0: .1, 1: .2, 2: .3, 3: .4}
>>> X = FiniteRV('X', density)
>>> E(X)
2.00000000000000
>>> P(X >= 2)
0.700000000000000
Returns
=======
RandomSymbol
"""
# have a default of False while `rv` should have a default of True
kwargs['check'] = kwargs.pop('check', False)
return rv(name, FiniteDistributionHandmade, density, **kwargs)
class DiscreteUniformDistribution(SingleFiniteDistribution):
@staticmethod
def check(*args):
# not using _value_check since there is a
# suggestion for the user
if len(set(args)) != len(args):
from sympy.utilities.iterables import multiset
from sympy.utilities.misc import filldedent
weights = multiset(args)
n = Integer(len(args))
for k in weights:
weights[k] /= n
raise ValueError(filldedent("""
Repeated args detected but set expected. For a
distribution having different weights for each
item use the following:""") + (
'\nS("FiniteRV(%s, %s)")' % ("'X'", weights)))
@property
def p(self):
return Rational(1, len(self.args))
@property # type: ignore
@cacheit
def dict(self):
return {k: self.p for k in self.set}
@property
def set(self):
return set(self.args)
def pmf(self, x):
if x in self.args:
return self.p
else:
return S.Zero
def DiscreteUniform(name, items):
r"""
Create a Finite Random Variable representing a uniform distribution over
the input set.
Parameters
==========
items: list/tuple
Items over which Uniform distribution is to be made
Examples
========
>>> from sympy.stats import DiscreteUniform, density
>>> from sympy import symbols
>>> X = DiscreteUniform('X', symbols('a b c')) # equally likely over a, b, c
>>> density(X).dict
{a: 1/3, b: 1/3, c: 1/3}
>>> Y = DiscreteUniform('Y', list(range(5))) # distribution over a range
>>> density(Y).dict
{0: 1/5, 1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5}
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Discrete_uniform_distribution
.. [2] http://mathworld.wolfram.com/DiscreteUniformDistribution.html
"""
return rv(name, DiscreteUniformDistribution, *items)
class DieDistribution(SingleFiniteDistribution):
_argnames = ('sides',)
@staticmethod
def check(sides):
_value_check((sides.is_positive, sides.is_integer),
"number of sides must be a positive integer.")
@property
def is_symbolic(self):
return not self.sides.is_number
@property
def high(self):
return self.sides
@property
def low(self):
return S.One
@property
def set(self):
if self.is_symbolic:
return Intersection(S.Naturals0, Interval(0, self.sides))
return set(map(Integer, list(range(1, self.sides + 1))))
def pmf(self, x):
x = sympify(x)
if not (x.is_number or x.is_Symbol or is_random(x)):
raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , "
"'RandomSymbol' not %s" % (type(x)))
cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers)
return Piecewise((S.One/self.sides, cond), (S.Zero, True))
def Die(name, sides=6):
r"""
Create a Finite Random Variable representing a fair die.
Parameters
==========
sides: Integer
Represents the number of sides of the Die, by default is 6
Examples
========
>>> from sympy.stats import Die, density
>>> from sympy import Symbol
>>> D6 = Die('D6', 6) # Six sided Die
>>> density(D6).dict
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> D4 = Die('D4', 4) # Four sided Die
>>> density(D4).dict
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
>>> n = Symbol('n', positive=True, integer=True)
>>> Dn = Die('Dn', n) # n sided Die
>>> density(Dn).dict
Density(DieDistribution(n))
>>> density(Dn).dict.subs(n, 4).doit()
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
Returns
=======
RandomSymbol
"""
return rv(name, DieDistribution, sides)
class BernoulliDistribution(SingleFiniteDistribution):
_argnames = ('p', 'succ', 'fail')
@staticmethod
def check(p, succ, fail):
_value_check((p >= 0, p <= 1),
"p should be in range [0, 1].")
@property
def set(self):
return {self.succ, self.fail}
def pmf(self, x):
if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol):
return Piecewise((self.p, x == self.succ),
(1 - self.p, x == self.fail),
(S.Zero, True))
return Piecewise((self.p, Eq(x, self.succ)),
(1 - self.p, Eq(x, self.fail)),
(S.Zero, True))
def Bernoulli(name, p, succ=1, fail=0):
r"""
Create a Finite Random Variable representing a Bernoulli process.
Parameters
==========
p : Rational number between 0 and 1
Represents probability of success
succ : Integer/symbol/string
Represents event of success
fail : Integer/symbol/string
Represents event of failure
Examples
========
>>> from sympy.stats import Bernoulli, density
>>> from sympy import S
>>> X = Bernoulli('X', S(3)/4) # 1-0 Bernoulli variable, probability = 3/4
>>> density(X).dict
{0: 1/4, 1: 3/4}
>>> X = Bernoulli('X', S.Half, 'Heads', 'Tails') # A fair coin toss
>>> density(X).dict
{Heads: 1/2, Tails: 1/2}
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_distribution
.. [2] http://mathworld.wolfram.com/BernoulliDistribution.html
"""
return rv(name, BernoulliDistribution, p, succ, fail)
def Coin(name, p=S.Half):
r"""
Create a Finite Random Variable representing a Coin toss.
Parameters
==========
p : Rational Numeber between 0 and 1
Represents probability of getting "Heads", by default is Half
Examples
========
>>> from sympy.stats import Coin, density
>>> from sympy import Rational
>>> C = Coin('C') # A fair coin toss
>>> density(C).dict
{H: 1/2, T: 1/2}
>>> C2 = Coin('C2', Rational(3, 5)) # An unfair coin
>>> density(C2).dict
{H: 3/5, T: 2/5}
Returns
=======
RandomSymbol
See Also
========
sympy.stats.Binomial
References
==========
.. [1] https://en.wikipedia.org/wiki/Coin_flipping
"""
return rv(name, BernoulliDistribution, p, 'H', 'T')
class BinomialDistribution(SingleFiniteDistribution):
_argnames = ('n', 'p', 'succ', 'fail')
@staticmethod
def check(n, p, succ, fail):
_value_check((n.is_integer, n.is_nonnegative),
"'n' must be nonnegative integer.")
_value_check((p <= 1, p >= 0),
"p should be in range [0, 1].")
@property
def high(self):
return self.n
@property
def low(self):
return S.Zero
@property
def is_symbolic(self):
return not self.n.is_number
@property
def set(self):
if self.is_symbolic:
return Intersection(S.Naturals0, Interval(0, self.n))
return set(self.dict.keys())
def pmf(self, x):
n, p = self.n, self.p
x = sympify(x)
if not (x.is_number or x.is_Symbol or is_random(x)):
raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , "
"'RandomSymbol' not %s" % (type(x)))
cond = Ge(x, 0) & Le(x, n) & Contains(x, S.Integers)
return Piecewise((binomial(n, x) * p**x * (1 - p)**(n - x), cond), (S.Zero, True))
@property # type: ignore
@cacheit
def dict(self):
if self.is_symbolic:
return Density(self)
return {k*self.succ + (self.n-k)*self.fail: self.pmf(k)
for k in range(0, self.n + 1)}
def Binomial(name, n, p, succ=1, fail=0):
r"""
Create a Finite Random Variable representing a binomial distribution.
Parameters
==========
n : Positive Integer
Represents number of trials
p : Rational Number between 0 and 1
Represents probability of success
succ : Integer/symbol/string
Represents event of success, by default is 1
fail : Integer/symbol/string
Represents event of failure, by default is 0
Examples
========
>>> from sympy.stats import Binomial, density
>>> from sympy import S, Symbol
>>> X = Binomial('X', 4, S.Half) # Four "coin flips"
>>> density(X).dict
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
>>> n = Symbol('n', positive=True, integer=True)
>>> p = Symbol('p', positive=True)
>>> X = Binomial('X', n, S.Half) # n "coin flips"
>>> density(X).dict
Density(BinomialDistribution(n, 1/2, 1, 0))
>>> density(X).dict.subs(n, 4).doit()
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Binomial_distribution
.. [2] http://mathworld.wolfram.com/BinomialDistribution.html
"""
return rv(name, BinomialDistribution, n, p, succ, fail)
#-------------------------------------------------------------------------------
# Beta-binomial distribution ----------------------------------------------------------
class BetaBinomialDistribution(SingleFiniteDistribution):
_argnames = ('n', 'alpha', 'beta')
@staticmethod
def check(n, alpha, beta):
_value_check((n.is_integer, n.is_nonnegative),
"'n' must be nonnegative integer. n = %s." % str(n))
_value_check((alpha > 0),
"'alpha' must be: alpha > 0 . alpha = %s" % str(alpha))
_value_check((beta > 0),
"'beta' must be: beta > 0 . beta = %s" % str(beta))
@property
def high(self):
return self.n
@property
def low(self):
return S.Zero
@property
def is_symbolic(self):
return not self.n.is_number
@property
def set(self):
if self.is_symbolic:
return Intersection(S.Naturals0, Interval(0, self.n))
return set(map(Integer, list(range(0, self.n + 1))))
def pmf(self, k):
n, a, b = self.n, self.alpha, self.beta
return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b)
def BetaBinomial(name, n, alpha, beta):
r"""
Create a Finite Random Variable representing a Beta-binomial distribution.
Parameters
==========
n : Positive Integer
Represents number of trials
alpha : Real positive number
beta : Real positive number
Examples
========
>>> from sympy.stats import BetaBinomial, density
>>> X = BetaBinomial('X', 2, 1, 1)
>>> density(X).dict
{0: 1/3, 1: 2*beta(2, 2), 2: 1/3}
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
.. [2] http://mathworld.wolfram.com/BetaBinomialDistribution.html
"""
return rv(name, BetaBinomialDistribution, n, alpha, beta)
class HypergeometricDistribution(SingleFiniteDistribution):
_argnames = ('N', 'm', 'n')
@staticmethod
def check(n, N, m):
_value_check((N.is_integer, N.is_nonnegative),
"'N' must be nonnegative integer. N = %s." % str(n))
_value_check((n.is_integer, n.is_nonnegative),
"'n' must be nonnegative integer. n = %s." % str(n))
_value_check((m.is_integer, m.is_nonnegative),
"'m' must be nonnegative integer. m = %s." % str(n))
@property
def is_symbolic(self):
return any(not x.is_number for x in (self.N, self.m, self.n))
@property
def high(self):
return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True))
@property
def low(self):
return Piecewise((0, Gt(0, self.n + self.m - self.N) != False), (self.n + self.m - self.N, True))
@property
def set(self):
N, m, n = self.N, self.m, self.n
if self.is_symbolic:
return Intersection(S.Naturals0, Interval(self.low, self.high))
return {i for i in range(max(0, n + m - N), min(n, m) + 1)}
def pmf(self, k):
N, m, n = self.N, self.m, self.n
return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n)
def Hypergeometric(name, N, m, n):
r"""
Create a Finite Random Variable representing a hypergeometric distribution.
Parameters
==========
N : Positive Integer
Represents finite population of size N.
m : Positive Integer
Represents number of trials with required feature.
n : Positive Integer
Represents numbers of draws.
Examples
========
>>> from sympy.stats import Hypergeometric, density
>>> X = Hypergeometric('X', 10, 5, 3) # 10 marbles, 5 white (success), 3 draws
>>> density(X).dict
{0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12}
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Hypergeometric_distribution
.. [2] http://mathworld.wolfram.com/HypergeometricDistribution.html
"""
return rv(name, HypergeometricDistribution, N, m, n)
class RademacherDistribution(SingleFiniteDistribution):
@property
def set(self):
return {-1, 1}
@property
def pmf(self):
k = Dummy('k')
return Lambda(k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True)))
def Rademacher(name):
r"""
Create a Finite Random Variable representing a Rademacher distribution.
Examples
========
>>> from sympy.stats import Rademacher, density
>>> X = Rademacher('X')
>>> density(X).dict
{-1: 1/2, 1: 1/2}
Returns
=======
RandomSymbol
See Also
========
sympy.stats.Bernoulli
References
==========
.. [1] https://en.wikipedia.org/wiki/Rademacher_distribution
"""
return rv(name, RademacherDistribution)
class IdealSolitonDistribution(SingleFiniteDistribution):
_argnames = ('k',)
@staticmethod
def check(k):
_value_check(k.is_integer and k.is_positive,
"'k' must be a positive integer.")
@property
def low(self):
return S.One
@property
def high(self):
return self.k
@property
def set(self):
return set(list(Range(1, self.k+1)))
@property
@cacheit
def dict(self):
if self.k.is_Symbol:
return Density(self)
d = {1: Rational(1, self.k)}
d.update(dict((i, Rational(1, i*(i - 1))) for i in range(2, self.k + 1)))
return d
def pmf(self, x):
x = sympify(x)
if not (x.is_number or x.is_Symbol or is_random(x)):
raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , "
"'RandomSymbol' not %s" % (type(x)))
cond1 = Eq(x, 1) & x.is_integer
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
return Piecewise((1/self.k, cond1), (1/(x*(x - 1)), cond2), (S.Zero, True))
def IdealSoliton(name, k):
r"""
Create a Finite Random Variable of Ideal Soliton Distribution
Parameters
==========
k : Positive Integer
Represents the number of input symbols in an LT (Luby Transform) code.
Examples
========
>>> from sympy.stats import IdealSoliton, density, P, E
>>> sol = IdealSoliton('sol', 5)
>>> density(sol).dict
{1: 1/5, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20}
>>> density(sol).set
{1, 2, 3, 4, 5}
>>> from sympy import Symbol
>>> k = Symbol('k', positive=True, integer=True)
>>> sol = IdealSoliton('sol', k)
>>> density(sol).dict
Density(IdealSolitonDistribution(k))
>>> density(sol).dict.subs(k, 10).doit()
{1: 1/10, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20, 6: 1/30, 7: 1/42, 8: 1/56, 9: 1/72, 10: 1/90}
>>> E(sol.subs(k, 10))
7381/2520
>>> P(sol.subs(k, 4) > 2)
1/4
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Ideal_distribution
.. [2] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
"""
return rv(name, IdealSolitonDistribution, k)
class RobustSolitonDistribution(SingleFiniteDistribution):
_argnames= ('k', 'delta', 'c')
@staticmethod
def check(k, delta, c):
_value_check(k.is_integer and k.is_positive,
"'k' must be a positive integer")
_value_check(Gt(delta, 0) and Le(delta, 1),
"'delta' must be a real number in the interval (0,1)")
_value_check(c.is_positive,
"'c' must be a positive real number.")
@property
def R(self):
return self.c * log(self.k/self.delta) * self.k**0.5
@property
def Z(self):
z = 0
for i in Range(1, round(self.k/self.R)):
z += (1/i)
z += log(self.R/self.delta)
return 1 + z * self.R/self.k
@property
def low(self):
return S.One
@property
def high(self):
return self.k
@property
def set(self):
return set(list(Range(1, self.k+1)))
@property
def is_symbolic(self):
return not all([self.k.is_number, self.c.is_number, self.delta.is_number])
def pmf(self, x):
x = sympify(x)
if not (x.is_number or x.is_Symbol or is_random(x)):
raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , "
"'RandomSymbol' not %s" % (type(x)))
cond1 = Eq(x, 1) & x.is_integer
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
rho = Piecewise((Rational(1, self.k), cond1), (Rational(1, x*(x-1)), cond2), (S.Zero, True))
cond1 = Ge(x, 1) & Le(x, round(self.k/self.R)-1)
cond2 = Eq(x, round(self.k/self.R))
tau = Piecewise((self.R/(self.k * x), cond1), (self.R * log(self.R/self.delta)/self.k, cond2), (S.Zero, True))
return (rho + tau)/self.Z
def RobustSoliton(name, k, delta, c):
r'''
Create a Finite Random Variable of Robust Soliton Distribution
Parameters
==========
k : Positive Integer
Represents the number of input symbols in an LT (Luby Transform) code.
delta : Positive Rational Number
Represents the failure probability. Must be in the interval (0,1).
c : Positive Rational Number
Constant of proportionality. Values close to 1 are recommended
Examples
========
>>> from sympy.stats import RobustSoliton, density, P, E
>>> robSol = RobustSoliton('robSol', 5, 0.5, 0.01)
>>> density(robSol).dict
{1: 0.204253668152708, 2: 0.490631107897393, 3: 0.165210624506162, 4: 0.0834387731899302, 5: 0.0505633404760675}
>>> density(robSol).set
{1, 2, 3, 4, 5}
>>> from sympy import Symbol
>>> k = Symbol('k', positive=True, integer=True)
>>> c = Symbol('c', positive=True)
>>> robSol = RobustSoliton('robSol', k, 0.5, c)
>>> density(robSol).dict
Density(RobustSolitonDistribution(k, 0.5, c))
>>> density(robSol).dict.subs(k, 10).subs(c, 0.03).doit()
{1: 0.116641095387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100,
6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887}
>>> E(robSol.subs(k, 10).subs(c, 0.05))
2.91358846104106
>>> P(robSol.subs(k, 4).subs(c, 0.1) > 2)
0.243650614389834
Returns
=======
RandomSymbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Robust_distribution
.. [2] http://www.inference.org.uk/mackay/itprnn/ps/588.596.pdf
.. [3] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
'''
return rv(name, RobustSolitonDistribution, k, delta, c)
|
39ab2b5166c173176902019daf27b06ea6090fe41e8f8a85271edaea618aa89b | """
Contains
========
FlorySchulz
Geometric
Hermite
Logarithmic
NegativeBinomial
Poisson
Skellam
YuleSimon
Zeta
"""
from sympy import (Basic, factorial, exp, S, sympify, I, zeta, polylog, log, beta,
hyper, binomial, Piecewise, floor, besseli, sqrt, Sum, Dummy,
Lambda, Eq)
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
from sympy.stats.rv import _value_check, is_random
__all__ = ['FlorySchulz',
'Geometric',
'Hermite',
'Logarithmic',
'NegativeBinomial',
'Poisson',
'Skellam',
'YuleSimon',
'Zeta'
]
def rv(symbol, cls, *args, **kwargs):
args = list(map(sympify, args))
dist = cls(*args)
if kwargs.pop('check', True):
dist.check(*args)
pspace = SingleDiscretePSpace(symbol, dist)
if any(is_random(arg) for arg in args):
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
pspace = CompoundPSpace(symbol, CompoundDistribution(dist))
return pspace.value
class DiscreteDistributionHandmade(SingleDiscreteDistribution):
_argnames = ('pdf',)
def __new__(cls, pdf, set=S.Integers):
return Basic.__new__(cls, pdf, set)
@property
def set(self):
return self.args[1]
@staticmethod
def check(pdf, set):
x = Dummy('x')
val = Sum(pdf(x), (x, set._inf, set._sup)).doit()
_value_check(Eq(val, 1) != S.false, "The pdf is incorrect on the given set.")
def DiscreteRV(symbol, density, set=S.Integers, **kwargs):
"""
Create a Discrete Random Variable given the following:
Parameters
==========
symbol : Symbol
Represents name of the random variable.
density : Expression containing symbol
Represents probability density function.
set : set
Represents the region where the pdf is valid, by default is real line.
check : bool
If True, it will check whether the given density
integrates to 1 over the given set. If False, it
will not perform this check. Default is False.
Examples
========
>>> from sympy.stats import DiscreteRV, P, E
>>> from sympy import Rational, Symbol
>>> x = Symbol('x')
>>> n = 10
>>> density = Rational(1, 10)
>>> X = DiscreteRV(x, density, set=set(range(n)))
>>> E(X)
9/2
>>> P(X>3)
3/5
Returns
=======
RandomSymbol
"""
set = sympify(set)
pdf = Piecewise((density, set.as_relational(symbol)), (0, True))
pdf = Lambda(symbol, pdf)
# have a default of False while `rv` should have a default of True
kwargs['check'] = kwargs.pop('check', False)
return rv(symbol.name, DiscreteDistributionHandmade, pdf, set, **kwargs)
#-------------------------------------------------------------------------------
# Flory-Schulz distribution ------------------------------------------------------------
class FlorySchulzDistribution(SingleDiscreteDistribution):
_argnames = ('a',)
set = S.Naturals
@staticmethod
def check(a):
_value_check((0 < a, a < 1), "a must be between 0 and 1")
def pdf(self, k):
a = self.a
return (a**2 * k * (1 - a)**(k - 1))
def _characteristic_function(self, t):
a = self.a
return a**2*exp(I*t)/((1 + (a - 1)*exp(I*t))**2)
def _moment_generating_function(self, t):
a = self.a
return a**2*exp(t)/((1 + (a - 1)*exp(t))**2)
def FlorySchulz(name, a):
r"""
Create a discrete random variable with a FlorySchulz distribution.
The density of the FlorySchulz distribution is given by
.. math::
f(k) := (a^2) k (1 - a)^{k-1}
Parameters
==========
a
A real number between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, E, variance, FlorySchulz
>>> from sympy import Symbol, S
>>> a = S.One / 5
>>> z = Symbol("z")
>>> X = FlorySchulz("x", a)
>>> density(X)(z)
(4/5)**(z - 1)*z/25
>>> E(X)
9
>>> variance(X)
40
References
==========
https://en.wikipedia.org/wiki/Flory%E2%80%93Schulz_distribution
"""
return rv(name, FlorySchulzDistribution, a)
#-------------------------------------------------------------------------------
# Geometric distribution ------------------------------------------------------------
class GeometricDistribution(SingleDiscreteDistribution):
_argnames = ('p',)
set = S.Naturals
@staticmethod
def check(p):
_value_check((0 < p, p <= 1), "p must be between 0 and 1")
def pdf(self, k):
return (1 - self.p)**(k - 1) * self.p
def _characteristic_function(self, t):
p = self.p
return p * exp(I*t) / (1 - (1 - p)*exp(I*t))
def _moment_generating_function(self, t):
p = self.p
return p * exp(t) / (1 - (1 - p) * exp(t))
def Geometric(name, p):
r"""
Create a discrete random variable with a Geometric distribution.
The density of the Geometric distribution is given by
.. math::
f(k) := p (1 - p)^{k - 1}
Parameters
==========
p: A probability between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Geometric, density, E, variance
>>> from sympy import Symbol, S
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = Geometric("x", p)
>>> density(X)(z)
(4/5)**(z - 1)/5
>>> E(X)
5
>>> variance(X)
20
References
==========
.. [1] https://en.wikipedia.org/wiki/Geometric_distribution
.. [2] http://mathworld.wolfram.com/GeometricDistribution.html
"""
return rv(name, GeometricDistribution, p)
#-------------------------------------------------------------------------------
# Hermite distribution ---------------------------------------------------------
class HermiteDistribution(SingleDiscreteDistribution):
_argnames = ('a1', 'a2')
set = S.Naturals0
@staticmethod
def check(a1, a2):
_value_check(a1.is_nonnegative, 'Parameter a1 must be >= 0.')
_value_check(a2.is_nonnegative, 'Parameter a2 must be >= 0.')
def pdf(self, k):
a1, a2 = self.a1, self.a2
term1 = exp(-(a1 + a2))
j = Dummy("j", integer=True)
num = a1**(k - 2*j) * a2**j
den = factorial(k - 2*j) * factorial(j)
return term1 * Sum(num/den, (j, 0, k//2)).doit()
def _moment_generating_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(t) - 1)
term2 = a2 * (exp(2*t) - 1)
return exp(term1 + term2)
def _characteristic_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(I*t) - 1)
term2 = a2 * (exp(2*I*t) - 1)
return exp(term1 + term2)
def Hermite(name, a1, a2):
r"""
Create a discrete random variable with a Hermite distribution.
The density of the Hermite distribution is given by
.. math::
f(x):= e^{-a_1 -a_2}\sum_{j=0}^{\left \lfloor x/2 \right \rfloor}
\frac{a_{1}^{x-2j}a_{2}^{j}}{(x-2j)!j!}
Parameters
==========
a1: A Positive number greater than equal to 0.
a2: A Positive number greater than equal to 0.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Hermite, density, E, variance
>>> from sympy import Symbol
>>> a1 = Symbol("a1", positive=True)
>>> a2 = Symbol("a2", positive=True)
>>> x = Symbol("x")
>>> H = Hermite("H", a1=5, a2=4)
>>> density(H)(2)
33*exp(-9)/2
>>> E(H)
13
>>> variance(H)
21
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_distribution
"""
return rv(name, HermiteDistribution, a1, a2)
#-------------------------------------------------------------------------------
# Logarithmic distribution ------------------------------------------------------------
class LogarithmicDistribution(SingleDiscreteDistribution):
_argnames = ('p',)
set = S.Naturals
@staticmethod
def check(p):
_value_check((p > 0, p < 1), "p should be between 0 and 1")
def pdf(self, k):
p = self.p
return (-1) * p**k / (k * log(1 - p))
def _characteristic_function(self, t):
p = self.p
return log(1 - p * exp(I*t)) / log(1 - p)
def _moment_generating_function(self, t):
p = self.p
return log(1 - p * exp(t)) / log(1 - p)
def Logarithmic(name, p):
r"""
Create a discrete random variable with a Logarithmic distribution.
The density of the Logarithmic distribution is given by
.. math::
f(k) := \frac{-p^k}{k \ln{(1 - p)}}
Parameters
==========
p: A value between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Logarithmic, density, E, variance
>>> from sympy import Symbol, S
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = Logarithmic("x", p)
>>> density(X)(z)
-5**(-z)/(z*log(4/5))
>>> E(X)
-1/(-4*log(5) + 8*log(2))
>>> variance(X)
-1/((-4*log(5) + 8*log(2))*(-2*log(5) + 4*log(2))) + 1/(-64*log(2)*log(5) + 64*log(2)**2 + 16*log(5)**2) - 10/(-32*log(5) + 64*log(2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Logarithmic_distribution
.. [2] http://mathworld.wolfram.com/LogarithmicDistribution.html
"""
return rv(name, LogarithmicDistribution, p)
#-------------------------------------------------------------------------------
# Negative binomial distribution ------------------------------------------------------------
class NegativeBinomialDistribution(SingleDiscreteDistribution):
_argnames = ('r', 'p')
set = S.Naturals0
@staticmethod
def check(r, p):
_value_check(r > 0, 'r should be positive')
_value_check((p > 0, p < 1), 'p should be between 0 and 1')
def pdf(self, k):
r = self.r
p = self.p
return binomial(k + r - 1, k) * (1 - p)**r * p**k
def _characteristic_function(self, t):
r = self.r
p = self.p
return ((1 - p) / (1 - p * exp(I*t)))**r
def _moment_generating_function(self, t):
r = self.r
p = self.p
return ((1 - p) / (1 - p * exp(t)))**r
def NegativeBinomial(name, r, p):
r"""
Create a discrete random variable with a Negative Binomial distribution.
The density of the Negative Binomial distribution is given by
.. math::
f(k) := \binom{k + r - 1}{k} (1 - p)^r p^k
Parameters
==========
r: A positive value
p: A value between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import NegativeBinomial, density, E, variance
>>> from sympy import Symbol, S
>>> r = 5
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = NegativeBinomial("x", r, p)
>>> density(X)(z)
1024*5**(-z)*binomial(z + 4, z)/3125
>>> E(X)
5/4
>>> variance(X)
25/16
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_binomial_distribution
.. [2] http://mathworld.wolfram.com/NegativeBinomialDistribution.html
"""
return rv(name, NegativeBinomialDistribution, r, p)
#-------------------------------------------------------------------------------
# Poisson distribution ------------------------------------------------------------
class PoissonDistribution(SingleDiscreteDistribution):
_argnames = ('lamda',)
set = S.Naturals0
@staticmethod
def check(lamda):
_value_check(lamda > 0, "Lambda must be positive")
def pdf(self, k):
return self.lamda**k / factorial(k) * exp(-self.lamda)
def _characteristic_function(self, t):
return exp(self.lamda * (exp(I*t) - 1))
def _moment_generating_function(self, t):
return exp(self.lamda * (exp(t) - 1))
def Poisson(name, lamda):
r"""
Create a discrete random variable with a Poisson distribution.
The density of the Poisson distribution is given by
.. math::
f(k) := \frac{\lambda^{k} e^{- \lambda}}{k!}
Parameters
==========
lamda: Positive number, a rate
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Poisson, density, E, variance
>>> from sympy import Symbol, simplify
>>> rate = Symbol("lambda", positive=True)
>>> z = Symbol("z")
>>> X = Poisson("x", rate)
>>> density(X)(z)
lambda**z*exp(-lambda)/factorial(z)
>>> E(X)
lambda
>>> simplify(variance(X))
lambda
References
==========
.. [1] https://en.wikipedia.org/wiki/Poisson_distribution
.. [2] http://mathworld.wolfram.com/PoissonDistribution.html
"""
return rv(name, PoissonDistribution, lamda)
# -----------------------------------------------------------------------------
# Skellam distribution --------------------------------------------------------
class SkellamDistribution(SingleDiscreteDistribution):
_argnames = ('mu1', 'mu2')
set = S.Integers
@staticmethod
def check(mu1, mu2):
_value_check(mu1 >= 0, 'Parameter mu1 must be >= 0')
_value_check(mu2 >= 0, 'Parameter mu2 must be >= 0')
def pdf(self, k):
(mu1, mu2) = (self.mu1, self.mu2)
term1 = exp(-(mu1 + mu2)) * (mu1 / mu2) ** (k / 2)
term2 = besseli(k, 2 * sqrt(mu1 * mu2))
return term1 * term2
def _cdf(self, x):
raise NotImplementedError(
"Skellam doesn't have closed form for the CDF.")
def _characteristic_function(self, t):
(mu1, mu2) = (self.mu1, self.mu2)
return exp(-(mu1 + mu2) + mu1 * exp(I * t) + mu2 * exp(-I * t))
def _moment_generating_function(self, t):
(mu1, mu2) = (self.mu1, self.mu2)
return exp(-(mu1 + mu2) + mu1 * exp(t) + mu2 * exp(-t))
def Skellam(name, mu1, mu2):
r"""
Create a discrete random variable with a Skellam distribution.
The Skellam is the distribution of the difference N1 - N2
of two statistically independent random variables N1 and N2
each Poisson-distributed with respective expected values mu1 and mu2.
The density of the Skellam distribution is given by
.. math::
f(k) := e^{-(\mu_1+\mu_2)}(\frac{\mu_1}{\mu_2})^{k/2}I_k(2\sqrt{\mu_1\mu_2})
Parameters
==========
mu1: A non-negative value
mu2: A non-negative value
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Skellam, density, E, variance
>>> from sympy import Symbol, pprint
>>> z = Symbol("z", integer=True)
>>> mu1 = Symbol("mu1", positive=True)
>>> mu2 = Symbol("mu2", positive=True)
>>> X = Skellam("x", mu1, mu2)
>>> pprint(density(X)(z), use_unicode=False)
z
-
2
/mu1\ -mu1 - mu2 / _____ _____\
|---| *e *besseli\z, 2*\/ mu1 *\/ mu2 /
\mu2/
>>> E(X)
mu1 - mu2
>>> variance(X).expand()
mu1 + mu2
References
==========
.. [1] https://en.wikipedia.org/wiki/Skellam_distribution
"""
return rv(name, SkellamDistribution, mu1, mu2)
#-------------------------------------------------------------------------------
# Yule-Simon distribution ------------------------------------------------------------
class YuleSimonDistribution(SingleDiscreteDistribution):
_argnames = ('rho',)
set = S.Naturals
@staticmethod
def check(rho):
_value_check(rho > 0, 'rho should be positive')
def pdf(self, k):
rho = self.rho
return rho * beta(k, rho + 1)
def _cdf(self, x):
return Piecewise((1 - floor(x) * beta(floor(x), self.rho + 1), x >= 1), (0, True))
def _characteristic_function(self, t):
rho = self.rho
return rho * hyper((1, 1), (rho + 2,), exp(I*t)) * exp(I*t) / (rho + 1)
def _moment_generating_function(self, t):
rho = self.rho
return rho * hyper((1, 1), (rho + 2,), exp(t)) * exp(t) / (rho + 1)
def YuleSimon(name, rho):
r"""
Create a discrete random variable with a Yule-Simon distribution.
The density of the Yule-Simon distribution is given by
.. math::
f(k) := \rho B(k, \rho + 1)
Parameters
==========
rho: A positive value
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import YuleSimon, density, E, variance
>>> from sympy import Symbol, simplify
>>> p = 5
>>> z = Symbol("z")
>>> X = YuleSimon("x", p)
>>> density(X)(z)
5*beta(z, 6)
>>> simplify(E(X))
5/4
>>> simplify(variance(X))
25/48
References
==========
.. [1] https://en.wikipedia.org/wiki/Yule%E2%80%93Simon_distribution
"""
return rv(name, YuleSimonDistribution, rho)
#-------------------------------------------------------------------------------
# Zeta distribution ------------------------------------------------------------
class ZetaDistribution(SingleDiscreteDistribution):
_argnames = ('s',)
set = S.Naturals
@staticmethod
def check(s):
_value_check(s > 1, 's should be greater than 1')
def pdf(self, k):
s = self.s
return 1 / (k**s * zeta(s))
def _characteristic_function(self, t):
return polylog(self.s, exp(I*t)) / zeta(self.s)
def _moment_generating_function(self, t):
return polylog(self.s, exp(t)) / zeta(self.s)
def Zeta(name, s):
r"""
Create a discrete random variable with a Zeta distribution.
The density of the Zeta distribution is given by
.. math::
f(k) := \frac{1}{k^s \zeta{(s)}}
Parameters
==========
s: A value greater than 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Zeta, density, E, variance
>>> from sympy import Symbol
>>> s = 5
>>> z = Symbol("z")
>>> X = Zeta("x", s)
>>> density(X)(z)
1/(z**5*zeta(5))
>>> E(X)
pi**4/(90*zeta(5))
>>> variance(X)
-pi**8/(8100*zeta(5)**2) + zeta(3)/zeta(5)
References
==========
.. [1] https://en.wikipedia.org/wiki/Zeta_distribution
"""
return rv(name, ZetaDistribution, s)
|
41971eb174a0f92def43019a568ced895dbe2ad81a352efbf02011d3422574ee | """
Main Random Variables Module
Defines abstract random variable type.
Contains interfaces for probability space object (PSpace) as well as standard
operators, P, E, sample, density, where, quantile
See Also
========
sympy.stats.crv
sympy.stats.frv
sympy.stats.rv_interface
"""
from functools import singledispatch
from typing import Tuple as tTuple
from sympy import (Basic, S, Expr, Symbol, Tuple, And, Add, Eq, lambdify, Or,
Equality, Lambda, sympify, Dummy, Ne, KroneckerDelta,
DiracDelta, Mul, Indexed, MatrixSymbol, Function)
from sympy.core.relational import Relational
from sympy.core.sympify import _sympify
from sympy.sets.sets import FiniteSet, ProductSet, Intersection
from sympy.solvers.solveset import solveset
from sympy.external import import_module
from sympy.utilities.misc import filldedent
import warnings
x = Symbol('x')
@singledispatch
def is_random(x):
return False
@is_random.register(Basic)
def _(x):
atoms = x.free_symbols
return any([is_random(i) for i in atoms])
class RandomDomain(Basic):
"""
Represents a set of variables and the values which they can take
See Also
========
sympy.stats.crv.ContinuousDomain
sympy.stats.frv.FiniteDomain
"""
is_ProductDomain = False
is_Finite = False
is_Continuous = False
is_Discrete = False
def __new__(cls, symbols, *args):
symbols = FiniteSet(*symbols)
return Basic.__new__(cls, symbols, *args)
@property
def symbols(self):
return self.args[0]
@property
def set(self):
return self.args[1]
def __contains__(self, other):
raise NotImplementedError()
def compute_expectation(self, expr):
raise NotImplementedError()
class SingleDomain(RandomDomain):
"""
A single variable and its domain
See Also
========
sympy.stats.crv.SingleContinuousDomain
sympy.stats.frv.SingleFiniteDomain
"""
def __new__(cls, symbol, set):
assert symbol.is_Symbol
return Basic.__new__(cls, symbol, set)
@property
def symbol(self):
return self.args[0]
@property
def symbols(self):
return FiniteSet(self.symbol)
def __contains__(self, other):
if len(other) != 1:
return False
sym, val = tuple(other)[0]
return self.symbol == sym and val in self.set
class MatrixDomain(RandomDomain):
"""
A Random Matrix variable and its domain
"""
def __new__(cls, symbol, set):
symbol, set = _symbol_converter(symbol), _sympify(set)
return Basic.__new__(cls, symbol, set)
@property
def symbol(self):
return self.args[0]
@property
def symbols(self):
return FiniteSet(self.symbol)
class ConditionalDomain(RandomDomain):
"""
A RandomDomain with an attached condition
See Also
========
sympy.stats.crv.ConditionalContinuousDomain
sympy.stats.frv.ConditionalFiniteDomain
"""
def __new__(cls, fulldomain, condition):
condition = condition.xreplace({rs: rs.symbol
for rs in random_symbols(condition)})
return Basic.__new__(cls, fulldomain, condition)
@property
def symbols(self):
return self.fulldomain.symbols
@property
def fulldomain(self):
return self.args[0]
@property
def condition(self):
return self.args[1]
@property
def set(self):
raise NotImplementedError("Set of Conditional Domain not Implemented")
def as_boolean(self):
return And(self.fulldomain.as_boolean(), self.condition)
class PSpace(Basic):
"""
A Probability Space
Probability Spaces encode processes that equal different values
probabilistically. These underly Random Symbols which occur in SymPy
expressions and contain the mechanics to evaluate statistical statements.
See Also
========
sympy.stats.crv.ContinuousPSpace
sympy.stats.frv.FinitePSpace
"""
is_Finite = None # type: bool
is_Continuous = None # type: bool
is_Discrete = None # type: bool
is_real = None # type: bool
@property
def domain(self):
return self.args[0]
@property
def density(self):
return self.args[1]
@property
def values(self):
return frozenset(RandomSymbol(sym, self) for sym in self.symbols)
@property
def symbols(self):
return self.domain.symbols
def where(self, condition):
raise NotImplementedError()
def compute_density(self, expr):
raise NotImplementedError()
def sample(self):
raise NotImplementedError()
def probability(self, condition):
raise NotImplementedError()
def compute_expectation(self, expr):
raise NotImplementedError()
class SinglePSpace(PSpace):
"""
Represents the probabilities of a set of random events that can be
attributed to a single variable/symbol.
"""
def __new__(cls, s, distribution):
s = _symbol_converter(s)
return Basic.__new__(cls, s, distribution)
@property
def value(self):
return RandomSymbol(self.symbol, self)
@property
def symbol(self):
return self.args[0]
@property
def distribution(self):
return self.args[1]
@property
def pdf(self):
return self.distribution.pdf(self.symbol)
class RandomSymbol(Expr):
"""
Random Symbols represent ProbabilitySpaces in SymPy Expressions
In principle they can take on any value that their symbol can take on
within the associated PSpace with probability determined by the PSpace
Density.
Random Symbols contain pspace and symbol properties.
The pspace property points to the represented Probability Space
The symbol is a standard SymPy Symbol that is used in that probability space
for example in defining a density.
You can form normal SymPy expressions using RandomSymbols and operate on
those expressions with the Functions
E - Expectation of a random expression
P - Probability of a condition
density - Probability Density of an expression
given - A new random expression (with new random symbols) given a condition
An object of the RandomSymbol type should almost never be created by the
user. They tend to be created instead by the PSpace class's value method.
Traditionally a user doesn't even do this but instead calls one of the
convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
"""
def __new__(cls, symbol, pspace=None):
from sympy.stats.joint_rv import JointRandomSymbol
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
symbol = _symbol_converter(symbol)
if not isinstance(pspace, PSpace):
raise TypeError("pspace variable should be of type PSpace")
if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
cls = RandomSymbol
return Basic.__new__(cls, symbol, pspace)
is_finite = True
is_symbol = True
is_Atom = True
_diff_wrt = True
pspace = property(lambda self: self.args[1])
symbol = property(lambda self: self.args[0])
name = property(lambda self: self.symbol.name)
def _eval_is_positive(self):
return self.symbol.is_positive
def _eval_is_integer(self):
return self.symbol.is_integer
def _eval_is_real(self):
return self.symbol.is_real or self.pspace.is_real
@property
def is_commutative(self):
return self.symbol.is_commutative
@property
def free_symbols(self):
return {self}
class RandomIndexedSymbol(RandomSymbol):
def __new__(cls, idx_obj, pspace=None):
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
if not isinstance(idx_obj, (Indexed, Function)):
raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj))
return Basic.__new__(cls, idx_obj, pspace)
symbol = property(lambda self: self.args[0])
name = property(lambda self: str(self.args[0]))
@property
def key(self):
if isinstance(self.symbol, Indexed):
return self.symbol.args[1]
elif isinstance(self.symbol, Function):
return self.symbol.args[0]
@property
def free_symbols(self):
if self.key.free_symbols:
free_syms = self.key.free_symbols
free_syms.add(self)
return free_syms
return {self}
@property
def pspace(self):
return self.args[1]
class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore
def __new__(cls, symbol, n, m, pspace=None):
n, m = _sympify(n), _sympify(m)
symbol = _symbol_converter(symbol)
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
return Basic.__new__(cls, symbol, n, m, pspace)
symbol = property(lambda self: self.args[0])
pspace = property(lambda self: self.args[3])
class ProductPSpace(PSpace):
"""
Abstract class for representing probability spaces with multiple random
variables.
See Also
========
sympy.stats.rv.IndependentProductPSpace
sympy.stats.joint_rv.JointPSpace
"""
pass
class IndependentProductPSpace(ProductPSpace):
"""
A probability space resulting from the merger of two independent probability
spaces.
Often created using the function, pspace
"""
def __new__(cls, *spaces):
rs_space_dict = {}
for space in spaces:
for value in space.values:
rs_space_dict[value] = space
symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])
# Overlapping symbols
from sympy.stats.joint_rv import MarginalDistribution
from sympy.stats.compound_rv import CompoundDistribution
if len(symbols) < sum(len(space.symbols) for space in spaces if not
isinstance(space.distribution, (
CompoundDistribution, MarginalDistribution))):
raise ValueError("Overlapping Random Variables")
if all(space.is_Finite for space in spaces):
from sympy.stats.frv import ProductFinitePSpace
cls = ProductFinitePSpace
obj = Basic.__new__(cls, *FiniteSet(*spaces))
return obj
@property
def pdf(self):
p = Mul(*[space.pdf for space in self.spaces])
return p.subs({rv: rv.symbol for rv in self.values})
@property
def rs_space_dict(self):
d = {}
for space in self.spaces:
for value in space.values:
d[value] = space
return d
@property
def symbols(self):
return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
@property
def spaces(self):
return FiniteSet(*self.args)
@property
def values(self):
return sumsets(space.values for space in self.spaces)
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
rvs = rvs or self.values
rvs = frozenset(rvs)
for space in self.spaces:
expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs)
if evaluate and hasattr(expr, 'doit'):
return expr.doit(**kwargs)
return expr
@property
def domain(self):
return ProductDomain(*[space.domain for space in self.spaces])
@property
def density(self):
raise NotImplementedError("Density not available for ProductSpaces")
def sample(self, size=(), library='scipy', seed=None):
return {k: v for space in self.spaces
for k, v in space.sample(size=size, library=library, seed=seed).items()}
def probability(self, condition, **kwargs):
cond_inv = False
if isinstance(condition, Ne):
condition = Eq(condition.args[0], condition.args[1])
cond_inv = True
elif isinstance(condition, And): # they are independent
return Mul(*[self.probability(arg) for arg in condition.args])
elif isinstance(condition, Or): # they are independent
return Add(*[self.probability(arg) for arg in condition.args])
expr = condition.lhs - condition.rhs
rvs = random_symbols(expr)
dens = self.compute_density(expr)
if any([pspace(rv).is_Continuous for rv in rvs]):
from sympy.stats.crv import SingleContinuousPSpace
from sympy.stats.crv_types import ContinuousDistributionHandmade
if expr in self.values:
# Marginalize all other random symbols out of the density
randomsymbols = tuple(set(self.values) - frozenset([expr]))
symbols = tuple(rs.symbol for rs in randomsymbols)
pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
return Lambda(expr.symbol, pdf)
dens = ContinuousDistributionHandmade(dens)
z = Dummy('z', real=True)
space = SingleContinuousPSpace(z, dens)
result = space.probability(condition.__class__(space.value, 0))
else:
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import DiscreteDistributionHandmade
dens = DiscreteDistributionHandmade(dens)
z = Dummy('z', integer=True)
space = SingleDiscretePSpace(z, dens)
result = space.probability(condition.__class__(space.value, 0))
return result if not cond_inv else S.One - result
def compute_density(self, expr, **kwargs):
rvs = random_symbols(expr)
if any(pspace(rv).is_Continuous for rv in rvs):
z = Dummy('z', real=True)
expr = self.compute_expectation(DiracDelta(expr - z),
**kwargs)
else:
z = Dummy('z', integer=True)
expr = self.compute_expectation(KroneckerDelta(expr, z),
**kwargs)
return Lambda(z, expr)
def compute_cdf(self, expr, **kwargs):
raise ValueError("CDF not well defined on multivariate expressions")
def conditional_space(self, condition, normalize=True, **kwargs):
rvs = random_symbols(condition)
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
if any([pspace(rv).is_Continuous for rv in rvs]):
from sympy.stats.crv import (ConditionalContinuousDomain,
ContinuousPSpace)
space = ContinuousPSpace
domain = ConditionalContinuousDomain(self.domain, condition)
elif any([pspace(rv).is_Discrete for rv in rvs]):
from sympy.stats.drv import (ConditionalDiscreteDomain,
DiscretePSpace)
space = DiscretePSpace
domain = ConditionalDiscreteDomain(self.domain, condition)
elif all([pspace(rv).is_Finite for rv in rvs]):
from sympy.stats.frv import FinitePSpace
return FinitePSpace.conditional_space(self, condition)
if normalize:
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
norm = domain.compute_expectation(self.pdf, **kwargs)
pdf = self.pdf / norm.xreplace(replacement)
# XXX: Converting symbols from set to tuple. The order matters to
# Lambda though so we shouldn't be starting with a set here...
density = Lambda(tuple(domain.symbols), pdf)
return space(domain, density)
class ProductDomain(RandomDomain):
"""
A domain resulting from the merger of two independent domains
See Also
========
sympy.stats.crv.ProductContinuousDomain
sympy.stats.frv.ProductFiniteDomain
"""
is_ProductDomain = True
def __new__(cls, *domains):
# Flatten any product of products
domains2 = []
for domain in domains:
if not domain.is_ProductDomain:
domains2.append(domain)
else:
domains2.extend(domain.domains)
domains2 = FiniteSet(*domains2)
if all(domain.is_Finite for domain in domains2):
from sympy.stats.frv import ProductFiniteDomain
cls = ProductFiniteDomain
if all(domain.is_Continuous for domain in domains2):
from sympy.stats.crv import ProductContinuousDomain
cls = ProductContinuousDomain
if all(domain.is_Discrete for domain in domains2):
from sympy.stats.drv import ProductDiscreteDomain
cls = ProductDiscreteDomain
return Basic.__new__(cls, *domains2)
@property
def sym_domain_dict(self):
return {symbol: domain for domain in self.domains
for symbol in domain.symbols}
@property
def symbols(self):
return FiniteSet(*[sym for domain in self.domains
for sym in domain.symbols])
@property
def domains(self):
return self.args
@property
def set(self):
return ProductSet(*(domain.set for domain in self.domains))
def __contains__(self, other):
# Split event into each subdomain
for domain in self.domains:
# Collect the parts of this event which associate to this domain
elem = frozenset([item for item in other
if sympify(domain.symbols.contains(item[0]))
is S.true])
# Test this sub-event
if elem not in domain:
return False
# All subevents passed
return True
def as_boolean(self):
return And(*[domain.as_boolean() for domain in self.domains])
def random_symbols(expr):
"""
Returns all RandomSymbols within a SymPy Expression.
"""
atoms = getattr(expr, 'atoms', None)
if atoms is not None:
comp = lambda rv: rv.symbol.name
l = list(atoms(RandomSymbol))
return sorted(l, key=comp)
else:
return []
def pspace(expr):
"""
Returns the underlying Probability Space of a random expression.
For internal use.
Examples
========
>>> from sympy.stats import pspace, Normal
>>> X = Normal('X', 0, 1)
>>> pspace(2*X + 1) == X.pspace
True
"""
expr = sympify(expr)
if isinstance(expr, RandomSymbol) and expr.pspace is not None:
return expr.pspace
if expr.has(RandomMatrixSymbol):
rm = list(expr.atoms(RandomMatrixSymbol))[0]
return rm.pspace
rvs = random_symbols(expr)
if not rvs:
raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
# If only one space present
if all(rv.pspace == rvs[0].pspace for rv in rvs):
return rvs[0].pspace
from sympy.stats.compound_rv import CompoundPSpace
from sympy.stats.stochastic_process import StochasticPSpace
for rv in rvs:
if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)):
return rv.pspace
# Otherwise make a product space
return IndependentProductPSpace(*[rv.pspace for rv in rvs])
def sumsets(sets):
"""
Union of sets
"""
return frozenset().union(*sets)
def rs_swap(a, b):
"""
Build a dictionary to swap RandomSymbols based on their underlying symbol.
i.e.
if ``X = ('x', pspace1)``
and ``Y = ('x', pspace2)``
then ``X`` and ``Y`` match and the key, value pair
``{X:Y}`` will appear in the result
Inputs: collections a and b of random variables which share common symbols
Output: dict mapping RVs in a to RVs in b
"""
d = {}
for rsa in a:
d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0]
return d
def given(expr, condition=None, **kwargs):
r""" Conditional Random Expression
From a random expression and a condition on that expression creates a new
probability space from the condition and returns the same expression on that
conditional probability space.
Examples
========
>>> from sympy.stats import given, density, Die
>>> X = Die('X', 6)
>>> Y = given(X, X > 3)
>>> density(Y).dict
{4: 1/3, 5: 1/3, 6: 1/3}
Following convention, if the condition is a random symbol then that symbol
is considered fixed.
>>> from sympy.stats import Normal
>>> from sympy import pprint
>>> from sympy.abc import z
>>> X = Normal('X', 0, 1)
>>> Y = Normal('Y', 0, 1)
>>> pprint(density(X + Y, Y)(z), use_unicode=False)
2
-(-Y + z)
-----------
___ 2
\/ 2 *e
------------------
____
2*\/ pi
"""
if not is_random(condition) or pspace_independent(expr, condition):
return expr
if isinstance(condition, RandomSymbol):
condition = Eq(condition, condition.symbol)
condsymbols = random_symbols(condition)
if (isinstance(condition, Equality) and len(condsymbols) == 1 and
not isinstance(pspace(expr).domain, ConditionalDomain)):
rv = tuple(condsymbols)[0]
results = solveset(condition, rv)
if isinstance(results, Intersection) and S.Reals in results.args:
results = list(results.args[1])
sums = 0
for res in results:
temp = expr.subs(rv, res)
if temp == True:
return True
if temp != False:
# XXX: This seems nonsensical but preserves existing behaviour
# after the change that Relational is no longer a subclass of
# Expr. Here expr is sometimes Relational and sometimes Expr
# but we are trying to add them with +=. This needs to be
# fixed somehow.
if sums == 0 and isinstance(expr, Relational):
sums = expr.subs(rv, res)
else:
sums += expr.subs(rv, res)
if sums == 0:
return False
return sums
# Get full probability space of both the expression and the condition
fullspace = pspace(Tuple(expr, condition))
# Build new space given the condition
space = fullspace.conditional_space(condition, **kwargs)
# Dictionary to swap out RandomSymbols in expr with new RandomSymbols
# That point to the new conditional space
swapdict = rs_swap(fullspace.values, space.values)
# Swap random variables in the expression
expr = expr.xreplace(swapdict)
return expr
def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
"""
Returns the expected value of a random expression
Parameters
==========
expr : Expr containing RandomSymbols
The expression of which you want to compute the expectation value
given : Expr containing RandomSymbols
A conditional expression. E(X, X>0) is expectation of X given X > 0
numsamples : int
Enables sampling and approximates the expectation with this many samples
evalf : Bool (defaults to True)
If sampling return a number rather than a complex expression
evaluate : Bool (defaults to True)
In case of continuous systems return unevaluated integral
Examples
========
>>> from sympy.stats import E, Die
>>> X = Die('X', 6)
>>> E(X)
7/2
>>> E(2*X + 1)
8
>>> E(X, X > 3) # Expectation of X given that it is above 3
5
"""
if not is_random(expr): # expr isn't random?
return expr
kwargs['numsamples'] = numsamples
from sympy.stats.symbolic_probability import Expectation
if evaluate:
return Expectation(expr, condition).doit(**kwargs)
return Expectation(expr, condition)
def probability(condition, given_condition=None, numsamples=None,
evaluate=True, **kwargs):
"""
Probability that a condition is true, optionally given a second condition
Parameters
==========
condition : Combination of Relationals containing RandomSymbols
The condition of which you want to compute the probability
given_condition : Combination of Relationals containing RandomSymbols
A conditional expression. P(X > 1, X > 0) is expectation of X > 1
given X > 0
numsamples : int
Enables sampling and approximates the probability with this many samples
evaluate : Bool (defaults to True)
In case of continuous systems return unevaluated integral
Examples
========
>>> from sympy.stats import P, Die
>>> from sympy import Eq
>>> X, Y = Die('X', 6), Die('Y', 6)
>>> P(X > 3)
1/2
>>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
1/4
>>> P(X > Y)
5/12
"""
kwargs['numsamples'] = numsamples
from sympy.stats.symbolic_probability import Probability
if evaluate:
return Probability(condition, given_condition).doit(**kwargs)
### TODO: Remove the user warnings in the future releases
message = ("Since version 1.7, using `evaluate=False` returns `Probability` "
"object. If you want unevaluated Integral/Sum use "
"`P(condition, given_condition, evaluate=False).rewrite(Integral)`")
warnings.warn(filldedent(message))
return Probability(condition, given_condition)
class Density(Basic):
expr = property(lambda self: self.args[0])
@property
def condition(self):
if len(self.args) > 1:
return self.args[1]
else:
return None
def doit(self, evaluate=True, **kwargs):
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.joint_rv import JointPSpace
from sympy.stats.matrix_distributions import MatrixPSpace
from sympy.stats.compound_rv import CompoundPSpace
from sympy.stats.frv import SingleFiniteDistribution
expr, condition = self.expr, self.condition
if isinstance(expr, SingleFiniteDistribution):
return expr.dict
if condition is not None:
# Recompute on new conditional expr
expr = given(expr, condition, **kwargs)
if not random_symbols(expr):
return Lambda(x, DiracDelta(x - expr))
if isinstance(expr, RandomSymbol):
if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \
hasattr(expr.pspace, 'distribution'):
return expr.pspace.distribution
elif isinstance(expr.pspace, RandomMatrixPSpace):
return expr.pspace.model
if isinstance(pspace(expr), CompoundPSpace):
kwargs['compound_evaluate'] = evaluate
result = pspace(expr).compute_density(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
"""
Probability density of a random expression, optionally given a second
condition.
This density will take on different forms for different types of
probability spaces. Discrete variables produce Dicts. Continuous
variables produce Lambdas.
Parameters
==========
expr : Expr containing RandomSymbols
The expression of which you want to compute the density value
condition : Relational containing RandomSymbols
A conditional expression. density(X > 1, X > 0) is density of X > 1
given X > 0
numsamples : int
Enables sampling and approximates the density with this many samples
Examples
========
>>> from sympy.stats import density, Die, Normal
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> D = Die('D', 6)
>>> X = Normal(x, 0, 1)
>>> density(D).dict
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> density(2*D).dict
{2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
>>> density(X)(x)
sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
"""
if numsamples:
return sampling_density(expr, condition, numsamples=numsamples,
**kwargs)
return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
def cdf(expr, condition=None, evaluate=True, **kwargs):
"""
Cumulative Distribution Function of a random expression.
optionally given a second condition
This density will take on different forms for different types of
probability spaces.
Discrete variables produce Dicts.
Continuous variables produce Lambdas.
Examples
========
>>> from sympy.stats import density, Die, Normal, cdf
>>> D = Die('D', 6)
>>> X = Normal('X', 0, 1)
>>> density(D).dict
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> cdf(D)
{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
>>> cdf(3*D, D > 2)
{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
>>> cdf(X)
Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
"""
if condition is not None: # If there is a condition
# Recompute on new conditional expr
return cdf(given(expr, condition, **kwargs), **kwargs)
# Otherwise pass work off to the ProbabilitySpace
result = pspace(expr).compute_cdf(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def characteristic_function(expr, condition=None, evaluate=True, **kwargs):
"""
Characteristic function of a random expression, optionally given a second condition
Returns a Lambda
Examples
========
>>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function
>>> X = Normal('X', 0, 1)
>>> characteristic_function(X)
Lambda(_t, exp(-_t**2/2))
>>> Y = DiscreteUniform('Y', [1, 2, 7])
>>> characteristic_function(Y)
Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)
>>> Z = Poisson('Z', 2)
>>> characteristic_function(Z)
Lambda(_t, exp(2*exp(_t*I) - 2))
"""
if condition is not None:
return characteristic_function(given(expr, condition, **kwargs), **kwargs)
result = pspace(expr).compute_characteristic_function(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def moment_generating_function(expr, condition=None, evaluate=True, **kwargs):
if condition is not None:
return moment_generating_function(given(expr, condition, **kwargs), **kwargs)
result = pspace(expr).compute_moment_generating_function(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def where(condition, given_condition=None, **kwargs):
"""
Returns the domain where a condition is True.
Examples
========
>>> from sympy.stats import where, Die, Normal
>>> from sympy import And
>>> D1, D2 = Die('a', 6), Die('b', 6)
>>> a, b = D1.symbol, D2.symbol
>>> X = Normal('x', 0, 1)
>>> where(X**2<1)
Domain: (-1 < x) & (x < 1)
>>> where(X**2<1).set
Interval.open(-1, 1)
>>> where(And(D1<=D2 , D2<3))
Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
"""
if given_condition is not None: # If there is a condition
# Recompute on new conditional expr
return where(given(condition, given_condition, **kwargs), **kwargs)
# Otherwise pass work off to the ProbabilitySpace
return pspace(condition).where(condition, **kwargs)
def sample(expr, condition=None, size=(), library='scipy',
numsamples=1, seed=None, **kwargs):
"""
A realization of the random expression
Parameters
==========
expr : Expression of random variables
Expression from which sample is extracted
condition : Expr containing RandomSymbols
A conditional expression
size : int, tuple
Represents size of each sample in numsamples
library : str
- 'scipy' : Sample using scipy
- 'numpy' : Sample using numpy
- 'pymc3' : Sample using PyMC3
Choose any of the available options to sample from as string,
by default is 'scipy'
numsamples : int
Number of samples, each with size as ``size``
seed :
An object to be used as seed by the given external library for sampling `expr`.
Following is the list of possible types of object for the supported libraries,
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
- 'pymc3': int
Optional, by default None, in which case seed settings
related to the given library will be used.
No modifications to environment's global seed settings
are done by this argument.
Examples
========
>>> from sympy.stats import Die, sample, Normal, Geometric
>>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
>>> die_roll = sample(X + Y + Z) # doctest: +SKIP
>>> next(die_roll) # doctest: +SKIP
6
>>> N = Normal('N', 3, 4) # Continuous Random Variable
>>> samp = next(sample(N)) # doctest: +SKIP
>>> samp in N.pspace.domain.set # doctest: +SKIP
True
>>> samp = next(sample(N, N>0)) # doctest: +SKIP
>>> samp > 0 # doctest: +SKIP
True
>>> samp_list = next(sample(N, size=4)) # doctest: +SKIP
>>> [sam in N.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True, True]
>>> G = Geometric('G', 0.5) # Discrete Random Variable
>>> samp_list = next(sample(G, size=3)) # doctest: +SKIP
>>> samp_list # doctest: +SKIP
array([10, 4, 1])
>>> [sam in G.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True]
>>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
>>> samp_list = next(sample(MN, size=4)) # doctest: +SKIP
>>> samp_list # doctest: +SKIP
array([[4.22564264, 3.23364418],
[3.41002011, 4.60090908],
[3.76151866, 4.77617143],
[4.71440865, 2.65714157]])
>>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True, True]
Returns
=======
sample: iterator object
iterator object containing the sample/samples of given expr
"""
### TODO: Remove the user warnings in the future releases
message = ("The return type of sample has been changed to return an "
"iterator object since version 1.7. For more information see "
"https://github.com/sympy/sympy/issues/19061")
warnings.warn(filldedent(message))
return sample_iter(expr, condition, size=size, library=library,
numsamples=numsamples, seed=seed)
def quantile(expr, evaluate=True, **kwargs):
r"""
Return the :math:`p^{th}` order quantile of a probability distribution.
Quantile is defined as the value at which the probability of the random
variable is less than or equal to the given probability.
..math::
Q(p) = inf{x \in (-\infty, \infty) such that p <= F(x)}
Examples
========
>>> from sympy.stats import quantile, Die, Exponential
>>> from sympy import Symbol, pprint
>>> p = Symbol("p")
>>> l = Symbol("lambda", positive=True)
>>> X = Exponential("x", l)
>>> quantile(X)(p)
-log(1 - p)/lambda
>>> D = Die("d", 6)
>>> pprint(quantile(D)(p), use_unicode=False)
/nan for Or(p > 1, p < 0)
|
| 1 for p <= 1/6
|
| 2 for p <= 1/3
|
< 3 for p <= 1/2
|
| 4 for p <= 2/3
|
| 5 for p <= 5/6
|
\ 6 for p <= 1
"""
result = pspace(expr).compute_quantile(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def sample_iter(expr, condition=None, size=(), library='scipy',
numsamples=S.Infinity, seed=None, **kwargs):
"""
Returns an iterator of realizations from the expression given a condition
Parameters
==========
expr: Expr
Random expression to be realized
condition: Expr, optional
A conditional expression
size : int, tuple
Represents size of each sample in numsamples
numsamples: integer, optional
Length of the iterator (defaults to infinity)
seed :
An object to be used as seed by the given external library for sampling `expr`.
Following is the list of possible types of object for the supported libraries,
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
- 'pymc3': int
Optional, by default None, in which case seed settings
related to the given library will be used.
No modifications to environment's global seed settings
are done by this argument.
Examples
========
>>> from sympy.stats import Normal, sample_iter
>>> X = Normal('X', 0, 1)
>>> expr = X*X + 3
>>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
>>> list(iterator) # doctest: +SKIP
[12, 4, 7]
Returns
=======
sample_iter: iterator object
iterator object containing the sample/samples of given expr
See Also
========
sample
sampling_P
sampling_E
"""
from sympy.stats.joint_rv import JointRandomSymbol
if not import_module(library):
raise ValueError("Failed to import %s" % library)
if condition is not None:
ps = pspace(Tuple(expr, condition))
else:
ps = pspace(expr)
rvs = list(ps.values)
if isinstance(expr, JointRandomSymbol):
expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)})
else:
sub = {}
for arg in expr.args:
if isinstance(arg, JointRandomSymbol):
sub[arg] = RandomSymbol(arg.symbol, arg.pspace)
expr = expr.subs(sub)
def fn_subs(*args):
return expr.subs({rv: arg for rv, arg in zip(rvs, args)})
def given_fn_subs(*args):
if condition is not None:
return condition.subs({rv: arg for rv, arg in zip(rvs, args)})
return False
if library == 'pymc3':
# Currently unable to lambdify in pymc3
# TODO : Remove 'pymc3' when lambdify accepts 'pymc3' as module
fn = lambdify(rvs, expr, **kwargs)
else:
fn = lambdify(rvs, expr, modules=library, **kwargs)
if condition is not None:
given_fn = lambdify(rvs, condition, **kwargs)
def return_generator_infinite():
count = 0
np = import_module('numpy')
if np:
rand_state = np.random.default_rng(seed=seed)
else:
rand_state = None
while count < numsamples:
d = ps.sample(size=size, library=library, seed=rand_state) # a dictionary that maps RVs to values
args = [d[rv] for rv in rvs]
if condition is not None: # Check that these values satisfy the condition
# TODO: Replace the try-except block with only given_fn(*args)
# once lambdify works with unevaluated SymPy objects.
try:
gd = given_fn(*args)
except (NameError, TypeError):
gd = given_fn_subs(*args)
if gd != True and gd != False:
raise ValueError(
"Conditions must not contain free symbols")
if not gd: # If the values don't satisfy then try again
continue
yield fn(*args)
count += 1
def return_generator_finite():
faulty = True
while faulty:
d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size),
library=library, seed=seed) # a dictionary that maps RVs to values
faulty = False
count = 0
while count < numsamples and not faulty:
args = [d[rv][count] for rv in rvs]
if condition is not None: # Check that these values satisfy the condition
# TODO: Replace the try-except block with only given_fn(*args)
# once lambdify works with unevaluated SymPy objects.
try:
gd = given_fn(*args)
except (NameError, TypeError):
gd = given_fn_subs(*args)
if gd != True and gd != False:
raise ValueError(
"Conditions must not contain free symbols")
if not gd: # If the values don't satisfy then try again
faulty = True
count += 1
count = 0
while count < numsamples:
args = [d[rv][count] for rv in rvs]
# TODO: Replace the try-except block with only fn(*args)
# once lambdify works with unevaluated SymPy objects.
try:
yield fn(*args)
except (NameError, TypeError):
yield fn_subs(*args)
count += 1
if numsamples is S.Infinity:
return return_generator_infinite()
return return_generator_finite()
def sample_iter_lambdify(expr, condition=None, size=(),
numsamples=S.Infinity, seed=None, **kwargs):
return sample_iter(expr, condition=condition, size=size,
numsamples=numsamples, seed=seed, **kwargs)
def sample_iter_subs(expr, condition=None, size=(),
numsamples=S.Infinity, seed=None, **kwargs):
return sample_iter(expr, condition=condition, size=size,
numsamples=numsamples, seed=seed, **kwargs)
def sampling_P(condition, given_condition=None, library='scipy', numsamples=1,
evalf=True, seed=None, **kwargs):
"""
Sampling version of P
See Also
========
P
sampling_E
sampling_density
"""
count_true = 0
count_false = 0
samples = sample_iter(condition, given_condition, library=library,
numsamples=numsamples, seed=seed, **kwargs)
for sample in samples:
if sample:
count_true += 1
else:
count_false += 1
result = S(count_true) / numsamples
if evalf:
return result.evalf()
else:
return result
def sampling_E(expr, given_condition=None, library='scipy', numsamples=1,
evalf=True, seed=None, **kwargs):
"""
Sampling version of E
See Also
========
P
sampling_P
sampling_density
"""
samples = list(sample_iter(expr, given_condition, library=library,
numsamples=numsamples, seed=seed, **kwargs))
result = Add(*[samp for samp in samples]) / numsamples
if evalf:
return result.evalf()
else:
return result
def sampling_density(expr, given_condition=None, library='scipy',
numsamples=1, seed=None, **kwargs):
"""
Sampling version of density
See Also
========
density
sampling_P
sampling_E
"""
results = {}
for result in sample_iter(expr, given_condition, library=library,
numsamples=numsamples, seed=seed, **kwargs):
results[result] = results.get(result, 0) + 1
return results
def dependent(a, b):
"""
Dependence of two random expressions
Two expressions are independent if knowledge of one does not change
computations on the other.
Examples
========
>>> from sympy.stats import Normal, dependent, given
>>> from sympy import Tuple, Eq
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
>>> dependent(X, Y)
False
>>> dependent(2*X + Y, -Y)
True
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
>>> dependent(X, Y)
True
See Also
========
independent
"""
if pspace_independent(a, b):
return False
z = Symbol('z', real=True)
# Dependent if density is unchanged when one is given information about
# the other
return (density(a, Eq(b, z)) != density(a) or
density(b, Eq(a, z)) != density(b))
def independent(a, b):
"""
Independence of two random expressions
Two expressions are independent if knowledge of one does not change
computations on the other.
Examples
========
>>> from sympy.stats import Normal, independent, given
>>> from sympy import Tuple, Eq
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
>>> independent(X, Y)
True
>>> independent(2*X + Y, -Y)
False
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
>>> independent(X, Y)
False
See Also
========
dependent
"""
return not dependent(a, b)
def pspace_independent(a, b):
"""
Tests for independence between a and b by checking if their PSpaces have
overlapping symbols. This is a sufficient but not necessary condition for
independence and is intended to be used internally.
Notes
=====
pspace_independent(a, b) implies independent(a, b)
independent(a, b) does not imply pspace_independent(a, b)
"""
a_symbols = set(pspace(b).symbols)
b_symbols = set(pspace(a).symbols)
if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0:
return False
if len(a_symbols.intersection(b_symbols)) == 0:
return True
return None
def rv_subs(expr, symbols=None):
"""
Given a random expression replace all random variables with their symbols.
If symbols keyword is given restrict the swap to only the symbols listed.
"""
if symbols is None:
symbols = random_symbols(expr)
if not symbols:
return expr
swapdict = {rv: rv.symbol for rv in symbols}
return expr.subs(swapdict)
class NamedArgsMixin:
_argnames = () # type: tTuple[str, ...]
def __getattr__(self, attr):
try:
return self.args[self._argnames.index(attr)]
except ValueError:
raise AttributeError("'%s' object has no attribute '%s'" % (
type(self).__name__, attr))
class Distribution(Basic):
def sample(self, size=(), library='scipy', seed=None):
""" A random realization from the distribution """
module = import_module(library)
if library in {'scipy', 'numpy', 'pymc3'} and module is None:
raise ValueError("Failed to import %s" % library)
if library == 'scipy':
# scipy does not require map as it can handle using custom distributions.
# However, we will still use a map where we can.
# TODO: do this for drv.py and frv.py if necessary.
# TODO: add more distributions here if there are more
# See links below referring to sections beginning with "A common parametrization..."
# I will remove all these comments if everything is ok.
from sympy.stats.sampling.sample_scipy import do_sample_scipy
samps = do_sample_scipy(self, size, seed)
elif library == 'numpy':
from sympy.stats.sampling.sample_numpy import do_sample_numpy
import numpy
if seed is None or isinstance(seed, int):
rand_state = numpy.random.default_rng(seed=seed)
else:
rand_state = seed
samps = do_sample_numpy(self, size, rand_state)
elif library == 'pymc3':
from sympy.stats.sampling.sample_pymc3 import do_sample_pymc3
import pymc3
with pymc3.Model():
if do_sample_pymc3(self):
samps = pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X']
else:
samps = None
else:
raise NotImplementedError("Sampling from %s is not supported yet."
% str(library))
if samps is not None:
return samps
raise NotImplementedError(
"Sampling for %s is not currently implemented from %s"
% (self, library))
def _value_check(condition, message):
"""
Raise a ValueError with message if condition is False, else
return True if all conditions were True, else False.
Examples
========
>>> from sympy.stats.rv import _value_check
>>> from sympy.abc import a, b, c
>>> from sympy import And, Dummy
>>> _value_check(2 < 3, '')
True
Here, the condition is not False, but it doesn't evaluate to True
so False is returned (but no error is raised). So checking if the
return value is True or False will tell you if all conditions were
evaluated.
>>> _value_check(a < b, '')
False
In this case the condition is False so an error is raised:
>>> r = Dummy(real=True)
>>> _value_check(r < r - 1, 'condition is not true')
Traceback (most recent call last):
...
ValueError: condition is not true
If no condition of many conditions must be False, they can be
checked by passing them as an iterable:
>>> _value_check((a < 0, b < 0, c < 0), '')
False
The iterable can be a generator, too:
>>> _value_check((i < 0 for i in (a, b, c)), '')
False
The following are equivalent to the above but do not pass
an iterable:
>>> all(_value_check(i < 0, '') for i in (a, b, c))
False
>>> _value_check(And(a < 0, b < 0, c < 0), '')
False
"""
from sympy.core.compatibility import iterable
from sympy.core.logic import fuzzy_and
if not iterable(condition):
condition = [condition]
truth = fuzzy_and(condition)
if truth == False:
raise ValueError(message)
return truth == True
def _symbol_converter(sym):
"""
Casts the parameter to Symbol if it is 'str'
otherwise no operation is performed on it.
Parameters
==========
sym
The parameter to be converted.
Returns
=======
Symbol
the parameter converted to Symbol.
Raises
======
TypeError
If the parameter is not an instance of both str and
Symbol.
Examples
========
>>> from sympy import Symbol
>>> from sympy.stats.rv import _symbol_converter
>>> s = _symbol_converter('s')
>>> isinstance(s, Symbol)
True
>>> _symbol_converter(1)
Traceback (most recent call last):
...
TypeError: 1 is neither a Symbol nor a string
>>> r = Symbol('r')
>>> isinstance(r, Symbol)
True
"""
if isinstance(sym, str):
sym = Symbol(sym)
if not isinstance(sym, Symbol):
raise TypeError("%s is neither a Symbol nor a string"%(sym))
return sym
def sample_stochastic_process(process):
"""
This function is used to sample from stochastic process.
Parameters
==========
process: StochasticProcess
Process used to extract the samples. It must be an instance of
StochasticProcess
Examples
========
>>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
>>> from sympy import Matrix
>>> 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)
>>> next(sample_stochastic_process(Y)) in Y.state_space # doctest: +SKIP
True
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
0
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
2
Returns
=======
sample: iterator object
iterator object containing the sample of given process
"""
from sympy.stats.stochastic_process_types import StochasticProcess
if not isinstance(process, StochasticProcess):
raise ValueError("Process must be an instance of Stochastic Process")
return process.sample()
|
d6f132bfd5ed86f4aa5e69bd8e00f867a4d6ebf0001d486fbfddae0b609cc12a | from sympy import (Basic, sympify, symbols, Dummy, Lambda, summation,
Piecewise, S, cacheit, Sum, exp, I, Ne, Eq, poly,
series, factorial, And, floor)
from sympy.polys.polyerrors import PolynomialError
from sympy.stats.crv import reduce_rational_inequalities_wrap
from sympy.stats.rv import (NamedArgsMixin, SinglePSpace, SingleDomain,
random_symbols, PSpace, ConditionalDomain, RandomDomain,
ProductDomain, Distribution)
from sympy.stats.symbolic_probability import Probability
from sympy.sets.fancysets import Range, FiniteSet
from sympy.sets.sets import Union
from sympy.sets.contains import Contains
from sympy.utilities import filldedent
from sympy.core.sympify import _sympify
class DiscreteDistribution(Distribution):
def __call__(self, *args):
return self.pdf(*args)
class SingleDiscreteDistribution(DiscreteDistribution, NamedArgsMixin):
""" Discrete distribution of a single variable
Serves as superclass for PoissonDistribution etc....
Provides methods for pdf, cdf, and sampling
See Also:
sympy.stats.crv_types.*
"""
set = S.Integers
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
@cacheit
def compute_cdf(self, **kwargs):
""" Compute the CDF from the PDF
Returns a Lambda
"""
x = symbols('x', integer=True, cls=Dummy)
z = symbols('z', real=True, cls=Dummy)
left_bound = self.set.inf
# CDF is integral of PDF from left bound to z
pdf = self.pdf(x)
cdf = summation(pdf, (x, left_bound, floor(z)), **kwargs)
# CDF Ensure that CDF left of left_bound is zero
cdf = Piecewise((cdf, z >= left_bound), (0, True))
return Lambda(z, cdf)
def _cdf(self, x):
return None
def cdf(self, x, **kwargs):
""" Cumulative density function """
if not kwargs:
cdf = self._cdf(x)
if cdf is not None:
return cdf
return self.compute_cdf(**kwargs)(x)
@cacheit
def compute_characteristic_function(self, **kwargs):
""" Compute the characteristic function from the PDF
Returns a Lambda
"""
x, t = symbols('x, t', real=True, cls=Dummy)
pdf = self.pdf(x)
cf = summation(exp(I*t*x)*pdf, (x, self.set.inf, self.set.sup))
return Lambda(t, cf)
def _characteristic_function(self, t):
return None
def characteristic_function(self, t, **kwargs):
""" Characteristic function """
if not kwargs:
cf = self._characteristic_function(t)
if cf is not None:
return cf
return self.compute_characteristic_function(**kwargs)(t)
@cacheit
def compute_moment_generating_function(self, **kwargs):
t = Dummy('t', real=True)
x = Dummy('x', integer=True)
pdf = self.pdf(x)
mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup))
return Lambda(t, mgf)
def _moment_generating_function(self, t):
return None
def moment_generating_function(self, t, **kwargs):
if not kwargs:
mgf = self._moment_generating_function(t)
if mgf is not None:
return mgf
return self.compute_moment_generating_function(**kwargs)(t)
@cacheit
def compute_quantile(self, **kwargs):
""" Compute the Quantile from the PDF
Returns a Lambda
"""
x = Dummy('x', integer=True)
p = Dummy('p', real=True)
left_bound = self.set.inf
pdf = self.pdf(x)
cdf = summation(pdf, (x, left_bound, x), **kwargs)
set = ((x, p <= cdf), )
return Lambda(p, Piecewise(*set))
def _quantile(self, x):
return None
def quantile(self, x, **kwargs):
""" Cumulative density function """
if not kwargs:
quantile = self._quantile(x)
if quantile is not None:
return quantile
return self.compute_quantile(**kwargs)(x)
def expectation(self, expr, var, evaluate=True, **kwargs):
""" Expectation of expression over distribution """
# TODO: support discrete sets with non integer stepsizes
if evaluate:
try:
p = poly(expr, var)
t = Dummy('t', real=True)
mgf = self.moment_generating_function(t)
deg = p.degree()
taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
result = 0
for k in range(deg+1):
result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
return result
except PolynomialError:
return summation(expr * self.pdf(var),
(var, self.set.inf, self.set.sup), **kwargs)
else:
return Sum(expr * self.pdf(var),
(var, self.set.inf, self.set.sup), **kwargs)
def __call__(self, *args):
return self.pdf(*args)
class DiscreteDomain(RandomDomain):
"""
A domain with discrete support with step size one.
Represented using symbols and Range.
"""
is_Discrete = True
class SingleDiscreteDomain(DiscreteDomain, SingleDomain):
def as_boolean(self):
return Contains(self.symbol, self.set)
class ConditionalDiscreteDomain(DiscreteDomain, ConditionalDomain):
"""
Domain with discrete support of step size one, that is restricted by
some condition.
"""
@property
def set(self):
rv = self.symbols
if len(self.symbols) > 1:
raise NotImplementedError(filldedent('''
Multivariate conditional domains are not yet implemented.'''))
rv = list(rv)[0]
return reduce_rational_inequalities_wrap(self.condition,
rv).intersect(self.fulldomain.set)
class DiscretePSpace(PSpace):
is_real = True
is_Discrete = True
@property
def pdf(self):
return self.density(*self.symbols)
def where(self, condition):
rvs = random_symbols(condition)
assert all(r.symbol in self.symbols for r in rvs)
if len(rvs) > 1:
raise NotImplementedError(filldedent('''Multivariate discrete
random variables are not yet supported.'''))
conditional_domain = reduce_rational_inequalities_wrap(condition,
rvs[0])
conditional_domain = conditional_domain.intersect(self.domain.set)
return SingleDiscreteDomain(rvs[0].symbol, conditional_domain)
def probability(self, condition):
complement = isinstance(condition, Ne)
if complement:
condition = Eq(condition.args[0], condition.args[1])
try:
_domain = self.where(condition).set
if condition == False or _domain is S.EmptySet:
return S.Zero
if condition == True or _domain == self.domain.set:
return S.One
prob = self.eval_prob(_domain)
except NotImplementedError:
from sympy.stats.rv import density
expr = condition.lhs - condition.rhs
dens = density(expr)
if not isinstance(dens, DiscreteDistribution):
from sympy.stats.drv_types import DiscreteDistributionHandmade
dens = DiscreteDistributionHandmade(dens)
z = Dummy('z', real=True)
space = SingleDiscretePSpace(z, dens)
prob = space.probability(condition.__class__(space.value, 0))
if prob is None:
prob = Probability(condition)
return prob if not complement else S.One - prob
def eval_prob(self, _domain):
sym = list(self.symbols)[0]
if isinstance(_domain, Range):
n = symbols('n', integer=True)
inf, sup, step = (r for r in _domain.args)
summand = ((self.pdf).replace(
sym, n*step))
rv = summation(summand,
(n, inf/step, (sup)/step - 1)).doit()
return rv
elif isinstance(_domain, FiniteSet):
pdf = Lambda(sym, self.pdf)
rv = sum(pdf(x) for x in _domain)
return rv
elif isinstance(_domain, Union):
rv = sum(self.eval_prob(x) for x in _domain.args)
return rv
def conditional_space(self, condition):
# XXX: Converting from set to tuple. The order matters to Lambda
# though so we should be starting with a set...
density = Lambda(tuple(self.symbols), self.pdf/self.probability(condition))
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
domain = ConditionalDiscreteDomain(self.domain, condition)
return DiscretePSpace(domain, density)
class ProductDiscreteDomain(ProductDomain, DiscreteDomain):
def as_boolean(self):
return And(*[domain.as_boolean for domain in self.domains])
class SingleDiscretePSpace(DiscretePSpace, SinglePSpace):
""" Discrete probability space over a single univariate variable """
is_real = True
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return SingleDiscreteDomain(self.symbol, self.set)
def sample(self, size=(), library='scipy', seed=None):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
def compute_expectation(self, expr, rvs=None, evaluate=True, **kwargs):
rvs = rvs or (self.value,)
if self.value not in rvs:
return expr
expr = _sympify(expr)
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
x = self.value.symbol
try:
return self.distribution.expectation(expr, x, evaluate=evaluate,
**kwargs)
except NotImplementedError:
return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup),
**kwargs)
def compute_cdf(self, expr, **kwargs):
if expr == self.value:
x = Dummy("x", real=True)
return Lambda(x, self.distribution.cdf(x, **kwargs))
else:
raise NotImplementedError()
def compute_density(self, expr, **kwargs):
if expr == self.value:
return self.distribution
raise NotImplementedError()
def compute_characteristic_function(self, expr, **kwargs):
if expr == self.value:
t = Dummy("t", real=True)
return Lambda(t, self.distribution.characteristic_function(t, **kwargs))
else:
raise NotImplementedError()
def compute_moment_generating_function(self, expr, **kwargs):
if expr == self.value:
t = Dummy("t", real=True)
return Lambda(t, self.distribution.moment_generating_function(t, **kwargs))
else:
raise NotImplementedError()
def compute_quantile(self, expr, **kwargs):
if expr == self.value:
p = Dummy("p", real=True)
return Lambda(p, self.distribution.quantile(p, **kwargs))
else:
raise NotImplementedError()
|
499b6c67d9ed542abddbc28769e0f71dbdbf59dbab5a3b377c3f5414be4b16d9 | """
Continuous Random Variables Module
See Also
========
sympy.stats.crv_types
sympy.stats.rv
sympy.stats.frv
"""
from sympy import (Interval, Intersection, symbols, sympify, Dummy, nan,
Integral, And, Or, Piecewise, cacheit, integrate, oo, Lambda,
Basic, S, exp, I, FiniteSet, Ne, Eq, Union, poly, series, factorial)
from sympy.core.function import PoleError
from sympy.functions.special.delta_functions import DiracDelta
from sympy.polys.polyerrors import PolynomialError
from sympy.solvers.solveset import solveset
from sympy.solvers.inequalities import reduce_rational_inequalities
from sympy.core.sympify import _sympify
from sympy.stats.rv import (RandomDomain, SingleDomain, ConditionalDomain, is_random,
ProductDomain, PSpace, SinglePSpace, random_symbols, NamedArgsMixin, Distribution)
class ContinuousDomain(RandomDomain):
"""
A domain with continuous support
Represented using symbols and Intervals.
"""
is_Continuous = True
def as_boolean(self):
raise NotImplementedError("Not Implemented for generic Domains")
class SingleContinuousDomain(ContinuousDomain, SingleDomain):
"""
A univariate domain with continuous support
Represented using a single symbol and interval.
"""
def compute_expectation(self, expr, variables=None, **kwargs):
if variables is None:
variables = self.symbols
if not variables:
return expr
if frozenset(variables) != frozenset(self.symbols):
raise ValueError("Values should be equal")
# assumes only intervals
return Integral(expr, (self.symbol, self.set), **kwargs)
def as_boolean(self):
return self.set.as_relational(self.symbol)
class ProductContinuousDomain(ProductDomain, ContinuousDomain):
"""
A collection of independent domains with continuous support
"""
def compute_expectation(self, expr, variables=None, **kwargs):
if variables is None:
variables = self.symbols
for domain in self.domains:
domain_vars = frozenset(variables) & frozenset(domain.symbols)
if domain_vars:
expr = domain.compute_expectation(expr, domain_vars, **kwargs)
return expr
def as_boolean(self):
return And(*[domain.as_boolean() for domain in self.domains])
class ConditionalContinuousDomain(ContinuousDomain, ConditionalDomain):
"""
A domain with continuous support that has been further restricted by a
condition such as x > 3
"""
def compute_expectation(self, expr, variables=None, **kwargs):
if variables is None:
variables = self.symbols
if not variables:
return expr
# Extract the full integral
fullintgrl = self.fulldomain.compute_expectation(expr, variables)
# separate into integrand and limits
integrand, limits = fullintgrl.function, list(fullintgrl.limits)
conditions = [self.condition]
while conditions:
cond = conditions.pop()
if cond.is_Boolean:
if isinstance(cond, And):
conditions.extend(cond.args)
elif isinstance(cond, Or):
raise NotImplementedError("Or not implemented here")
elif cond.is_Relational:
if cond.is_Equality:
# Add the appropriate Delta to the integrand
integrand *= DiracDelta(cond.lhs - cond.rhs)
else:
symbols = cond.free_symbols & set(self.symbols)
if len(symbols) != 1: # Can't handle x > y
raise NotImplementedError(
"Multivariate Inequalities not yet implemented")
# Can handle x > 0
symbol = symbols.pop()
# Find the limit with x, such as (x, -oo, oo)
for i, limit in enumerate(limits):
if limit[0] == symbol:
# Make condition into an Interval like [0, oo]
cintvl = reduce_rational_inequalities_wrap(
cond, symbol)
# Make limit into an Interval like [-oo, oo]
lintvl = Interval(limit[1], limit[2])
# Intersect them to get [0, oo]
intvl = cintvl.intersect(lintvl)
# Put back into limits list
limits[i] = (symbol, intvl.left, intvl.right)
else:
raise TypeError(
"Condition %s is not a relational or Boolean" % cond)
return Integral(integrand, *limits, **kwargs)
def as_boolean(self):
return And(self.fulldomain.as_boolean(), self.condition)
@property
def set(self):
if len(self.symbols) == 1:
return (self.fulldomain.set & reduce_rational_inequalities_wrap(
self.condition, tuple(self.symbols)[0]))
else:
raise NotImplementedError(
"Set of Conditional Domain not Implemented")
class ContinuousDistribution(Distribution):
def __call__(self, *args):
return self.pdf(*args)
class SingleContinuousDistribution(ContinuousDistribution, NamedArgsMixin):
""" Continuous distribution of a single variable
Serves as superclass for Normal/Exponential/UniformDistribution etc....
Represented by parameters for each of the specific classes. E.g
NormalDistribution is represented by a mean and standard deviation.
Provides methods for pdf, cdf, and sampling
See Also
========
sympy.stats.crv_types.*
"""
set = Interval(-oo, oo)
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
@cacheit
def compute_cdf(self, **kwargs):
""" Compute the CDF from the PDF
Returns a Lambda
"""
x, z = symbols('x, z', real=True, cls=Dummy)
left_bound = self.set.start
# CDF is integral of PDF from left bound to z
pdf = self.pdf(x)
cdf = integrate(pdf.doit(), (x, left_bound, z), **kwargs)
# CDF Ensure that CDF left of left_bound is zero
cdf = Piecewise((cdf, z >= left_bound), (0, True))
return Lambda(z, cdf)
def _cdf(self, x):
return None
def cdf(self, x, **kwargs):
""" Cumulative density function """
if len(kwargs) == 0:
cdf = self._cdf(x)
if cdf is not None:
return cdf
return self.compute_cdf(**kwargs)(x)
@cacheit
def compute_characteristic_function(self, **kwargs):
""" Compute the characteristic function from the PDF
Returns a Lambda
"""
x, t = symbols('x, t', real=True, cls=Dummy)
pdf = self.pdf(x)
cf = integrate(exp(I*t*x)*pdf, (x, self.set))
return Lambda(t, cf)
def _characteristic_function(self, t):
return None
def characteristic_function(self, t, **kwargs):
""" Characteristic function """
if len(kwargs) == 0:
cf = self._characteristic_function(t)
if cf is not None:
return cf
return self.compute_characteristic_function(**kwargs)(t)
@cacheit
def compute_moment_generating_function(self, **kwargs):
""" Compute the moment generating function from the PDF
Returns a Lambda
"""
x, t = symbols('x, t', real=True, cls=Dummy)
pdf = self.pdf(x)
mgf = integrate(exp(t * x) * pdf, (x, self.set))
return Lambda(t, mgf)
def _moment_generating_function(self, t):
return None
def moment_generating_function(self, t, **kwargs):
""" Moment generating function """
if not kwargs:
mgf = self._moment_generating_function(t)
if mgf is not None:
return mgf
return self.compute_moment_generating_function(**kwargs)(t)
def expectation(self, expr, var, evaluate=True, **kwargs):
""" Expectation of expression over distribution """
if evaluate:
try:
p = poly(expr, var)
if p.is_zero:
return S.Zero
t = Dummy('t', real=True)
mgf = self._moment_generating_function(t)
if mgf is None:
return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
deg = p.degree()
taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
result = 0
for k in range(deg+1):
result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
return result
except PolynomialError:
return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
else:
return Integral(expr * self.pdf(var), (var, self.set), **kwargs)
@cacheit
def compute_quantile(self, **kwargs):
""" Compute the Quantile from the PDF
Returns a Lambda
"""
x, p = symbols('x, p', real=True, cls=Dummy)
left_bound = self.set.start
pdf = self.pdf(x)
cdf = integrate(pdf, (x, left_bound, x), **kwargs)
quantile = solveset(cdf - p, x, self.set)
return Lambda(p, Piecewise((quantile, (p >= 0) & (p <= 1) ), (nan, True)))
def _quantile(self, x):
return None
def quantile(self, x, **kwargs):
""" Cumulative density function """
if len(kwargs) == 0:
quantile = self._quantile(x)
if quantile is not None:
return quantile
return self.compute_quantile(**kwargs)(x)
class ContinuousPSpace(PSpace):
""" Continuous Probability Space
Represents the likelihood of an event space defined over a continuum.
Represented with a ContinuousDomain and a PDF (Lambda-Like)
"""
is_Continuous = True
is_real = True
@property
def pdf(self):
return self.density(*self.domain.symbols)
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
if rvs is None:
rvs = self.values
else:
rvs = frozenset(rvs)
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
domain_symbols = frozenset(rv.symbol for rv in rvs)
return self.domain.compute_expectation(self.pdf * expr,
domain_symbols, **kwargs)
def compute_density(self, expr, **kwargs):
# Common case Density(X) where X in self.values
if expr in self.values:
# Marginalize all other random symbols out of the density
randomsymbols = tuple(set(self.values) - frozenset([expr]))
symbols = tuple(rs.symbol for rs in randomsymbols)
pdf = self.domain.compute_expectation(self.pdf, symbols, **kwargs)
return Lambda(expr.symbol, pdf)
z = Dummy('z', real=True)
return Lambda(z, self.compute_expectation(DiracDelta(expr - z), **kwargs))
@cacheit
def compute_cdf(self, expr, **kwargs):
if not self.domain.set.is_Interval:
raise ValueError(
"CDF not well defined on multivariate expressions")
d = self.compute_density(expr, **kwargs)
x, z = symbols('x, z', real=True, cls=Dummy)
left_bound = self.domain.set.start
# CDF is integral of PDF from left bound to z
cdf = integrate(d(x), (x, left_bound, z), **kwargs)
# CDF Ensure that CDF left of left_bound is zero
cdf = Piecewise((cdf, z >= left_bound), (0, True))
return Lambda(z, cdf)
@cacheit
def compute_characteristic_function(self, expr, **kwargs):
if not self.domain.set.is_Interval:
raise NotImplementedError("Characteristic function of multivariate expressions not implemented")
d = self.compute_density(expr, **kwargs)
x, t = symbols('x, t', real=True, cls=Dummy)
cf = integrate(exp(I*t*x)*d(x), (x, -oo, oo), **kwargs)
return Lambda(t, cf)
@cacheit
def compute_moment_generating_function(self, expr, **kwargs):
if not self.domain.set.is_Interval:
raise NotImplementedError("Moment generating function of multivariate expressions not implemented")
d = self.compute_density(expr, **kwargs)
x, t = symbols('x, t', real=True, cls=Dummy)
mgf = integrate(exp(t * x) * d(x), (x, -oo, oo), **kwargs)
return Lambda(t, mgf)
@cacheit
def compute_quantile(self, expr, **kwargs):
if not self.domain.set.is_Interval:
raise ValueError(
"Quantile not well defined on multivariate expressions")
d = self.compute_cdf(expr, **kwargs)
x = Dummy('x', real=True)
p = Dummy('p', positive=True)
quantile = solveset(d(x) - p, x, self.set)
return Lambda(p, quantile)
def probability(self, condition, **kwargs):
z = Dummy('z', real=True)
cond_inv = False
if isinstance(condition, Ne):
condition = Eq(condition.args[0], condition.args[1])
cond_inv = True
# Univariate case can be handled by where
try:
domain = self.where(condition)
rv = [rv for rv in self.values if rv.symbol == domain.symbol][0]
# Integrate out all other random variables
pdf = self.compute_density(rv, **kwargs)
# return S.Zero if `domain` is empty set
if domain.set is S.EmptySet or isinstance(domain.set, FiniteSet):
return S.Zero if not cond_inv else S.One
if isinstance(domain.set, Union):
return sum(
Integral(pdf(z), (z, subset), **kwargs) for subset in
domain.set.args if isinstance(subset, Interval))
# Integrate out the last variable over the special domain
return Integral(pdf(z), (z, domain.set), **kwargs)
# Other cases can be turned into univariate case
# by computing a density handled by density computation
except NotImplementedError:
from sympy.stats.rv import density
expr = condition.lhs - condition.rhs
if not is_random(expr):
dens = self.density
comp = condition.rhs
else:
dens = density(expr, **kwargs)
comp = 0
if not isinstance(dens, ContinuousDistribution):
from sympy.stats.crv_types import ContinuousDistributionHandmade
dens = ContinuousDistributionHandmade(dens, set=self.domain.set)
# Turn problem into univariate case
space = SingleContinuousPSpace(z, dens)
result = space.probability(condition.__class__(space.value, comp))
return result if not cond_inv else S.One - result
def where(self, condition):
rvs = frozenset(random_symbols(condition))
if not (len(rvs) == 1 and rvs.issubset(self.values)):
raise NotImplementedError(
"Multiple continuous random variables not supported")
rv = tuple(rvs)[0]
interval = reduce_rational_inequalities_wrap(condition, rv)
interval = interval.intersect(self.domain.set)
return SingleContinuousDomain(rv.symbol, interval)
def conditional_space(self, condition, normalize=True, **kwargs):
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
domain = ConditionalContinuousDomain(self.domain, condition)
if normalize:
# create a clone of the variable to
# make sure that variables in nested integrals are different
# from the variables outside the integral
# this makes sure that they are evaluated separately
# and in the correct order
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
norm = domain.compute_expectation(self.pdf, **kwargs)
pdf = self.pdf / norm.xreplace(replacement)
# XXX: Converting set to tuple. The order matters to Lambda though
# so we shouldn't be starting with a set here...
density = Lambda(tuple(domain.symbols), pdf)
return ContinuousPSpace(domain, density)
class SingleContinuousPSpace(ContinuousPSpace, SinglePSpace):
"""
A continuous probability space over a single univariate variable
These consist of a Symbol and a SingleContinuousDistribution
This class is normally accessed through the various random variable
functions, Normal, Exponential, Uniform, etc....
"""
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return SingleContinuousDomain(sympify(self.symbol), self.set)
def sample(self, size=(), library='scipy', seed=None):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
rvs = rvs or (self.value,)
if self.value not in rvs:
return expr
expr = _sympify(expr)
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
x = self.value.symbol
try:
return self.distribution.expectation(expr, x, evaluate=evaluate, **kwargs)
except PoleError:
return Integral(expr * self.pdf, (x, self.set), **kwargs)
def compute_cdf(self, expr, **kwargs):
if expr == self.value:
z = Dummy("z", real=True)
return Lambda(z, self.distribution.cdf(z, **kwargs))
else:
return ContinuousPSpace.compute_cdf(self, expr, **kwargs)
def compute_characteristic_function(self, expr, **kwargs):
if expr == self.value:
t = Dummy("t", real=True)
return Lambda(t, self.distribution.characteristic_function(t, **kwargs))
else:
return ContinuousPSpace.compute_characteristic_function(self, expr, **kwargs)
def compute_moment_generating_function(self, expr, **kwargs):
if expr == self.value:
t = Dummy("t", real=True)
return Lambda(t, self.distribution.moment_generating_function(t, **kwargs))
else:
return ContinuousPSpace.compute_moment_generating_function(self, expr, **kwargs)
def compute_density(self, expr, **kwargs):
# https://en.wikipedia.org/wiki/Random_variable#Functions_of_random_variables
if expr == self.value:
return self.density
y = Dummy('y', real=True)
gs = solveset(expr - y, self.value, S.Reals)
if isinstance(gs, Intersection) and S.Reals in gs.args:
gs = list(gs.args[1])
if not gs:
raise ValueError("Can not solve %s for %s"%(expr, self.value))
fx = self.compute_density(self.value)
fy = sum(fx(g) * abs(g.diff(y)) for g in gs)
return Lambda(y, fy)
def compute_quantile(self, expr, **kwargs):
if expr == self.value:
p = Dummy("p", real=True)
return Lambda(p, self.distribution.quantile(p, **kwargs))
else:
return ContinuousPSpace.compute_quantile(self, expr, **kwargs)
def _reduce_inequalities(conditions, var, **kwargs):
try:
return reduce_rational_inequalities(conditions, var, **kwargs)
except PolynomialError:
raise ValueError("Reduction of condition failed %s\n" % conditions[0])
def reduce_rational_inequalities_wrap(condition, var):
if condition.is_Relational:
return _reduce_inequalities([[condition]], var, relational=False)
if isinstance(condition, Or):
return Union(*[_reduce_inequalities([[arg]], var, relational=False)
for arg in condition.args])
if isinstance(condition, And):
intervals = [_reduce_inequalities([[arg]], var, relational=False)
for arg in condition.args]
I = intervals[0]
for i in intervals:
I = I.intersect(i)
return I
|
09b92427a32e4c5cc5b3697c188a92f2f7bcf29e02308fe33d2fa5ec0d831fed | """
Finite Discrete Random Variables Module
See Also
========
sympy.stats.frv_types
sympy.stats.rv
sympy.stats.crv
"""
from itertools import product
from sympy import (Basic, Symbol, cacheit, sympify, Mul,
And, Or, Piecewise, Eq, Lambda, exp, I, Dummy, nan,
Sum, Intersection, S)
from sympy.core.containers import Dict
from sympy.core.logic import Logic
from sympy.core.relational import Relational
from sympy.core.sympify import _sympify
from sympy.sets.sets import FiniteSet
from sympy.stats.rv import (RandomDomain, ProductDomain, ConditionalDomain,
PSpace, IndependentProductPSpace, SinglePSpace, random_symbols,
sumsets, rv_subs, NamedArgsMixin, Density, Distribution)
class FiniteDensity(dict):
"""
A domain with Finite Density.
"""
def __call__(self, item):
"""
Make instance of a class callable.
If item belongs to current instance of a class, return it.
Otherwise, return 0.
"""
item = sympify(item)
if item in self:
return self[item]
else:
return 0
@property
def dict(self):
"""
Return item as dictionary.
"""
return dict(self)
class FiniteDomain(RandomDomain):
"""
A domain with discrete finite support
Represented using a FiniteSet.
"""
is_Finite = True
@property
def symbols(self):
return FiniteSet(sym for sym, val in self.elements)
@property
def elements(self):
return self.args[0]
@property
def dict(self):
return FiniteSet(*[Dict(dict(el)) for el in self.elements])
def __contains__(self, other):
return other in self.elements
def __iter__(self):
return self.elements.__iter__()
def as_boolean(self):
return Or(*[And(*[Eq(sym, val) for sym, val in item]) for item in self])
class SingleFiniteDomain(FiniteDomain):
"""
A FiniteDomain over a single symbol/set
Example: The possibilities of a *single* die roll.
"""
def __new__(cls, symbol, set):
if not isinstance(set, FiniteSet) and \
not isinstance(set, Intersection):
set = FiniteSet(*set)
return Basic.__new__(cls, symbol, set)
@property
def symbol(self):
return self.args[0]
@property
def symbols(self):
return FiniteSet(self.symbol)
@property
def set(self):
return self.args[1]
@property
def elements(self):
return FiniteSet(*[frozenset(((self.symbol, elem), )) for elem in self.set])
def __iter__(self):
return (frozenset(((self.symbol, elem),)) for elem in self.set)
def __contains__(self, other):
sym, val = tuple(other)[0]
return sym == self.symbol and val in self.set
class ProductFiniteDomain(ProductDomain, FiniteDomain):
"""
A Finite domain consisting of several other FiniteDomains
Example: The possibilities of the rolls of three independent dice
"""
def __iter__(self):
proditer = product(*self.domains)
return (sumsets(items) for items in proditer)
@property
def elements(self):
return FiniteSet(*self)
class ConditionalFiniteDomain(ConditionalDomain, ProductFiniteDomain):
"""
A FiniteDomain that has been restricted by a condition
Example: The possibilities of a die roll under the condition that the
roll is even.
"""
def __new__(cls, domain, condition):
"""
Create a new instance of ConditionalFiniteDomain class
"""
if condition is True:
return domain
cond = rv_subs(condition)
return Basic.__new__(cls, domain, cond)
def _test(self, elem):
"""
Test the value. If value is boolean, return it. If value is equality
relational (two objects are equal), return it with left-hand side
being equal to right-hand side. Otherwise, raise ValueError exception.
"""
val = self.condition.xreplace(dict(elem))
if val in [True, False]:
return val
elif val.is_Equality:
return val.lhs == val.rhs
raise ValueError("Undecidable if %s" % str(val))
def __contains__(self, other):
return other in self.fulldomain and self._test(other)
def __iter__(self):
return (elem for elem in self.fulldomain if self._test(elem))
@property
def set(self):
if isinstance(self.fulldomain, SingleFiniteDomain):
return FiniteSet(*[elem for elem in self.fulldomain.set
if frozenset(((self.fulldomain.symbol, elem),)) in self])
else:
raise NotImplementedError(
"Not implemented on multi-dimensional conditional domain")
def as_boolean(self):
return FiniteDomain.as_boolean(self)
class SingleFiniteDistribution(Distribution, NamedArgsMixin):
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
@property # type: ignore
@cacheit
def dict(self):
if self.is_symbolic:
return Density(self)
return {k: self.pmf(k) for k in self.set}
def pmf(self, *args): # to be overridden by specific distribution
raise NotImplementedError()
@property
def set(self): # to be overridden by specific distribution
raise NotImplementedError()
values = property(lambda self: self.dict.values)
items = property(lambda self: self.dict.items)
is_symbolic = property(lambda self: False)
__iter__ = property(lambda self: self.dict.__iter__)
__getitem__ = property(lambda self: self.dict.__getitem__)
def __call__(self, *args):
return self.pmf(*args)
def __contains__(self, other):
return other in self.set
#=============================================
#========= Probability Space ===============
#=============================================
class FinitePSpace(PSpace):
"""
A Finite Probability Space
Represents the probabilities of a finite number of events.
"""
is_Finite = True
def __new__(cls, domain, density):
density = {sympify(key): sympify(val)
for key, val in density.items()}
public_density = Dict(density)
obj = PSpace.__new__(cls, domain, public_density)
obj._density = density
return obj
def prob_of(self, elem):
elem = sympify(elem)
density = self._density
if isinstance(list(density.keys())[0], FiniteSet):
return density.get(elem, S.Zero)
return density.get(tuple(elem)[0][1], S.Zero)
def where(self, condition):
assert all(r.symbol in self.symbols for r in random_symbols(condition))
return ConditionalFiniteDomain(self.domain, condition)
def compute_density(self, expr):
expr = rv_subs(expr, self.values)
d = FiniteDensity()
for elem in self.domain:
val = expr.xreplace(dict(elem))
prob = self.prob_of(elem)
d[val] = d.get(val, S.Zero) + prob
return d
@cacheit
def compute_cdf(self, expr):
d = self.compute_density(expr)
cum_prob = S.Zero
cdf = []
for key in sorted(d):
prob = d[key]
cum_prob += prob
cdf.append((key, cum_prob))
return dict(cdf)
@cacheit
def sorted_cdf(self, expr, python_float=False):
cdf = self.compute_cdf(expr)
items = list(cdf.items())
sorted_items = sorted(items, key=lambda val_cumprob: val_cumprob[1])
if python_float:
sorted_items = [(v, float(cum_prob))
for v, cum_prob in sorted_items]
return sorted_items
@cacheit
def compute_characteristic_function(self, expr):
d = self.compute_density(expr)
t = Dummy('t', real=True)
return Lambda(t, sum(exp(I*k*t)*v for k,v in d.items()))
@cacheit
def compute_moment_generating_function(self, expr):
d = self.compute_density(expr)
t = Dummy('t', real=True)
return Lambda(t, sum(exp(k*t)*v for k,v in d.items()))
def compute_expectation(self, expr, rvs=None, **kwargs):
rvs = rvs or self.values
expr = rv_subs(expr, rvs)
probs = [self.prob_of(elem) for elem in self.domain]
if isinstance(expr, (Logic, Relational)):
parse_domain = [tuple(elem)[0][1] for elem in self.domain]
bools = [expr.xreplace(dict(elem)) for elem in self.domain]
else:
parse_domain = [expr.xreplace(dict(elem)) for elem in self.domain]
bools = [True for elem in self.domain]
return sum([Piecewise((prob * elem, blv), (S.Zero, True))
for prob, elem, blv in zip(probs, parse_domain, bools)])
def compute_quantile(self, expr):
cdf = self.compute_cdf(expr)
p = Dummy('p', real=True)
set = ((nan, (p < 0) | (p > 1)),)
for key, value in cdf.items():
set = set + ((key, p <= value), )
return Lambda(p, Piecewise(*set))
def probability(self, condition):
cond_symbols = frozenset(rs.symbol for rs in random_symbols(condition))
cond = rv_subs(condition)
if not cond_symbols.issubset(self.symbols):
raise ValueError("Cannot compare foreign random symbols, %s"
%(str(cond_symbols - self.symbols)))
if isinstance(condition, Relational) and \
(not cond.free_symbols.issubset(self.domain.free_symbols)):
rv = condition.lhs if isinstance(condition.rhs, Symbol) else condition.rhs
return sum(Piecewise(
(self.prob_of(elem), condition.subs(rv, list(elem)[0][1])),
(S.Zero, True)) for elem in self.domain)
return sympify(sum(self.prob_of(elem) for elem in self.where(condition)))
def conditional_space(self, condition):
domain = self.where(condition)
prob = self.probability(condition)
density = {key: val / prob
for key, val in self._density.items() if domain._test(key)}
return FinitePSpace(domain, density)
def sample(self, size=(), library='scipy', seed=None):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
return {self.value: self.distribution.sample(size, library, seed)}
class SingleFinitePSpace(SinglePSpace, FinitePSpace):
"""
A single finite probability space
Represents the probabilities of a set of random events that can be
attributed to a single variable/symbol.
This class is implemented by many of the standard FiniteRV types such as
Die, Bernoulli, Coin, etc....
"""
@property
def domain(self):
return SingleFiniteDomain(self.symbol, self.distribution.set)
@property
def _is_symbolic(self):
"""
Helper property to check if the distribution
of the random variable is having symbolic
dimension.
"""
return self.distribution.is_symbolic
@property
def distribution(self):
return self.args[1]
def pmf(self, expr):
return self.distribution.pmf(expr)
@property # type: ignore
@cacheit
def _density(self):
return {FiniteSet((self.symbol, val)): prob
for val, prob in self.distribution.dict.items()}
@cacheit
def compute_characteristic_function(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
t = Dummy('t', real=True)
ki = Dummy('ki')
return Lambda(t, Sum(d(ki)*exp(I*ki*t), (ki, self.args[1].low, self.args[1].high)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_characteristic_function(expr)
@cacheit
def compute_moment_generating_function(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
t = Dummy('t', real=True)
ki = Dummy('ki')
return Lambda(t, Sum(d(ki)*exp(ki*t), (ki, self.args[1].low, self.args[1].high)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_moment_generating_function(expr)
def compute_quantile(self, expr):
if self._is_symbolic:
raise NotImplementedError("Computing quantile for random variables "
"with symbolic dimension because the bounds of searching the required "
"value is undetermined.")
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_quantile(expr)
def compute_density(self, expr):
if self._is_symbolic:
rv = list(random_symbols(expr))[0]
k = Dummy('k', integer=True)
cond = True if not isinstance(expr, (Relational, Logic)) \
else expr.subs(rv, k)
return Lambda(k,
Piecewise((self.pmf(k), And(k >= self.args[1].low,
k <= self.args[1].high, cond)), (S.Zero, True)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_density(expr)
def compute_cdf(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
k = Dummy('k')
ki = Dummy('ki')
return Lambda(k, Sum(d(ki), (ki, self.args[1].low, k)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_cdf(expr)
def compute_expectation(self, expr, rvs=None, **kwargs):
if self._is_symbolic:
rv = random_symbols(expr)[0]
k = Dummy('k', integer=True)
expr = expr.subs(rv, k)
cond = True if not isinstance(expr, (Relational, Logic)) \
else expr
func = self.pmf(k) * k if cond != True else self.pmf(k) * expr
return Sum(Piecewise((func, cond), (S.Zero, True)),
(k, self.distribution.low, self.distribution.high)).doit()
expr = _sympify(expr)
expr = rv_subs(expr, rvs)
return FinitePSpace(self.domain, self.distribution).compute_expectation(expr, rvs, **kwargs)
def probability(self, condition):
if self._is_symbolic:
#TODO: Implement the mechanism for handling queries for symbolic sized distributions.
raise NotImplementedError("Currently, probability queries are not "
"supported for random variables with symbolic sized distributions.")
condition = rv_subs(condition)
return FinitePSpace(self.domain, self.distribution).probability(condition)
def conditional_space(self, condition):
"""
This method is used for transferring the
computation to probability method because
conditional space of random variables with
symbolic dimensions is currently not possible.
"""
if self._is_symbolic:
self
domain = self.where(condition)
prob = self.probability(condition)
density = {key: val / prob
for key, val in self._density.items() if domain._test(key)}
return FinitePSpace(domain, density)
class ProductFinitePSpace(IndependentProductPSpace, FinitePSpace):
"""
A collection of several independent finite probability spaces
"""
@property
def domain(self):
return ProductFiniteDomain(*[space.domain for space in self.spaces])
@property # type: ignore
@cacheit
def _density(self):
proditer = product(*[iter(space._density.items())
for space in self.spaces])
d = {}
for items in proditer:
elems, probs = list(zip(*items))
elem = sumsets(elems)
prob = Mul(*probs)
d[elem] = d.get(elem, S.Zero) + prob
return Dict(d)
@property # type: ignore
@cacheit
def density(self):
return Dict(self._density)
def probability(self, condition):
return FinitePSpace.probability(self, condition)
def compute_density(self, expr):
return FinitePSpace.compute_density(self, expr)
|
7b50529062c0e2064cce79a317e7d9be8730aa25180c3f129ef0f655ec124baa | """
Generating and counting primes.
"""
import random
from bisect import bisect
from itertools import count
# Using arrays for sieving instead of lists greatly reduces
# memory consumption
from array import array as _array
from sympy import Function, S
from sympy.core.compatibility import as_int
from .primetest import isprime
def _azeros(n):
return _array('l', [0]*n)
def _aset(*v):
return _array('l', v)
def _arange(a, b):
return _array('l', range(a, b))
class Sieve:
"""An infinite list of prime numbers, implemented as a dynamically
growing sieve of Eratosthenes. When a lookup is requested involving
an odd number that has not been sieved, the sieve is automatically
extended up to that number.
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> 25 in sieve
False
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
"""
# data shared (and updated) by all Sieve instances
def __init__(self):
self._n = 6
self._list = _aset(2, 3, 5, 7, 11, 13) # primes
self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient
self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius
assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
def __repr__(self):
return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
'prime', len(self._list),
self._list[0], self._list[1], self._list[2],
self._list[-2], self._list[-1],
'totient', len(self._tlist),
self._tlist[0], self._tlist[1],
self._tlist[2], self._tlist[-2], self._tlist[-1],
'mobius', len(self._mlist),
self._mlist[0], self._mlist[1],
self._mlist[2], self._mlist[-2], self._mlist[-1])
def _reset(self, prime=None, totient=None, mobius=None):
"""Reset all caches (default). To reset one or more set the
desired keyword to True."""
if all(i is None for i in (prime, totient, mobius)):
prime = totient = mobius = True
if prime:
self._list = self._list[:self._n]
if totient:
self._tlist = self._tlist[:self._n]
if mobius:
self._mlist = self._mlist[:self._n]
def extend(self, n):
"""Grow the sieve to cover all primes <= n (a real number).
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend(30)
>>> sieve[10] == 29
True
"""
n = int(n)
if n <= self._list[-1]:
return
# We need to sieve against all bases up to sqrt(n).
# This is a recursive call that will do nothing if there are enough
# known bases already.
maxbase = int(n**0.5) + 1
self.extend(maxbase)
# Create a new sieve starting from sqrt(n)
begin = self._list[-1] + 1
newsieve = _arange(begin, n + 1)
# Now eliminate all multiples of primes in [2, sqrt(n)]
for p in self.primerange(2, maxbase):
# Start counting at a multiple of p, offsetting
# the index to account for the new sieve's base index
startindex = (-begin) % p
for i in range(startindex, len(newsieve), p):
newsieve[i] = 0
# Merge the sieves
self._list += _array('l', [x for x in newsieve if x])
def extend_to_no(self, i):
"""Extend to include the ith prime number.
Parameters
==========
i : integer
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend_to_no(9)
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
Notes
=====
The list is extended by 50% if it is too short, so it is
likely that it will be longer than requested.
"""
i = as_int(i)
while len(self._list) < i:
self.extend(int(self._list[-1] * 1.5))
def primerange(self, a, b=None):
"""Generate all prime numbers in the range [a, b) when both a and b are
provided and generates all prime numbers till a when only a is provided.
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.primerange(7, 19)])
[7, 11, 13, 17]
>>> print([i for i in sieve.primerange(19)])
[2, 3, 5, 7, 11, 13, 17]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
if b is None:
b = as_int(ceiling(a))
a = 2
else:
a = max(2, as_int(ceiling(a)))
b = as_int(ceiling(b))
if a >= b:
return
self.extend(b)
i = self.search(a)[1]
maxi = len(self._list) + 1
while i < maxi:
p = self._list[i - 1]
if p < b:
yield p
i += 1
else:
return
def totientrange(self, a, b):
"""Generate all totient numbers for the range [a, b).
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.totientrange(7, 18)])
[6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._tlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._tlist[i]
else:
self._tlist += _arange(n, b)
for i in range(1, n):
ti = self._tlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
for i in range(n, b):
ti = self._tlist[i]
for j in range(2 * i, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
def mobiusrange(self, a, b):
"""Generate all mobius numbers for the range [a, b).
Parameters
==========
a : integer
First number in range
b : integer
First number outside of range
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.mobiusrange(7, 18)])
[-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._mlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._mlist[i]
else:
self._mlist += _azeros(b - n)
for i in range(1, n):
mi = self._mlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
for i in range(n, b):
mi = self._mlist[i]
for j in range(2 * i, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
def search(self, n):
"""Return the indices i, j of the primes that bound n.
If n is prime then i == j.
Although n can be an expression, if ceiling cannot convert
it to an integer then an n error will be raised.
Examples
========
>>> from sympy import sieve
>>> sieve.search(25)
(9, 10)
>>> sieve.search(23)
(9, 9)
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
test = as_int(ceiling(n))
n = as_int(n)
if n < 2:
raise ValueError("n should be >= 2 but got: %s" % n)
if n > self._list[-1]:
self.extend(n)
b = bisect(self._list, n)
if self._list[b - 1] == test:
return b, b
else:
return b, b + 1
def __contains__(self, n):
try:
n = as_int(n)
assert n >= 2
except (ValueError, AssertionError):
return False
if n % 2 == 0:
return n == 2
a, b = self.search(n)
return a == b
def __iter__(self):
for n in count(1):
yield self[n]
def __getitem__(self, n):
"""Return the nth prime number"""
if isinstance(n, slice):
self.extend_to_no(n.stop)
# Python 2.7 slices have 0 instead of None for start, so
# we can't default to 1.
start = n.start if n.start is not None else 0
if start < 1:
# sieve[:5] would be empty (starting at -1), let's
# just be explicit and raise.
raise IndexError("Sieve indices start at 1.")
return self._list[start - 1:n.stop - 1:n.step]
else:
if n < 1:
# offset is one, so forbid explicit access to sieve[0]
# (would surprisingly return the last one).
raise IndexError("Sieve indices start at 1.")
n = as_int(n)
self.extend_to_no(n)
return self._list[n - 1]
# Generate a global object for repeated use in trial division etc
sieve = Sieve()
def prime(nth):
""" Return the nth prime, with the primes indexed as prime(1) = 2,
prime(2) = 3, etc.... The nth prime is approximately n*log(n).
Logarithmic integral of x is a pretty nice approximation for number of
primes <= x, i.e.
li(x) ~ pi(x)
In fact, for the numbers we are concerned about( x<1e11 ),
li(x) - pi(x) < 50000
Also,
li(x) > pi(x) can be safely assumed for the numbers which
can be evaluated by this function.
Here, we find the least integer m such that li(m) > n using binary search.
Now pi(m-1) < li(m-1) <= n,
We find pi(m - 1) using primepi function.
Starting from m, we have to find n - pi(m-1) more primes.
For the inputs this implementation can handle, we will have to test
primality for at max about 10**5 numbers, to get our answer.
Examples
========
>>> from sympy import prime
>>> prime(10)
29
>>> prime(1)
2
>>> prime(100000)
1299709
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29
.. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
.. [3] https://en.wikipedia.org/wiki/Skewes%27_number
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; prime(1) == 2")
if n <= len(sieve._list):
return sieve[n]
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 2 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if li(mid) > n:
b = mid
else:
a = mid + 1
n_primes = primepi(a - 1)
while n_primes < n:
if isprime(a):
n_primes += 1
a += 1
return a - 1
class primepi(Function):
""" Represents the prime counting function pi(n) = the number
of prime numbers less than or equal to n.
Algorithm Description:
In sieve method, we remove all multiples of prime p
except p itself.
Let phi(i,j) be the number of integers 2 <= k <= i
which remain after sieving from primes less than
or equal to j.
Clearly, pi(n) = phi(n, sqrt(n))
If j is not a prime,
phi(i,j) = phi(i, j - 1)
if j is a prime,
We remove all numbers(except j) whose
smallest prime factor is j.
Let x= j*a be such a number, where 2 <= a<= i / j
Now, after sieving from primes <= j - 1,
a must remain
(because x, and hence a has no prime factor <= j - 1)
Clearly, there are phi(i / j, j - 1) such a
which remain on sieving from primes <= j - 1
Now, if a is a prime less than equal to j - 1,
x= j*a has smallest prime factor = a, and
has already been removed(by sieving from a).
So, we don't need to remove it again.
(Note: there will be pi(j - 1) such x)
Thus, number of x, that will be removed are:
phi(i / j, j - 1) - phi(j - 1, j - 1)
(Note that pi(j - 1) = phi(j - 1, j - 1))
=> phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
So,following recursion is used and implemented as dp:
phi(a, b) = phi(a, b - 1), if b is not a prime
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
Clearly a is always of the form floor(n / k),
which can take at most 2*sqrt(n) values.
Two arrays arr1,arr2 are maintained
arr1[i] = phi(i, j),
arr2[i] = phi(n // i, j)
Finally the answer is arr2[1]
Examples
========
>>> from sympy import primepi
>>> primepi(25)
9
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n is S.NegativeInfinity:
return S.Zero
try:
n = int(n)
except TypeError:
if n.is_real == False or n is S.NaN:
raise ValueError("n must be real")
return
if n < 2:
return S.Zero
if n <= sieve._list[-1]:
return S(sieve.search(n)[0])
lim = int(n ** 0.5)
lim -= 1
lim = max(lim, 0)
while lim * lim <= n:
lim += 1
lim -= 1
arr1 = [0] * (lim + 1)
arr2 = [0] * (lim + 1)
for i in range(1, lim + 1):
arr1[i] = i - 1
arr2[i] = n // i - 1
for i in range(2, lim + 1):
# Presently, arr1[k]=phi(k,i - 1),
# arr2[k] = phi(n // k,i - 1)
if arr1[i] == arr1[i - 1]:
continue
p = arr1[i - 1]
for j in range(1, min(n // (i * i), lim) + 1):
st = i * j
if st <= lim:
arr2[j] -= arr2[st] - p
else:
arr2[j] -= arr1[n // st] - p
lim2 = min(lim, i * i - 1)
for j in range(lim, lim2, -1):
arr1[j] -= arr1[j // i] - p
return S(arr2[1])
def nextprime(n, ith=1):
""" Return the ith prime greater than n.
i must be an integer.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import nextprime
>>> [(i, nextprime(i)) for i in range(10, 15)]
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
>>> nextprime(2, ith=2) # the 2nd prime after 2
5
See Also
========
prevprime : Return the largest prime smaller than n
primerange : Generate all primes in a given range
"""
n = int(n)
i = as_int(ith)
if i > 1:
pr = n
j = 1
while 1:
pr = nextprime(pr)
j += 1
if j > i:
break
return pr
if n < 2:
return 2
if n < 7:
return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n]
if n <= sieve._list[-2]:
l, u = sieve.search(n)
if l == u:
return sieve[u + 1]
else:
return sieve[u]
nn = 6*(n//6)
if nn == n:
n += 1
if isprime(n):
return n
n += 4
elif n - nn == 5:
n += 2
if isprime(n):
return n
n += 4
else:
n = nn + 5
while 1:
if isprime(n):
return n
n += 2
if isprime(n):
return n
n += 4
def prevprime(n):
""" Return the largest prime smaller than n.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import prevprime
>>> [(i, prevprime(i)) for i in range(10, 15)]
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
See Also
========
nextprime : Return the ith prime greater than n
primerange : Generates all primes in a given range
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
n = as_int(ceiling(n))
if n < 3:
raise ValueError("no preceding primes")
if n < 8:
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
if n <= sieve._list[-1]:
l, u = sieve.search(n)
if l == u:
return sieve[l-1]
else:
return sieve[l]
nn = 6*(n//6)
if n - nn <= 1:
n = nn - 1
if isprime(n):
return n
n -= 4
else:
n = nn + 1
while 1:
if isprime(n):
return n
n -= 2
if isprime(n):
return n
n -= 4
def primerange(a, b):
""" Generate a list of all prime numbers in the range [a, b).
If the range exists in the default sieve, the values will
be returned from there; otherwise values will be returned
but will not modify the sieve.
Examples
========
>>> from sympy import primerange, sieve
>>> print([i for i in primerange(1, 30)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
The Sieve method, primerange, is generally faster but it will
occupy more memory as the sieve stores values. The default
instance of Sieve, named sieve, can be used:
>>> list(sieve.primerange(1, 30))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Notes
=====
Some famous conjectures about the occurrence of primes in a given
range are [1]:
- Twin primes: though often not, the following will give 2 primes
an infinite number of times:
primerange(6*n - 1, 6*n + 2)
- Legendre's: the following always yields at least one prime
primerange(n**2, (n+1)**2+1)
- Bertrand's (proven): there is always a prime in the range
primerange(n, 2*n)
- Brocard's: there are at least four primes in the range
primerange(prime(n)**2, prime(n+1)**2)
The average gap between primes is log(n) [2]; the gap between
primes can be arbitrarily large since sequences of composite
numbers are arbitrarily large, e.g. the numbers in the sequence
n! + 2, n! + 3 ... n! + n are all composite.
See Also
========
nextprime : Return the ith prime greater than n
prevprime : Return the largest prime smaller than n
randprime : Returns a random prime in a given range
primorial : Returns the product of primes based on condition
Sieve.primerange : return range from already computed primes
or extend the sieve to contain the requested
range.
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number
.. [2] http://primes.utm.edu/notes/gaps.html
"""
from sympy.functions.elementary.integers import ceiling
if a >= b:
return
# if we already have the range, return it
if b <= sieve._list[-1]:
yield from sieve.primerange(a, b)
return
# otherwise compute, without storing, the desired range.
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = as_int(ceiling(a)) - 1
b = as_int(ceiling(b))
while 1:
a = nextprime(a)
if a < b:
yield a
else:
return
def randprime(a, b):
""" Return a random prime number in the range [a, b).
Bertrand's postulate assures that
randprime(a, 2*a) will always succeed for a > 1.
Examples
========
>>> from sympy import randprime, isprime
>>> randprime(1, 30) #doctest: +SKIP
13
>>> isprime(randprime(1, 30))
True
See Also
========
primerange : Generate all primes in a given range
References
==========
.. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
"""
if a >= b:
return
a, b = map(int, (a, b))
n = random.randint(a - 1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p
def primorial(n, nth=True):
"""
Returns the product of the first n primes (default) or
the primes less than or equal to n (when ``nth=False``).
Examples
========
>>> from sympy.ntheory.generate import primorial, primerange
>>> from sympy import factorint, Mul, primefactors, sqrt
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
210
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
6
>>> primorial(1)
2
>>> primorial(1, nth=False)
1
>>> primorial(sqrt(101), nth=False)
210
One can argue that the primes are infinite since if you take
a set of primes and multiply them together (e.g. the primorial) and
then add or subtract 1, the result cannot be divided by any of the
original factors, hence either 1 or more new primes must divide this
product of primes.
In this case, the number itself is a new prime:
>>> factorint(primorial(4) + 1)
{211: 1}
In this case two new primes are the factors:
>>> factorint(primorial(4) - 1)
{11: 1, 19: 1}
Here, some primes smaller and larger than the primes multiplied together
are obtained:
>>> p = list(primerange(10, 20))
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
[2, 5, 31, 149]
See Also
========
primerange : Generate all primes in a given range
"""
if nth:
n = as_int(n)
else:
n = int(n)
if n < 1:
raise ValueError("primorial argument must be >= 1")
p = 1
if nth:
for i in range(1, n + 1):
p *= prime(i)
else:
for i in primerange(2, n + 1):
p *= i
return p
def cycle_length(f, x0, nmax=None, values=False):
"""For a given iterated sequence, return a generator that gives
the length of the iterated cycle (lambda) and the length of terms
before the cycle begins (mu); if ``values`` is True then the
terms of the sequence will be returned instead. The sequence is
started with value ``x0``.
Note: more than the first lambda + mu terms may be returned and this
is the cost of cycle detection with Brent's method; there are, however,
generally less terms calculated than would have been calculated if the
proper ending point were determined, e.g. by using Floyd's method.
>>> from sympy.ntheory.generate import cycle_length
This will yield successive values of i <-- func(i):
>>> def iter(func, i):
... while 1:
... ii = func(i)
... yield ii
... i = ii
...
A function is defined:
>>> func = lambda i: (i**2 + 1) % 51
and given a seed of 4 and the mu and lambda terms calculated:
>>> next(cycle_length(func, 4))
(6, 2)
We can see what is meant by looking at the output:
>>> n = cycle_length(func, 4, values=True)
>>> list(ni for ni in n)
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
There are 6 repeating values after the first 2.
If a sequence is suspected of being longer than you might wish, ``nmax``
can be used to exit early (and mu will be returned as None):
>>> next(cycle_length(func, 4, nmax = 4))
(4, None)
>>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]
[17, 35, 2, 5]
Code modified from:
https://en.wikipedia.org/wiki/Cycle_detection.
"""
nmax = int(nmax or 0)
# main phase: search successive powers of two
power = lam = 1
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
i = 0
while tortoise != hare and (not nmax or i < nmax):
i += 1
if power == lam: # time to start a new power of two?
tortoise = hare
power *= 2
lam = 0
if values:
yield hare
hare = f(hare)
lam += 1
if nmax and i == nmax:
if values:
return
else:
yield nmax, None
return
if not values:
# Find the position of the first repetition of length lambda
mu = 0
tortoise = hare = x0
for i in range(lam):
hare = f(hare)
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
if mu:
mu -= 1
yield lam, mu
def composite(nth):
""" Return the nth composite number, with the composite numbers indexed as
composite(1) = 4, composite(2) = 6, etc....
Examples
========
>>> from sympy import composite
>>> composite(36)
52
>>> composite(1)
4
>>> composite(17737)
20000
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
prime : Return the nth prime
compositepi : Return the number of positive composite numbers less than or equal to n
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; composite(1) == 4")
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
if n <= 10:
return composite_arr[n - 1]
a, b = 4, sieve._list[-1]
if n <= b - primepi(b) - 1:
while a < b - 1:
mid = (a + b) >> 1
if mid - primepi(mid) - 1 > n:
b = mid
else:
a = mid
if isprime(a):
a -= 1
return a
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 4 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if mid - li(mid) - 1 > n:
b = mid
else:
a = mid + 1
n_composites = a - primepi(a) - 1
while n_composites > n:
if not isprime(a):
n_composites -= 1
a -= 1
if isprime(a):
a -= 1
return a
def compositepi(n):
""" Return the number of positive composite numbers less than or equal to n.
The first positive composite is 4, i.e. compositepi(4) = 1.
Examples
========
>>> from sympy import compositepi
>>> compositepi(25)
15
>>> compositepi(1000)
831
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
primepi : Return the number of primes less than or equal to n
composite : Return the nth composite number
"""
n = int(n)
if n < 4:
return 0
return n - primepi(n) - 1
|
9466ae7c51446422a9265a86f6224d765fb12daecd19848a0bc972f40917705e | from sympy.ntheory import sieve, isprime
from sympy.core.power import integer_log
from sympy.core.compatibility import as_int
import random
rgen = random.Random()
#----------------------------------------------------------------------------#
# #
# Lenstra's Elliptic Curve Factorization #
# #
#----------------------------------------------------------------------------#
class Point:
"""Montgomery form of Points in an elliptic curve.
In this form, the addition and doubling of points
does not need any y-coordinate information thus
decreasing the number of operations.
Using Montgomery form we try to perform point addition
and doubling in least amount of multiplications.
The elliptic curve used here is of the form
(E : b*y**2*z = x**3 + a*x**2*z + x*z**2).
The a_24 parameter is equal to (a + 2)/4.
References
==========
.. [1] http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
"""
def __init__(self, x_cord, z_cord, a_24, mod):
"""
Initial parameters for the Point class.
Parameters
==========
x_cord : X coordinate of the Point
z_cord : Z coordinate of the Point
a_24 : Parameter of the elliptic curve in Montgomery form
mod : modulus
"""
self.x_cord = x_cord
self.z_cord = z_cord
self.a_24 = a_24
self.mod = mod
def __eq__(self, other):
"""Two points are equal if X/Z of both points are equal
"""
from sympy import mod_inverse
if self.a_24 != other.a_24 or self.mod != other.mod:
return False
return self.x_cord * mod_inverse(self.z_cord, self.mod) % self.mod ==\
other.x_cord * mod_inverse(other.z_cord, self.mod) % self.mod
def add(self, Q, diff):
"""
Add two points self and Q where diff = self - Q. Moreover the assumption
is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm
requires 6 multiplications. Here the difference between the points
is already known and using this algorihtm speeds up the addition
by reducing the number of multiplication required. Also in the
mont_ladder algorithm is constructed in a way so that the difference
between intermediate points is always equal to the initial point.
So, we always know what the difference between the point is.
Parameters
==========
Q : point on the curve in Montgomery form
diff : self - Q
Examples
========
>>> from sympy.ntheory.ecm import Point
>>> p1 = Point(11, 16, 7, 29)
>>> p2 = Point(13, 10, 7, 29)
>>> p3 = p2.add(p1, p1)
>>> p3.x_cord
23
>>> p3.z_cord
17
"""
u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord)
v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord)
add, subt = u + v, u - v
x_cord = diff.z_cord * add * add % self.mod
z_cord = diff.x_cord * subt * subt % self.mod
return Point(x_cord, z_cord, self.a_24, self.mod)
def double(self):
"""
Doubles a point in an elliptic curve in Montgomery form.
This algorithm requires 5 multiplications.
Examples
========
>>> from sympy.ntheory.ecm import Point
>>> p1 = Point(11, 16, 7, 29)
>>> p2 = p1.double()
>>> p2.x_cord
13
>>> p2.z_cord
10
"""
u, v = self.x_cord + self.z_cord, self.x_cord - self.z_cord
u, v = u*u, v*v
diff = u - v
x_cord = u*v % self.mod
z_cord = diff*(v + self.a_24*diff) % self.mod
return Point(x_cord, z_cord, self.a_24, self.mod)
def mont_ladder(self, k):
"""
Scalar multiplication of a point in Montgomery form
using Montgomery Ladder Algorithm.
A total of 11 multiplications are required in each step of this
algorithm.
Parameters
==========
k : The positive integer multiplier
Examples
========
>>> from sympy.ntheory.ecm import Point
>>> p1 = Point(11, 16, 7, 29)
>>> p3 = p1.mont_ladder(3)
>>> p3.x_cord
23
>>> p3.z_cord
17
"""
Q = self
R = self.double()
for i in bin(k)[3:]:
if i == '1':
Q = R.add(Q, self)
R = R.double()
else:
R = Q.add(R, self)
Q = Q.double()
return Q
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200):
"""Returns one factor of n using
Lenstra's 2 Stage Elliptic curve Factorization
with Suyama's Parameterization. Here Montgomery
arithmetic is used for fast computation of addition
and doubling of points in elliptic curve.
This ECM method considers elliptic curves in Montgomery
form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves
elliptic curve operations (mod N), where the elements in
Z are reduced (mod N). Since N is not a prime, E over FF(N)
is not really an elliptic curve but we can still do point additions
and doubling as if FF(N) was a field.
Stage 1 : The basic algorithm involves taking a random point (P) on an
elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm.
Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|,
might be a smooth number that divides k. Then we have k = l * |E(FF(q))|
for some l. For any point belonging to the curve E, |E(FF(q))|*P = O,
hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn
factor of N (q) can be recovered by taking gcd(kP.z_cord, N).
Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize
the fact that even if kP != 0, the value of k might miss just one large
prime divisor of |E(FF(q))|. In this case we only need to compute the
scalar multiplication by p to get p*k*P = O. Here a second bound B2
restrict the size of possible values of p.
Parameters
==========
n : Number to be Factored
B1 : Stage 1 Bound
B2 : Stage 2 Bound
max_curve : Maximum number of curves generated
References
==========
.. [1] Carl Pomerance and Richard Crandall "Prime Numbers:
A Computational Perspective" (2nd Ed.), page 344
"""
from sympy import gcd, mod_inverse, sqrt
n = as_int(n)
if B1 % 2 != 0 or B2 % 2 != 0:
raise ValueError("The Bounds should be an even integer")
sieve.extend(B2)
if isprime(n):
return n
curve = 0
D = int(sqrt(B2))
beta = [0]*(D + 1)
S = [0]*(D + 1)
k = 1
for p in sieve.primerange(1, B1 + 1):
k *= pow(p, integer_log(B1, p)[0])
g = 1
while(curve <= max_curve):
curve += 1
#Suyama's Paramatrization
sigma = rgen.randint(6, n - 1)
u = (sigma*sigma - 5) % n
v = (4*sigma) % n
diff = v - u
u_3 = pow(u, 3, n)
try:
C = (pow(diff, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2) % n
except ValueError:
#If the mod_inverse(4*u_3*v, n) doesn't exist
return gcd(4*u_3*v, n)
a24 = (C + 2)*mod_inverse(4, n) % n
Q = Point(u_3 , pow(v, 3, n), a24, n)
Q = Q.mont_ladder(k)
g = gcd(Q.z_cord, n)
#Stage 1 factor
if g != 1 and g != n:
return g
#Stage 1 failure. Q.z = 0, Try another curve
elif g == n:
continue
#Stage 2 - Improved Standard Continuation
S[1] = Q.double()
S[2] = S[1].double()
beta[1] = (S[1].x_cord*S[1].z_cord) % n
beta[2] = (S[2].x_cord*S[2].z_cord) % n
for d in range(3, D + 1):
S[d] = S[d - 1].add(S[1], S[d - 2])
beta[d] = (S[d].x_cord*S[d].z_cord) % n
g = 1
B = B1 - 1
T = Q.mont_ladder(B - 2*D)
R = Q.mont_ladder(B)
for r in range(B, B2, 2*D):
alpha = (R.x_cord*R.z_cord) % n
for q in sieve.primerange(r + 2, r + 2*D + 1):
delta = (q - r) // 2
f = (R.x_cord - S[d].x_cord)*(R.z_cord + S[d].z_cord) -\
alpha + beta[delta]
g = (g*f) % n
#Swap
T, R = R, R.add(S[D], T)
g = gcd(n, g)
#Stage 2 Factor found
if g != 1 and g != n:
return g
#ECM failed, Increase the bounds
raise ValueError("Increase the bounds")
def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234):
"""Performs factorization using Lenstra's Elliptic curve method.
This function repeatedly calls `ecm_one_factor` to compute the factors
of n. First all the small factors are taken out using trial division.
Then `ecm_one_factor` is used to compute one factor at a time.
Parameters
==========
n : Number to be Factored
B1 : Stage 1 Bound
B2 : Stage 2 Bound
max_curve : Maximum number of curves generated
seed : Initialize pseudorandom generator
Examples
========
>>> from sympy.ntheory import ecm
>>> ecm(25645121643901801)
{5394769, 4753701529}
>>> ecm(9804659461513846513)
{4641991, 2112166839943}
"""
_factors = set()
for prime in sieve.primerange(1, 100000):
if n % prime == 0:
_factors.add(prime)
while(n % prime == 0):
n //= prime
rgen.seed(seed)
while(n > 1):
try:
factor = _ecm_one_factor(n, B1, B2, max_curve)
except ValueError:
raise ValueError("Increase the bounds")
_factors.add(factor)
n //= factor
factors = set()
for factor in _factors:
if isprime(factor):
factors.add(factor)
continue
factors |= ecm(factor)
return factors
|
bb229becf9dd9dcb131efb7ad653081fb98394f0945fdf245402ad0288fb2f25 | """
Primality testing
"""
from sympy.core.compatibility import as_int
from mpmath.libmp import bitcount as _bitlength
def _int_tuple(*i):
return tuple(int(_) for _ in i)
def is_euler_pseudoprime(n, b):
"""Returns True if n is prime or an Euler pseudoprime to base b, else False.
Euler Pseudoprime : In arithmetic, an odd composite integer n is called an
euler pseudoprime to base a, if a and n are coprime and satisfy the modular
arithmetic congruence relation :
a ^ (n-1)/2 = + 1(mod n) or
a ^ (n-1)/2 = - 1(mod n)
(where mod refers to the modulo operation).
Examples
========
>>> from sympy.ntheory.primetest import is_euler_pseudoprime
>>> is_euler_pseudoprime(2, 5)
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
"""
from sympy.ntheory.factor_ import trailing
if not mr(n, [b]):
return False
n = as_int(n)
r = n - 1
c = pow(b, r >> trailing(r), n)
if c == 1:
return True
while True:
if c == n - 1:
return True
c = pow(c, 2, n)
if c == 1:
return False
def is_square(n, prep=True):
"""Return True if n == a * a for some integer a, else False.
If n is suspected of *not* being a square then this is a
quick method of confirming that it is not.
Examples
========
>>> from sympy.ntheory.primetest import is_square
>>> is_square(25)
True
>>> is_square(2)
False
References
==========
[1] http://mersenneforum.org/showpost.php?p=110896
See Also
========
sympy.core.power.integer_nthroot
"""
if prep:
n = as_int(n)
if n < 0:
return False
if n in [0, 1]:
return True
m = n & 127
if not ((m*0x8bc40d7d) & (m*0xa1e2f5d1) & 0x14020a):
m = n % 63
if not ((m*0x3d491df7) & (m*0xc824a9f9) & 0x10f14008):
from sympy.core.power import integer_nthroot
return integer_nthroot(n, 2)[1]
return False
def _test(n, base, s, t):
"""Miller-Rabin strong pseudoprime test for one base.
Return False if n is definitely composite, True if n is
probably prime, with a probability greater than 3/4.
"""
# do the Fermat test
b = pow(base, t, n)
if b == 1 or b == n - 1:
return True
else:
for j in range(1, s):
b = pow(b, 2, n)
if b == n - 1:
return True
# see I. Niven et al. "An Introduction to Theory of Numbers", page 78
if b == 1:
return False
return False
def mr(n, bases):
"""Perform a Miller-Rabin strong pseudoprime test on n using a
given list of bases/witnesses.
References
==========
- Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 135-138
A list of thresholds and the bases they require are here:
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants_of_the_test
Examples
========
>>> from sympy.ntheory.primetest import mr
>>> mr(1373651, [2, 3])
False
>>> mr(479001599, [31, 73])
True
"""
from sympy.ntheory.factor_ import trailing
from sympy.polys.domains import ZZ
n = as_int(n)
if n < 2:
return False
# remove powers of 2 from n-1 (= t * 2**s)
s = trailing(n - 1)
t = n >> s
for base in bases:
# Bases >= n are wrapped, bases < 2 are invalid
if base >= n:
base %= n
if base >= 2:
base = ZZ(base)
if not _test(n, base, s, t):
return False
return True
def _lucas_sequence(n, P, Q, k):
"""Return the modular Lucas sequence (U_k, V_k, Q_k).
Given a Lucas sequence defined by P, Q, returns the kth values for
U and V, along with Q^k, all modulo n. This is intended for use with
possibly very large values of n and k, where the combinatorial functions
would be completely unusable.
The modular Lucas sequences are used in numerous places in number theory,
especially in the Lucas compositeness tests and the various n + 1 proofs.
Examples
========
>>> from sympy.ntheory.primetest import _lucas_sequence
>>> N = 10**2000 + 4561
>>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
(0, 2, 1)
"""
D = P*P - 4*Q
if n < 2:
raise ValueError("n must be >= 2")
if k < 0:
raise ValueError("k must be >= 0")
if D == 0:
raise ValueError("D must not be zero")
if k == 0:
return _int_tuple(0, 2, Q)
U = 1
V = P
Qk = Q
b = _bitlength(k)
if Q == 1:
# Optimization for extra strong tests.
while b > 1:
U = (U*V) % n
V = (V*V - 2) % n
b -= 1
if (k >> (b - 1)) & 1:
U, V = U*P + V, V*P + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
elif P == 1 and Q == -1:
# Small optimization for 50% of Selfridge parameters.
while b > 1:
U = (U*V) % n
if Qk == 1:
V = (V*V - 2) % n
else:
V = (V*V + 2) % n
Qk = 1
b -= 1
if (k >> (b-1)) & 1:
U, V = U + V, V + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
Qk = -1
else:
# The general case with any P and Q.
while b > 1:
U = (U*V) % n
V = (V*V - 2*Qk) % n
Qk *= Qk
b -= 1
if (k >> (b - 1)) & 1:
U, V = U*P + V, V*P + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
Qk *= Q
Qk %= n
return _int_tuple(U % n, V % n, Qk)
def _lucas_selfridge_params(n):
"""Calculates the Selfridge parameters (D, P, Q) for n. This is
method A from page 1401 of Baillie and Wagstaff.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
"""
from sympy.core import igcd
from sympy.ntheory.residue_ntheory import jacobi_symbol
D = 5
while True:
g = igcd(abs(D), n)
if g > 1 and g != n:
return (0, 0, 0)
if jacobi_symbol(D, n) == -1:
break
if D > 0:
D = -D - 2
else:
D = -D + 2
return _int_tuple(D, 1, (1 - D)/4)
def _lucas_extrastrong_params(n):
"""Calculates the "extra strong" parameters (D, P, Q) for n.
References
==========
- OEIS A217719: Extra Strong Lucas Pseudoprimes
https://oeis.org/A217719
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
"""
from sympy.core import igcd
from sympy.ntheory.residue_ntheory import jacobi_symbol
P, Q, D = 3, 1, 5
while True:
g = igcd(D, n)
if g > 1 and g != n:
return (0, 0, 0)
if jacobi_symbol(D, n) == -1:
break
P += 1
D = P*P - 4
return _int_tuple(D, P, Q)
def is_lucas_prp(n):
"""Standard Lucas compositeness test with Selfridge parameters. Returns
False if n is definitely composite, and True if n is a Lucas probable
prime.
This is typically used in combination with the Miller-Rabin test.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- OEIS A217120: Lucas Pseudoprimes
https://oeis.org/A217120
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_lucas_prp
>>> for i in range(10000):
... if is_lucas_prp(i) and not isprime(i):
... print(i)
323
377
1159
1829
3827
5459
5777
9071
9179
"""
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_selfridge_params(n)
if D == 0:
return False
U, V, Qk = _lucas_sequence(n, P, Q, n+1)
return U == 0
def is_strong_lucas_prp(n):
"""Strong Lucas compositeness test with Selfridge parameters. Returns
False if n is definitely composite, and True if n is a strong Lucas
probable prime.
This is often used in combination with the Miller-Rabin test, and
in particular, when combined with M-R base 2 creates the strong BPSW test.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- OEIS A217255: Strong Lucas Pseudoprimes
https://oeis.org/A217255
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
>>> for i in range(20000):
... if is_strong_lucas_prp(i) and not isprime(i):
... print(i)
5459
5777
10877
16109
18971
"""
from sympy.ntheory.factor_ import trailing
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_selfridge_params(n)
if D == 0:
return False
# remove powers of 2 from n+1 (= k * 2**s)
s = trailing(n + 1)
k = (n+1) >> s
U, V, Qk = _lucas_sequence(n, P, Q, k)
if U == 0 or V == 0:
return True
for r in range(1, s):
V = (V*V - 2*Qk) % n
if V == 0:
return True
Qk = pow(Qk, 2, n)
return False
def is_extra_strong_lucas_prp(n):
"""Extra Strong Lucas compositeness test. Returns False if n is
definitely composite, and True if n is a "extra strong" Lucas probable
prime.
The parameters are selected using P = 3, Q = 1, then incrementing P until
(D|n) == -1. The test itself is as defined in Grantham 2000, from the
Mo and Jones preprint. The parameter selection and test are the same as
used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
page on Wikipedia.
With these parameters, there are no counterexamples below 2^64 nor any
known above that range. It is 20-50% faster than the strong test.
Because of the different parameters selected, there is no relationship
between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
In particular, one is not a subset of the other.
References
==========
- "Frobenius Pseudoprimes", Jon Grantham, 2000.
http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/
- OEIS A217719: Extra Strong Lucas Pseudoprimes
https://oeis.org/A217719
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
>>> for i in range(20000):
... if is_extra_strong_lucas_prp(i) and not isprime(i):
... print(i)
989
3239
5777
10877
"""
# Implementation notes:
# 1) the parameters differ from Thomas R. Nicely's. His parameter
# selection leads to pseudoprimes that overlap M-R tests, and
# contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
# 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
# sequence must have Q=1. See Grantham theorem 2.3, any of the
# references on the MathWorld page, or run it and see Q=-1 is wrong.
from sympy.ntheory.factor_ import trailing
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_extrastrong_params(n)
if D == 0:
return False
# remove powers of 2 from n+1 (= k * 2**s)
s = trailing(n + 1)
k = (n+1) >> s
U, V, Qk = _lucas_sequence(n, P, Q, k)
if U == 0 and (V == 2 or V == n - 2):
return True
for r in range(1, s):
if V == 0:
return True
V = (V*V - 2) % n
return False
def isprime(n):
"""
Test if n is a prime number (True) or not (False). For n < 2^64 the
answer is definitive; larger n values have a small probability of actually
being pseudoprimes.
Negative numbers (e.g. -2) are not considered prime.
The first step is looking for trivial factors, which if found enables
a quick return. Next, if the sieve is large enough, use bisection search
on the sieve. For small numbers, a set of deterministic Miller-Rabin
tests are performed with bases that are known to have no counterexamples
in their range. Finally if the number is larger than 2^64, a strong
BPSW test is performed. While this is a probable prime test and we
believe counterexamples exist, there are no known counterexamples.
Examples
========
>>> from sympy.ntheory import isprime
>>> isprime(13)
True
>>> isprime(13.0) # limited precision
False
>>> isprime(15)
False
Notes
=====
This routine is intended only for integer input, not numerical
expressions which may represent numbers. Floats are also
rejected as input because they represent numbers of limited
precision. While it is tempting to permit 7.0 to represent an
integer there are errors that may "pass silently" if this is
allowed:
>>> from sympy import Float, S
>>> int(1e3) == 1e3 == 10**3
True
>>> int(1e23) == 1e23
True
>>> int(1e23) == 10**23
False
>>> near_int = 1 + S(1)/10**19
>>> near_int == int(near_int)
False
>>> n = Float(near_int, 10) # truncated by precision
>>> n == int(n)
True
>>> n = Float(near_int, 20)
>>> n == int(n)
False
See Also
========
sympy.ntheory.generate.primerange : Generates all primes in a given range
sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n
sympy.ntheory.generate.prime : Return the nth prime
References
==========
- https://en.wikipedia.org/wiki/Strong_pseudoprime
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
"""
try:
n = as_int(n)
except ValueError:
return False
# Step 1, do quick composite testing via trial division. The individual
# modulo tests benchmark faster than one or two primorial igcds for me.
# The point here is just to speedily handle small numbers and many
# composites. Step 2 only requires that n <= 2 get handled here.
if n in [2, 3, 5]:
return True
if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
return False
if n < 49:
return True
if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
(n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
(n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
return False
if n < 2809:
return True
if n <= 23001:
return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951]
# bisection search on the sieve if the sieve is large enough
from sympy.ntheory.generate import sieve as s
if n <= s._list[-1]:
l, u = s.search(n)
return l == u
# If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
# This should be a bit faster than our step 2, and for large values will
# be a lot faster than our step 3 (C+GMP vs. Python).
from sympy.core.compatibility import HAS_GMPY
if HAS_GMPY == 2:
from gmpy2 import is_strong_prp, is_strong_selfridge_prp
return is_strong_prp(n, 2) and is_strong_selfridge_prp(n)
# Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
# https://miller-rabin.appspot.com/
# for lists. We have made sure the M-R routine will successfully handle
# bases larger than n, so we can use the minimal set.
if n < 341531:
return mr(n, [9345883071009581737])
if n < 885594169:
return mr(n, [725270293939359937, 3569819667048198375])
if n < 350269456337:
return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
if n < 55245642489451:
return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
if n < 7999252175582851:
return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
if n < 585226005592931977:
return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
if n < 18446744073709551616:
return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
# We could do this instead at any point:
#if n < 18446744073709551616:
# return mr(n, [2]) and is_extra_strong_lucas_prp(n)
# Here are tests that are safe for MR routines that don't understand
# large bases.
#if n < 9080191:
# return mr(n, [31, 73])
#if n < 19471033:
# return mr(n, [2, 299417])
#if n < 38010307:
# return mr(n, [2, 9332593])
#if n < 316349281:
# return mr(n, [11000544, 31481107])
#if n < 4759123141:
# return mr(n, [2, 7, 61])
#if n < 105936894253:
# return mr(n, [2, 1005905886, 1340600841])
#if n < 31858317218647:
# return mr(n, [2, 642735, 553174392, 3046413974])
#if n < 3071837692357849:
# return mr(n, [2, 75088, 642735, 203659041, 3613982119])
#if n < 18446744073709551616:
# return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
# Step 3: BPSW.
#
# Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
# 44.0s old isprime using 46 bases
# 5.3s strong BPSW + one random base
# 4.3s extra strong BPSW + one random base
# 4.1s strong BPSW
# 3.2s extra strong BPSW
# Classic BPSW from page 1401 of the paper. See alternate ideas below.
return mr(n, [2]) and is_strong_lucas_prp(n)
# Using extra strong test, which is somewhat faster
#return mr(n, [2]) and is_extra_strong_lucas_prp(n)
# Add a random M-R base
#import random
#return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
def is_gaussian_prime(num):
r"""Test if num is a Gaussian prime number.
References
==========
.. [1] https://oeis.org/wiki/Gaussian_primes
"""
from sympy import sympify
num = sympify(num)
a, b = num.as_real_imag()
a = as_int(a, strict=False)
b = as_int(b, strict=False)
if a == 0:
b = abs(b)
return isprime(b) and b % 4 == 3
elif b == 0:
a = abs(a)
return isprime(a) and a % 4 == 3
return isprime(a**2 + b**2)
|
a98d56046b193285dec29f711f1e5a3f98bf00f2e70dddfd8b9b775b701f06e7 | from sympy.core.numbers import igcd, mod_inverse
from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
from sympy.ntheory import isprime
from math import log, sqrt
import random
rgen = random.Random()
class SievePolynomial:
def __init__(self, modified_coeff=[], a=None, b=None):
"""This class denotes the seive polynomial.
If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded
to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient
is stored in the form `[a**2, 2*a*b, b**2 - N]`. This
ensures faster `eval` method because we dont have to
perform `a**2, 2*a*b, b**2` every time we call the
`eval` method. As multiplication is more expensive
than addition, by using modified_coefficient we get
a faster seiving process.
Parameters
==========
modified_coeff : modified_coefficient of sieve polynomial
a : parameter of the sieve polynomial
b : parameter of the sieve polynomial
"""
self.modified_coeff = modified_coeff
self.a = a
self.b = b
def eval(self, x):
"""
Compute the value of the sieve polynomial at point x.
Parameters
==========
x : Integer parameter for sieve polynomial
"""
ans = 0
for coeff in self.modified_coeff:
ans *= x
ans += coeff
return ans
class FactorBaseElem:
"""This class stores an element of the `factor_base`.
"""
def __init__(self, prime, tmem_p, log_p):
"""
Initialization of factor_base_elem.
Parameters
==========
prime : prime number of the factor_base
tmem_p : Integer square root of x**2 = n mod prime
log_p : Compute Natural Logarithm of the prime
"""
self.prime = prime
self.tmem_p = tmem_p
self.log_p = log_p
self.soln1 = None
self.soln2 = None
self.a_inv = None
self.b_ainv = None
def _generate_factor_base(prime_bound, n):
"""Generate `factor_base` for Quadratic Sieve. The `factor_base`
consists of all the the points whose ``legendre_symbol(n, p) == 1``
and ``p < num_primes``. Along with the prime `factor_base` also stores
natural logarithm of prime and the residue n modulo p.
It also returns the of primes numbers in the `factor_base` which are
close to 1000 and 5000.
Parameters
==========
prime_bound : upper prime bound of the factor_base
n : integer to be factored
"""
from sympy import sieve
factor_base = []
idx_1000, idx_5000 = None, None
for prime in sieve.primerange(1, prime_bound):
if pow(n, (prime - 1) // 2, prime) == 1:
if prime > 1000 and idx_1000 is None:
idx_1000 = len(factor_base) - 1
if prime > 5000 and idx_5000 is None:
idx_5000 = len(factor_base) - 1
residue = _sqrt_mod_prime_power(n, prime, 1)[0]
log_p = round(log(prime)*2**10)
factor_base.append(FactorBaseElem(prime, residue, log_p))
return idx_1000, idx_5000, factor_base
def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None):
"""This step is the initialization of the 1st sieve polynomial.
Here `a` is selected as a product of several primes of the factor_base
such that `a` is about to ``sqrt(2*N) / M``. Other initial values of
factor_base elem are also intialized which includes a_inv, b_ainv, soln1,
soln2 which are used when the sieve polynomial is changed. The b_ainv
is required for fast polynomial change as we don't have to calculate
`2*b*mod_inverse(a, prime)` every time.
We also ensure that the `factor_base` primes which make `a` are between
1000 and 5000.
Parameters
==========
N : Number to be factored
M : sieve interval
factor_base : factor_base primes
idx_1000 : index of prime numbe in the factor_base near 1000
idx_5000 : index of primenumber in the factor_base near to 5000
seed : Generate pseudoprime numbers
"""
if seed is not None:
rgen.seed(seed)
approx_val = sqrt(2*N) / M
# `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a`
# randomly search for a combination of primes whose multiplication is close to approx_val
# This multiplication of primes will be `a` and the primes will be `q`
# `best_a` denotes that `a` is close to approx_val in the random search of combination
best_a, best_q, best_ratio = None, None, None
start = 0 if idx_1000 is None else idx_1000
end = len(factor_base) - 1 if idx_5000 is None else idx_5000
for _ in range(50):
a = 1
q = []
while(a < approx_val):
rand_p = 0
while(rand_p == 0 or rand_p in q):
rand_p = rgen.randint(start, end)
p = factor_base[rand_p].prime
a *= p
q.append(rand_p)
ratio = a / approx_val
if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
best_q = q
best_a = a
best_ratio = ratio
a = best_a
q = best_q
B = []
for idx, val in enumerate(q):
q_l = factor_base[val].prime
gamma = factor_base[val].tmem_p * mod_inverse(a // q_l, q_l) % q_l
if gamma > q_l / 2:
gamma = q_l - gamma
B.append(a//q_l*gamma)
b = sum(B)
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
for fb in factor_base:
if a % fb.prime == 0:
continue
fb.a_inv = mod_inverse(a, fb.prime)
fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B]
fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime
fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime
return g, B
def _initialize_ith_poly(N, factor_base, i, g, B):
"""Initialization stage of ith poly. After we finish sieving 1`st polynomial
here we quickly change to the next polynomial from which we will again
start sieving. Suppose we generated ith sieve polynomial and now we
want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1``
where `j` is the number of prime factors of the coefficient `a`
then this function can be used to go to the next polynomial. If
``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage.
Parameters
==========
N : number to be factored
factor_base : factor_base primes
i : integer denoting ith polynomial
g : (i - 1)th polynomial
B : array that stores a//q_l*gamma
"""
from sympy import ceiling
v = 1
j = i
while(j % 2 == 0):
v += 1
j //= 2
if ceiling(i / (2**v)) % 2 == 1:
neg_pow = -1
else:
neg_pow = 1
b = g.b + 2*neg_pow*B[v - 1]
a = g.a
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
for fb in factor_base:
if a % fb.prime == 0:
continue
fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
return g
def _gen_sieve_array(M, factor_base):
"""Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
that doesn't divide the coefficient `a` we add log_p over the sieve_array
such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
is an integer. When p = 2 then log_p is only added using
``-M <= soln1 + i*p <= M``.
Parameters
==========
M : sieve interval
factor_base : factor_base primes
"""
sieve_array = [0]*(2*M + 1)
for factor in factor_base:
if factor.soln1 is None: #The prime does not divides a
continue
for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
sieve_array[idx] += factor.log_p
if factor.prime == 2:
continue
#if prime is 2 then sieve only with soln_1_p
for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
sieve_array[idx] += factor.log_p
return sieve_array
def _check_smoothness(num, factor_base):
"""Here we check that if `num` is a smooth number or not. If `a` is a smooth
number then it returns a vector of prime exponents modulo 2. For example
if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then
`a` is a smooth number and this function returns ([1, 0, 0, 1], True). If
`a` is a partial relation which means that `a` a has one prime factor
greater than the `factor_base` then it returns `(a, False)` which denotes `a`
is a partial relation.
Parameters
==========
a : integer whose smootheness is to be checked
factor_base : factor_base primes
"""
vec = []
if num < 0:
vec.append(1)
num *= -1
else:
vec.append(0)
#-1 is not included in factor_base add -1 in vector
for factor in factor_base:
if num % factor.prime != 0:
vec.append(0)
continue
factor_exp = 0
while num % factor.prime == 0:
factor_exp += 1
num //= factor.prime
vec.append(factor_exp % 2)
if num == 1:
return vec, True
if isprime(num):
return num, False
return None, None
def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
"""Trial division stage. Here we trial divide the values generetated
by sieve_poly in the sieve interval and if it is a smooth number then
it is stored in `smooth_relations`. Moreover, if we find two partial relations
with same large prime then they are combined to form a smooth relation.
First we iterate over sieve array and look for values which are greater
than accumulated_val, as these values have a high chance of being smooth
number. Then using these values we find smooth relations.
In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
to form a smooth relation.
Parameters
==========
N : Number to be factored
M : sieve interval
factor_base : factor_base primes
sieve_array : stores log_p values
sieve_poly : polynomial from which we find smooth relations
partial_relations : stores partial relations with one large prime
ERROR_TERM : error term for accumulated_val
"""
sqrt_n = sqrt(float(N))
accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM
smooth_relations = []
proper_factor = set()
partial_relation_upper_bound = 128*factor_base[-1].prime
for idx, val in enumerate(sieve_array):
if val < accumulated_val:
continue
x = idx - M
v = sieve_poly.eval(x)
vec, is_smooth = _check_smoothness(v, factor_base)
if is_smooth is None:#Neither smooth nor partial
continue
u = sieve_poly.a*x + sieve_poly.b
# Update the partial relation
# If 2 partial relation with same large prime is found then generate smooth relation
if is_smooth is False:#partial relation found
large_prime = vec
#Consider the large_primes under 128*F
if large_prime > partial_relation_upper_bound:
continue
if large_prime not in partial_relations:
partial_relations[large_prime] = (u, v)
continue
else:
u_prev, v_prev = partial_relations[large_prime]
partial_relations.pop(large_prime)
try:
large_prime_inv = mod_inverse(large_prime, N)
except ValueError:#if large_prine divides N
proper_factor.add(large_prime)
continue
u = u*u_prev*large_prime_inv
v = v*v_prev // (large_prime*large_prime)
vec, is_smooth = _check_smoothness(v, factor_base)
#assert u*u % N == v % N
smooth_relations.append((u, v, vec))
return smooth_relations, proper_factor
#LINEAR ALGEBRA STAGE
def _build_matrix(smooth_relations):
"""Build a 2D matrix from smooth relations.
Parameters
==========
smooth_relations : Stores smooth relations
"""
matrix = []
for s_relation in smooth_relations:
matrix.append(s_relation[2])
return matrix
def _gauss_mod_2(A):
"""Fast gaussian reduction for modulo 2 matrix.
Parameters
==========
A : Matrix
Examples
========
>>> from sympy.ntheory.qs import _gauss_mod_2
>>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]])
([[[1, 0, 1], 3]],
[True, True, True, False],
[[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]])
Reference
==========
.. [1] A fast algorithm for gaussian elimination over GF(2) and
its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige"""
import copy
matrix = copy.deepcopy(A)
row = len(matrix)
col = len(matrix[0])
mark = [False]*row
for c in range(col):
for r in range(row):
if matrix[r][c] == 1:
break
mark[r] = True
for c1 in range(col):
if c1 == c:
continue
if matrix[r][c1] == 1:
for r2 in range(row):
matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2
dependent_row = []
for idx, val in enumerate(mark):
if val == False:
dependent_row.append([matrix[idx], idx])
return dependent_row, mark, matrix
def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N):
"""Finds proper factor of N. Here, transform the dependent rows as a
combination of independent rows of the gauss_matrix to form the desired
relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation
we obtain a proper factor of N by `gcd(X - Y, N)`.
Parameters
==========
dependent_rows : denoted dependent rows in the reduced matrix form
mark : boolean array to denoted dependent and independent rows
gauss_matrix : Reduced form of the smooth relations matrix
index : denoted the index of the dependent_rows
smooth_relations : Smooth relations vectors matrix
N : Number to be factored
"""
from sympy import integer_nthroot
idx_in_smooth = dependent_rows[index][1]
independent_u = [smooth_relations[idx_in_smooth][0]]
independent_v = [smooth_relations[idx_in_smooth][1]]
dept_row = dependent_rows[index][0]
for idx, val in enumerate(dept_row):
if val == 1:
for row in range(len(gauss_matrix)):
if gauss_matrix[row][idx] == 1 and mark[row] == True:
independent_u.append(smooth_relations[row][0])
independent_v.append(smooth_relations[row][1])
break
u = 1
v = 1
for i in independent_u:
u *= i
for i in independent_v:
v *= i
#assert u**2 % N == v % N
v = integer_nthroot(v, 2)[0]
return igcd(u - v, N)
def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
"""Performs factorization using Self-Initializing Quadratic Sieve.
In SIQS, let N be a number to be factored, and this N should not be a
perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
In order to find these integers X and Y we try to find relations of form
t**2 = u modN where u is a product of small primes. If we have enough of
these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
Here, several optimizations are done like using muliple polynomials for
sieving, fast changing between polynomials and using partial relations.
The use of partial relations can speeds up the factoring by 2 times.
Parameters
==========
N : Number to be Factored
prime_bound : upper bound for primes in the factor base
M : Sieve Interval
ERROR_TERM : Error term for checking smoothness
threshold : Extra smooth relations for factorization
seed : generate pseudo prime numbers
Examples
========
>>> from sympy.ntheory import qs
>>> qs(25645121643901801, 2000, 10000)
{5394769, 4753701529}
>>> qs(9804659461513846513, 2000, 10000)
{4641991, 2112166839943}
References
==========
.. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
.. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
"""
ERROR_TERM*=2**10
rgen.seed(seed)
idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
smooth_relations = []
ith_poly = 0
partial_relations = {}
proper_factor = set()
threshold = 5*len(factor_base) // 100
while True:
if ith_poly == 0:
ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000)
else:
ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array)
ith_poly += 1
if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial
ith_poly = 0
sieve_array = _gen_sieve_array(M, factor_base)
s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM)
smooth_relations += s_rel
proper_factor |= p_f
if len(smooth_relations) >= len(factor_base) + threshold:
break
matrix = _build_matrix(smooth_relations)
dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix)
N_copy = N
for index in range(len(dependent_row)):
factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N)
if factor > 1 and factor < N:
proper_factor.add(factor)
while(N_copy % factor == 0):
N_copy //= factor
if isprime(N_copy):
proper_factor.add(N_copy)
break
if(N_copy == 1):
break
return proper_factor
|
49c1ac5fc98dcf6a98f9b965c963ccf1f848397806831f3d61cb09ecbea77e74 | from collections import defaultdict
from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify,
expand_func, Function, Dummy, Expr, factor_terms,
expand_power_exp, Eq)
from sympy.core.compatibility import iterable, ordered, as_int
from sympy.core.parameters import global_parameters
from sympy.core.function import (expand_log, count_ops, _mexpand, _coeff_isneg,
nfloat, expand_mul)
from sympy.core.numbers import Float, I, pi, Rational, Integer
from sympy.core.relational import Relational
from sympy.core.rules import Transform
from sympy.core.sympify import _sympify
from sympy.functions import gamma, exp, sqrt, log, exp_polar, re
from sympy.functions.combinatorial.factorials import CombinatorialFunction
from sympy.functions.elementary.complexes import unpolarify, Abs
from sympy.functions.elementary.exponential import ExpBase
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.functions.special.bessel import besselj, besseli, besselk, jn, bessely
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import together, cancel, factor
from sympy.simplify.combsimp import combsimp
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import radsimp, fraction, collect_abs
from sympy.simplify.sqrtdenest import sqrtdenest
from sympy.simplify.trigsimp import trigsimp, exptrigsimp
from sympy.utilities.iterables import has_variety, sift
import mpmath
def separatevars(expr, symbols=[], dict=False, force=False):
"""
Separates variables in an expression, if possible. By
default, it separates with respect to all symbols in an
expression and collects constant coefficients that are
independent of symbols.
Explanation
===========
If ``dict=True`` then the separated terms will be returned
in a dictionary keyed to their corresponding symbols.
By default, all symbols in the expression will appear as
keys; if symbols are provided, then all those symbols will
be used as keys, and any terms in the expression containing
other symbols or non-symbols will be returned keyed to the
string 'coeff'. (Passing None for symbols will return the
expression in a dictionary keyed to 'coeff'.)
If ``force=True``, then bases of powers will be separated regardless
of assumptions on the symbols involved.
Notes
=====
The order of the factors is determined by Mul, so that the
separated expressions may not necessarily be grouped together.
Although factoring is necessary to separate variables in some
expressions, it is not necessary in all cases, so one should not
count on the returned factors being factored.
Examples
========
>>> from sympy.abc import x, y, z, alpha
>>> from sympy import separatevars, sin
>>> separatevars((x*y)**y)
(x*y)**y
>>> separatevars((x*y)**y, force=True)
x**y*y**y
>>> e = 2*x**2*z*sin(y)+2*z*x**2
>>> separatevars(e)
2*x**2*z*(sin(y) + 1)
>>> separatevars(e, symbols=(x, y), dict=True)
{'coeff': 2*z, x: x**2, y: sin(y) + 1}
>>> separatevars(e, [x, y, alpha], dict=True)
{'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1}
If the expression is not really separable, or is only partially
separable, separatevars will do the best it can to separate it
by using factoring.
>>> separatevars(x + x*y - 3*x**2)
-x*(3*x - y - 1)
If the expression is not separable then expr is returned unchanged
or (if dict=True) then None is returned.
>>> eq = 2*x + y*sin(x)
>>> separatevars(eq) == eq
True
>>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None
True
"""
expr = sympify(expr)
if dict:
return _separatevars_dict(_separatevars(expr, force), symbols)
else:
return _separatevars(expr, force)
def _separatevars(expr, force):
if isinstance(expr, Abs):
arg = expr.args[0]
if arg.is_Mul and not arg.is_number:
s = separatevars(arg, dict=True, force=force)
if s is not None:
return Mul(*map(expr.func, s.values()))
else:
return expr
if len(expr.free_symbols) < 2:
return expr
# don't destroy a Mul since much of the work may already be done
if expr.is_Mul:
args = list(expr.args)
changed = False
for i, a in enumerate(args):
args[i] = separatevars(a, force)
changed = changed or args[i] != a
if changed:
expr = expr.func(*args)
return expr
# get a Pow ready for expansion
if expr.is_Pow:
expr = Pow(separatevars(expr.base, force=force), expr.exp)
# First try other expansion methods
expr = expr.expand(mul=False, multinomial=False, force=force)
_expr, reps = posify(expr) if force else (expr, {})
expr = factor(_expr).subs(reps)
if not expr.is_Add:
return expr
# Find any common coefficients to pull out
args = list(expr.args)
commonc = args[0].args_cnc(cset=True, warn=False)[0]
for i in args[1:]:
commonc &= i.args_cnc(cset=True, warn=False)[0]
commonc = Mul(*commonc)
commonc = commonc.as_coeff_Mul()[1] # ignore constants
commonc_set = commonc.args_cnc(cset=True, warn=False)[0]
# remove them
for i, a in enumerate(args):
c, nc = a.args_cnc(cset=True, warn=False)
c = c - commonc_set
args[i] = Mul(*c)*Mul(*nc)
nonsepar = Add(*args)
if len(nonsepar.free_symbols) > 1:
_expr = nonsepar
_expr, reps = posify(_expr) if force else (_expr, {})
_expr = (factor(_expr)).subs(reps)
if not _expr.is_Add:
nonsepar = _expr
return commonc*nonsepar
def _separatevars_dict(expr, symbols):
if symbols:
if not all(t.is_Atom for t in symbols):
raise ValueError("symbols must be Atoms.")
symbols = list(symbols)
elif symbols is None:
return {'coeff': expr}
else:
symbols = list(expr.free_symbols)
if not symbols:
return None
ret = {i: [] for i in symbols + ['coeff']}
for i in Mul.make_args(expr):
expsym = i.free_symbols
intersection = set(symbols).intersection(expsym)
if len(intersection) > 1:
return None
if len(intersection) == 0:
# There are no symbols, so it is part of the coefficient
ret['coeff'].append(i)
else:
ret[intersection.pop()].append(i)
# rebuild
for k, v in ret.items():
ret[k] = Mul(*v)
return ret
def _is_sum_surds(p):
args = p.args if p.is_Add else [p]
for y in args:
if not ((y**2).is_Rational and y.is_extended_real):
return False
return True
def posify(eq):
"""Return ``eq`` (with generic symbols made positive) and a
dictionary containing the mapping between the old and new
symbols.
Explanation
===========
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
processing of expressions, especially those involving powers and
logarithms.
A dictionary that can be sent to subs to restore ``eq`` to its original
symbols is also returned.
>>> from sympy import posify, Symbol, log, solve
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
>>> eq = 1/x
>>> log(eq).expand()
log(1/x)
>>> log(posify(eq)[0]).expand()
-log(_x)
>>> p, rep = posify(eq)
>>> log(p).expand().subs(rep)
-log(x)
It is possible to apply the same transformations to an iterable
of expressions:
>>> eq = x**2 - 4
>>> solve(eq, x)
[-2, 2]
>>> eq_x, reps = posify([eq, x]); eq_x
[_x**2 - 4, _x]
>>> solve(*eq_x)
[2]
"""
eq = sympify(eq)
if iterable(eq):
f = type(eq)
eq = list(eq)
syms = set()
for e in eq:
syms = syms.union(e.atoms(Symbol))
reps = {}
for s in syms:
reps.update({v: k for k, v in posify(s)[1].items()})
for i, e in enumerate(eq):
eq[i] = e.subs(reps)
return f(eq), {r: s for s, r in reps.items()}
reps = {s: Dummy(s.name, positive=True, **s.assumptions0)
for s in eq.free_symbols if s.is_positive is None}
eq = eq.subs(reps)
return eq, {r: s for s, r in reps.items()}
def hypersimp(f, k):
"""Given combinatorial term f(k) simplify its consecutive term ratio
i.e. f(k+1)/f(k). The input term can be composed of functions and
integer sequences which have equivalent representation in terms
of gamma special function.
Explanation
===========
The algorithm performs three basic steps:
1. Rewrite all functions in terms of gamma, if possible.
2. Rewrite all occurrences of gamma in terms of products
of gamma and rising factorial with integer, absolute
constant exponent.
3. Perform simplification of nested fractions, powers
and if the resulting expression is a quotient of
polynomials, reduce their total degree.
If f(k) is hypergeometric then as result we arrive with a
quotient of polynomials of minimal degree. Otherwise None
is returned.
For more information on the implemented algorithm refer to:
1. W. Koepf, Algorithms for m-fold Hypergeometric Summation,
Journal of Symbolic Computation (1995) 20, 399-417
"""
f = sympify(f)
g = f.subs(k, k + 1) / f
g = g.rewrite(gamma)
if g.has(Piecewise):
g = piecewise_fold(g)
g = g.args[-1][0]
g = expand_func(g)
g = powsimp(g, deep=True, combine='exp')
if g.is_rational_function(k):
return simplify(g, ratio=S.Infinity)
else:
return None
def hypersimilar(f, g, k):
"""
Returns True if ``f`` and ``g`` are hyper-similar.
Explanation
===========
Similarity in hypergeometric sense means that a quotient of
f(k) and g(k) is a rational function in ``k``. This procedure
is useful in solving recurrence relations.
For more information see hypersimp().
"""
f, g = list(map(sympify, (f, g)))
h = (f/g).rewrite(gamma)
h = h.expand(func=True, basic=False)
return h.is_rational_function(k)
def signsimp(expr, evaluate=None):
"""Make all Add sub-expressions canonical wrt sign.
Explanation
===========
If an Add subexpression, ``a``, can have a sign extracted,
as determined by could_extract_minus_sign, it is replaced
with Mul(-1, a, evaluate=False). This allows signs to be
extracted from powers and products.
Examples
========
>>> from sympy import signsimp, exp, symbols
>>> from sympy.abc import x, y
>>> i = symbols('i', odd=True)
>>> n = -1 + 1/x
>>> n/x/(-n)**2 - 1/n/x
(-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x))
>>> signsimp(_)
0
>>> x*n + x*-n
x*(-1 + 1/x) + x*(1 - 1/x)
>>> signsimp(_)
0
Since powers automatically handle leading signs
>>> (-2)**i
-2**i
signsimp can be used to put the base of a power with an integer
exponent into canonical form:
>>> n**i
(-1 + 1/x)**i
By default, signsimp doesn't leave behind any hollow simplification:
if making an Add canonical wrt sign didn't change the expression, the
original Add is restored. If this is not desired then the keyword
``evaluate`` can be set to False:
>>> e = exp(y - x)
>>> signsimp(e) == e
True
>>> signsimp(e, evaluate=False)
exp(-(x - y))
"""
if evaluate is None:
evaluate = global_parameters.evaluate
expr = sympify(expr)
if not isinstance(expr, (Expr, Relational)) or expr.is_Atom:
return expr
e = sub_post(sub_pre(expr))
if not isinstance(e, (Expr, Relational)) or e.is_Atom:
return e
if e.is_Add:
return e.func(*[signsimp(a, evaluate) for a in e.args])
if evaluate:
e = e.xreplace({m: -(-m) for m in e.atoms(Mul) if -(-m) != m})
return e
def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs):
"""Simplifies the given expression.
Explanation
===========
Simplification is not a well defined term and the exact strategies
this function tries can change in the future versions of SymPy. If
your algorithm relies on "simplification" (whatever it is), try to
determine what you need exactly - is it powsimp()?, radsimp()?,
together()?, logcombine()?, or something else? And use this particular
function directly, because those are well defined and thus your algorithm
will be robust.
Nonetheless, especially for interactive use, or when you don't know
anything about the structure of the expression, simplify() tries to apply
intelligent heuristics to make the input expression "simpler". For
example:
>>> from sympy import simplify, cos, sin
>>> from sympy.abc import x, y
>>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
>>> a
(x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
>>> simplify(a)
x + 1
Note that we could have obtained the same result by using specific
simplification functions:
>>> from sympy import trigsimp, cancel
>>> trigsimp(a)
(x**2 + x)/x
>>> cancel(_)
x + 1
In some cases, applying :func:`simplify` may actually result in some more
complicated expression. The default ``ratio=1.7`` prevents more extreme
cases: if (result length)/(input length) > ratio, then input is returned
unmodified. The ``measure`` parameter lets you specify the function used
to determine how complex an expression is. The function should take a
single argument as an expression and return a number such that if
expression ``a`` is more complex than expression ``b``, then
``measure(a) > measure(b)``. The default measure function is
:func:`~.count_ops`, which returns the total number of operations in the
expression.
For example, if ``ratio=1``, ``simplify`` output can't be longer
than input.
::
>>> from sympy import sqrt, simplify, count_ops, oo
>>> root = 1/(sqrt(2)+3)
Since ``simplify(root)`` would result in a slightly longer expression,
root is returned unchanged instead::
>>> simplify(root, ratio=1) == root
True
If ``ratio=oo``, simplify will be applied anyway::
>>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
True
Note that the shortest expression is not necessary the simplest, so
setting ``ratio`` to 1 may not be a good idea.
Heuristically, the default value ``ratio=1.7`` seems like a reasonable
choice.
You can easily define your own measure function based on what you feel
should represent the "size" or "complexity" of the input expression. Note
that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
good metrics, but have other problems (in this case, the measure function
may slow down simplify too much for very large expressions). If you don't
know what a good metric would be, the default, ``count_ops``, is a good
one.
For example:
>>> from sympy import symbols, log
>>> a, b = symbols('a b', positive=True)
>>> g = log(a) + log(b) + log(a)*log(1/b)
>>> h = simplify(g)
>>> h
log(a*b**(1 - log(a)))
>>> count_ops(g)
8
>>> count_ops(h)
5
So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
However, we may not like how ``simplify`` (in this case, using
``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way
to reduce this would be to give more weight to powers as operations in
``count_ops``. We can do this by using the ``visual=True`` option:
>>> print(count_ops(g, visual=True))
2*ADD + DIV + 4*LOG + MUL
>>> print(count_ops(h, visual=True))
2*LOG + MUL + POW + SUB
>>> from sympy import Symbol, S
>>> def my_measure(expr):
... POW = Symbol('POW')
... # Discourage powers by giving POW a weight of 10
... count = count_ops(expr, visual=True).subs(POW, 10)
... # Every other operation gets a weight of 1 (the default)
... count = count.replace(Symbol, type(S.One))
... return count
>>> my_measure(g)
8
>>> my_measure(h)
14
>>> 15./8 > 1.7 # 1.7 is the default ratio
True
>>> simplify(g, measure=my_measure)
-log(a)*log(b) + log(a) + log(b)
Note that because ``simplify()`` internally tries many different
simplification strategies and then compares them using the measure
function, we get a completely different result that is still different
from the input expression by doing this.
If ``rational=True``, Floats will be recast as Rationals before simplification.
If ``rational=None``, Floats will be recast as Rationals but the result will
be recast as Floats. If rational=False(default) then nothing will be done
to the Floats.
If ``inverse=True``, it will be assumed that a composition of inverse
functions, such as sin and asin, can be cancelled in any order.
For example, ``asin(sin(x))`` will yield ``x`` without checking whether
x belongs to the set where this relation is true. The default is
False.
Note that ``simplify()`` automatically calls ``doit()`` on the final
expression. You can avoid this behavior by passing ``doit=False`` as
an argument.
Also, it should be noted that simplifying the boolian expression is not
well defined. If the expression prefers automatic evaluation (such as
:obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or
``False`` if truth value can be determined. If the expression is not
evaluated by default (such as :obj:`~.Predicate()`), simplification will
not reduce it and you should use :func:`~.refine()` or :func:`~.ask()`
function. This inconsistency will be resolved in future version.
See Also
========
sympy.assumptions.refine.refine : Simplification using assumptions.
sympy.assumptions.ask.ask : Query for boolean expressions using assumptions.
"""
def shorter(*choices):
"""
Return the choice that has the fewest ops. In case of a tie,
the expression listed first is selected.
"""
if not has_variety(choices):
return choices[0]
return min(choices, key=measure)
def done(e):
rv = e.doit() if doit else e
return shorter(rv, collect_abs(rv))
expr = sympify(expr)
kwargs = dict(
ratio=kwargs.get('ratio', ratio),
measure=kwargs.get('measure', measure),
rational=kwargs.get('rational', rational),
inverse=kwargs.get('inverse', inverse),
doit=kwargs.get('doit', doit))
# no routine for Expr needs to check for is_zero
if isinstance(expr, Expr) and expr.is_zero:
return S.Zero
_eval_simplify = getattr(expr, '_eval_simplify', None)
if _eval_simplify is not None:
return _eval_simplify(**kwargs)
original_expr = expr = collect_abs(signsimp(expr))
if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack
return expr
if inverse and expr.has(Function):
expr = inversecombine(expr)
if not expr.args: # simplified to atomic
return expr
# do deep simplification
handled = Add, Mul, Pow, ExpBase
expr = expr.replace(
# here, checking for x.args is not enough because Basic has
# args but Basic does not always play well with replace, e.g.
# when simultaneous is True found expressions will be masked
# off with a Dummy but not all Basic objects in an expression
# can be replaced with a Dummy
lambda x: isinstance(x, Expr) and x.args and not isinstance(
x, handled),
lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]),
simultaneous=False)
if not isinstance(expr, handled):
return done(expr)
if not expr.is_commutative:
expr = nc_simplify(expr)
# TODO: Apply different strategies, considering expression pattern:
# is it a purely rational function? Is there any trigonometric function?...
# See also https://github.com/sympy/sympy/pull/185.
# rationalize Floats
floats = False
if rational is not False and expr.has(Float):
floats = True
expr = nsimplify(expr, rational=True)
expr = bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)())
expr = Mul(*powsimp(expr).as_content_primitive())
_e = cancel(expr)
expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829
expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))
if ratio is S.Infinity:
expr = expr2
else:
expr = shorter(expr2, expr1, expr)
if not isinstance(expr, Basic): # XXX: temporary hack
return expr
expr = factor_terms(expr, sign=False)
from sympy.simplify.hyperexpand import hyperexpand
from sympy.functions.special.bessel import BesselBase
from sympy import Sum, Product, Integral
from sympy.functions.elementary.complexes import sign
# must come before `Piecewise` since this introduces more `Piecewise` terms
if expr.has(sign):
expr = expr.rewrite(Abs)
# Deal with Piecewise separately to avoid recursive growth of expressions
if expr.has(Piecewise):
# Fold into a single Piecewise
expr = piecewise_fold(expr)
# Apply doit, if doit=True
expr = done(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Fold into a single Piecewise, in case doit lead to some
# expressions being Piecewise
expr = piecewise_fold(expr)
# kroneckersimp also affects Piecewise
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
# Still a Piecewise?
if expr.has(Piecewise):
from sympy.functions.elementary.piecewise import piecewise_simplify
# Do not apply doit on the segments as it has already
# been done above, but simplify
expr = piecewise_simplify(expr, deep=True, doit=False)
# Still a Piecewise?
if expr.has(Piecewise):
# Try factor common terms
expr = shorter(expr, factor_terms(expr))
# As all expressions have been simplified above with the
# complete simplify, nothing more needs to be done here
return expr
# hyperexpand automatically only works on hypergeometric terms
# Do this after the Piecewise part to avoid recursive expansion
expr = hyperexpand(expr)
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
if expr.has(BesselBase):
expr = besselsimp(expr)
if expr.has(TrigonometricFunction, HyperbolicFunction):
expr = trigsimp(expr, deep=True)
if expr.has(log):
expr = shorter(expand_log(expr, deep=True), logcombine(expr))
if expr.has(CombinatorialFunction, gamma):
# expression with gamma functions or non-integer arguments is
# automatically passed to gammasimp
expr = combsimp(expr)
if expr.has(Sum):
expr = sum_simplify(expr, **kwargs)
if expr.has(Integral):
expr = expr.xreplace({
i: factor_terms(i) for i in expr.atoms(Integral)})
if expr.has(Product):
expr = product_simplify(expr)
from sympy.physics.units import Quantity
from sympy.physics.units.util import quantity_simplify
if expr.has(Quantity):
expr = quantity_simplify(expr)
short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
short = shorter(short, cancel(short))
short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):
short = exptrigsimp(short)
# get rid of hollow 2-arg Mul factorization
hollow_mul = Transform(
lambda x: Mul(*x.args),
lambda x:
x.is_Mul and
len(x.args) == 2 and
x.args[0].is_Number and
x.args[1].is_Add and
x.is_commutative)
expr = short.xreplace(hollow_mul)
numer, denom = expr.as_numer_denom()
if denom.is_Add:
n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
if n is not S.One:
expr = (numer*n).expand()/d
if expr.could_extract_minus_sign():
n, d = fraction(expr)
if d != 0:
expr = signsimp(-n/(-d))
if measure(expr) > ratio*measure(original_expr):
expr = original_expr
# restore floats
if floats and rational is None:
expr = nfloat(expr, exponent=False)
return done(expr)
def sum_simplify(s, **kwargs):
"""Main function for Sum simplification"""
from sympy.concrete.summations import Sum
from sympy.core.function import expand
if not isinstance(s, Add):
s = s.xreplace({a: sum_simplify(a, **kwargs)
for a in s.atoms(Add) if a.has(Sum)})
s = expand(s)
if not isinstance(s, Add):
return s
terms = s.args
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
sum_terms, other = sift(Mul.make_args(term),
lambda i: isinstance(i, Sum), binary=True)
if not sum_terms:
o_t.append(term)
continue
other = [Mul(*other)]
s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms])))
result = Add(sum_combine(s_t), *o_t)
return result
def sum_combine(s_t):
"""Helper function for Sum simplification
Attempts to simplify a list of sums, by combining limits / sum function's
returns the simplified sum
"""
from sympy.concrete.summations import Sum
used = [False] * len(s_t)
for method in range(2):
for i, s_term1 in enumerate(s_t):
if not used[i]:
for j, s_term2 in enumerate(s_t):
if not used[j] and i != j:
temp = sum_add(s_term1, s_term2, method)
if isinstance(temp, Sum) or isinstance(temp, Mul):
s_t[i] = temp
s_term1 = s_t[i]
used[j] = True
result = S.Zero
for i, s_term in enumerate(s_t):
if not used[i]:
result = Add(result, s_term)
return result
def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True):
"""Return Sum with constant factors extracted.
If ``limits`` is specified then ``self`` is the summand; the other
keywords are passed to ``factor_terms``.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> from sympy.simplify.simplify import factor_sum
>>> s = Sum(x*y, (x, 1, 3))
>>> factor_sum(s)
y*Sum(x, (x, 1, 3))
>>> factor_sum(s.function, s.limits)
y*Sum(x, (x, 1, 3))
"""
# XXX deprecate in favor of direct call to factor_terms
from sympy.concrete.summations import Sum
kwargs = dict(radical=radical, clear=clear,
fraction=fraction, sign=sign)
expr = Sum(self, *limits) if limits else self
return factor_terms(expr, **kwargs)
def sum_add(self, other, method=0):
"""Helper function for Sum simplification"""
from sympy.concrete.summations import Sum
from sympy import Mul
#we know this is something in terms of a constant * a sum
#so we temporarily put the constants inside for simplification
#then simplify the result
def __refactor(val):
args = Mul.make_args(val)
sumv = next(x for x in args if isinstance(x, Sum))
constant = Mul(*[x for x in args if x != sumv])
return Sum(constant * sumv.function, *sumv.limits)
if isinstance(self, Mul):
rself = __refactor(self)
else:
rself = self
if isinstance(other, Mul):
rother = __refactor(other)
else:
rother = other
if type(rself) == type(rother):
if method == 0:
if rself.limits == rother.limits:
return factor_sum(Sum(rself.function + rother.function, *rself.limits))
elif method == 1:
if simplify(rself.function - rother.function) == 0:
if len(rself.limits) == len(rother.limits) == 1:
i = rself.limits[0][0]
x1 = rself.limits[0][1]
y1 = rself.limits[0][2]
j = rother.limits[0][0]
x2 = rother.limits[0][1]
y2 = rother.limits[0][2]
if i == j:
if x2 == y1 + 1:
return factor_sum(Sum(rself.function, (i, x1, y2)))
elif x1 == y2 + 1:
return factor_sum(Sum(rself.function, (i, x2, y1)))
return Add(self, other)
def product_simplify(s):
"""Main function for Product simplification"""
from sympy.concrete.products import Product
terms = Mul.make_args(s)
p_t = [] # Product Terms
o_t = [] # Other Terms
for term in terms:
if isinstance(term, Product):
p_t.append(term)
else:
o_t.append(term)
used = [False] * len(p_t)
for method in range(2):
for i, p_term1 in enumerate(p_t):
if not used[i]:
for j, p_term2 in enumerate(p_t):
if not used[j] and i != j:
if isinstance(product_mul(p_term1, p_term2, method), Product):
p_t[i] = product_mul(p_term1, p_term2, method)
used[j] = True
result = Mul(*o_t)
for i, p_term in enumerate(p_t):
if not used[i]:
result = Mul(result, p_term)
return result
def product_mul(self, other, method=0):
"""Helper function for Product simplification"""
from sympy.concrete.products import Product
if type(self) == type(other):
if method == 0:
if self.limits == other.limits:
return Product(self.function * other.function, *self.limits)
elif method == 1:
if simplify(self.function - other.function) == 0:
if len(self.limits) == len(other.limits) == 1:
i = self.limits[0][0]
x1 = self.limits[0][1]
y1 = self.limits[0][2]
j = other.limits[0][0]
x2 = other.limits[0][1]
y2 = other.limits[0][2]
if i == j:
if x2 == y1 + 1:
return Product(self.function, (i, x1, y2))
elif x1 == y2 + 1:
return Product(self.function, (i, x2, y1))
return Mul(self, other)
def _nthroot_solve(p, n, prec):
"""
helper function for ``nthroot``
It denests ``p**Rational(1, n)`` using its minimal polynomial
"""
from sympy.polys.numberfields import _minimal_polynomial_sq
from sympy.solvers import solve
while n % 2 == 0:
p = sqrtdenest(sqrt(p))
n = n // 2
if n == 1:
return p
pn = p**Rational(1, n)
x = Symbol('x')
f = _minimal_polynomial_sq(p, n, x)
if f is None:
return None
sols = solve(f, x)
for sol in sols:
if abs(sol - pn).n() < 1./10**prec:
sol = sqrtdenest(sol)
if _mexpand(sol**n) == p:
return sol
def logcombine(expr, force=False):
"""
Takes logarithms and combines them using the following rules:
- log(x) + log(y) == log(x*y) if both are positive
- a*log(x) == log(x**a) if x is positive and a is real
If ``force`` is ``True`` then the assumptions above will be assumed to hold if
there is no assumption already in place on a quantity. For example, if
``a`` is imaginary or the argument negative, force will not perform a
combination but if ``a`` is a symbol with no assumptions the change will
take place.
Examples
========
>>> from sympy import Symbol, symbols, log, logcombine, I
>>> from sympy.abc import a, x, y, z
>>> logcombine(a*log(x) + log(y) - log(z))
a*log(x) + log(y) - log(z)
>>> logcombine(a*log(x) + log(y) - log(z), force=True)
log(x**a*y/z)
>>> x,y,z = symbols('x,y,z', positive=True)
>>> a = Symbol('a', real=True)
>>> logcombine(a*log(x) + log(y) - log(z))
log(x**a*y/z)
The transformation is limited to factors and/or terms that
contain logs, so the result depends on the initial state of
expansion:
>>> eq = (2 + 3*I)*log(x)
>>> logcombine(eq, force=True) == eq
True
>>> logcombine(eq.expand(), force=True)
log(x**2) + I*log(x**3)
See Also
========
posify: replace all symbols with symbols having positive assumptions
sympy.core.function.expand_log: expand the logarithms of products
and powers; the opposite of logcombine
"""
def f(rv):
if not (rv.is_Add or rv.is_Mul):
return rv
def gooda(a):
# bool to tell whether the leading ``a`` in ``a*log(x)``
# could appear as log(x**a)
return (a is not S.NegativeOne and # -1 *could* go, but we disallow
(a.is_extended_real or force and a.is_extended_real is not False))
def goodlog(l):
# bool to tell whether log ``l``'s argument can combine with others
a = l.args[0]
return a.is_positive or force and a.is_nonpositive is not False
other = []
logs = []
log1 = defaultdict(list)
for a in Add.make_args(rv):
if isinstance(a, log) and goodlog(a):
log1[()].append(([], a))
elif not a.is_Mul:
other.append(a)
else:
ot = []
co = []
lo = []
for ai in a.args:
if ai.is_Rational and ai < 0:
ot.append(S.NegativeOne)
co.append(-ai)
elif isinstance(ai, log) and goodlog(ai):
lo.append(ai)
elif gooda(ai):
co.append(ai)
else:
ot.append(ai)
if len(lo) > 1:
logs.append((ot, co, lo))
elif lo:
log1[tuple(ot)].append((co, lo[0]))
else:
other.append(a)
# if there is only one log in other, put it with the
# good logs
if len(other) == 1 and isinstance(other[0], log):
log1[()].append(([], other.pop()))
# if there is only one log at each coefficient and none have
# an exponent to place inside the log then there is nothing to do
if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1):
return rv
# collapse multi-logs as far as possible in a canonical way
# TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))?
# -- in this case, it's unambiguous, but if it were were a log(c) in
# each term then it's arbitrary whether they are grouped by log(a) or
# by log(c). So for now, just leave this alone; it's probably better to
# let the user decide
for o, e, l in logs:
l = list(ordered(l))
e = log(l.pop(0).args[0]**Mul(*e))
while l:
li = l.pop(0)
e = log(li.args[0]**e)
c, l = Mul(*o), e
if isinstance(l, log): # it should be, but check to be sure
log1[(c,)].append(([], l))
else:
other.append(c*l)
# logs that have the same coefficient can multiply
for k in list(log1.keys()):
log1[Mul(*k)] = log(logcombine(Mul(*[
l.args[0]**Mul(*c) for c, l in log1.pop(k)]),
force=force), evaluate=False)
# logs that have oppositely signed coefficients can divide
for k in ordered(list(log1.keys())):
if not k in log1: # already popped as -k
continue
if -k in log1:
# figure out which has the minus sign; the one with
# more op counts should be the one
num, den = k, -k
if num.count_ops() > den.count_ops():
num, den = den, num
other.append(
num*log(log1.pop(num).args[0]/log1.pop(den).args[0],
evaluate=False))
else:
other.append(k*log1.pop(k))
return Add(*other)
return bottom_up(expr, f)
def inversecombine(expr):
"""Simplify the composition of a function and its inverse.
Explanation
===========
No attention is paid to whether the inverse is a left inverse or a
right inverse; thus, the result will in general not be equivalent
to the original expression.
Examples
========
>>> from sympy.simplify.simplify import inversecombine
>>> from sympy import asin, sin, log, exp
>>> from sympy.abc import x
>>> inversecombine(asin(sin(x)))
x
>>> inversecombine(2*log(exp(3*x)))
6*x
"""
def f(rv):
if rv.is_Function and hasattr(rv, "inverse"):
if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and
isinstance(rv.args[0], rv.inverse(argindex=1))):
rv = rv.args[0].args[0]
return rv
return bottom_up(expr, f)
def walk(e, *target):
"""Iterate through the args that are the given types (target) and
return a list of the args that were traversed; arguments
that are not of the specified types are not traversed.
Examples
========
>>> from sympy.simplify.simplify import walk
>>> from sympy import Min, Max
>>> from sympy.abc import x, y, z
>>> list(walk(Min(x, Max(y, Min(1, z))), Min))
[Min(x, Max(y, Min(1, z)))]
>>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max))
[Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)]
See Also
========
bottom_up
"""
if isinstance(e, target):
yield e
for i in e.args:
yield from walk(i, *target)
def bottom_up(rv, F, atoms=False, nonbasic=False):
"""Apply ``F`` to all expressions in an expression tree from the
bottom up. If ``atoms`` is True, apply ``F`` even if there are no args;
if ``nonbasic`` is True, try to apply ``F`` to non-Basic objects.
"""
args = getattr(rv, 'args', None)
if args is not None:
if args:
args = tuple([bottom_up(a, F, atoms, nonbasic) for a in args])
if args != rv.args:
rv = rv.func(*args)
rv = F(rv)
elif atoms:
rv = F(rv)
else:
if nonbasic:
try:
rv = F(rv)
except TypeError:
pass
return rv
def kroneckersimp(expr):
"""
Simplify expressions with KroneckerDelta.
The only simplification currently attempted is to identify multiplicative cancellation:
Examples
========
>>> from sympy import KroneckerDelta, kroneckersimp
>>> from sympy.abc import i
>>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i))
1
"""
def args_cancel(args1, args2):
for i1 in range(2):
for i2 in range(2):
a1 = args1[i1]
a2 = args2[i2]
a3 = args1[(i1 + 1) % 2]
a4 = args2[(i2 + 1) % 2]
if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false:
return True
return False
def cancel_kronecker_mul(m):
from sympy.utilities.iterables import subsets
args = m.args
deltas = [a for a in args if isinstance(a, KroneckerDelta)]
for delta1, delta2 in subsets(deltas, 2):
args1 = delta1.args
args2 = delta2.args
if args_cancel(args1, args2):
return 0*m
return m
if not expr.has(KroneckerDelta):
return expr
if expr.has(Piecewise):
expr = expr.rewrite(KroneckerDelta)
newexpr = expr
expr = None
while newexpr != expr:
expr = newexpr
newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul)
return expr
def besselsimp(expr):
"""
Simplify bessel-type functions.
Explanation
===========
This routine tries to simplify bessel-type functions. Currently it only
works on the Bessel J and I functions, however. It works by looking at all
such functions in turn, and eliminating factors of "I" and "-1" (actually
their polar equivalents) in front of the argument. Then, functions of
half-integer order are rewritten using strigonometric functions and
functions of integer order (> 1) are rewritten using functions
of low order. Finally, if the expression was changed, compute
factorization of the result with factor().
>>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S
>>> from sympy.abc import z, nu
>>> besselsimp(besselj(nu, z*polar_lift(-1)))
exp(I*pi*nu)*besselj(nu, z)
>>> besselsimp(besseli(nu, z*polar_lift(-I)))
exp(-I*pi*nu/2)*besselj(nu, z)
>>> besselsimp(besseli(S(-1)/2, z))
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
>>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z))
3*z*besseli(0, z)/2
"""
# TODO
# - better algorithm?
# - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ...
# - use contiguity relations?
def replacer(fro, to, factors):
factors = set(factors)
def repl(nu, z):
if factors.intersection(Mul.make_args(z)):
return to(nu, z)
return fro(nu, z)
return repl
def torewrite(fro, to):
def tofunc(nu, z):
return fro(nu, z).rewrite(to)
return tofunc
def tominus(fro):
def tofunc(nu, z):
return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z)
return tofunc
orig_expr = expr
ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)]
expr = expr.replace(
besselj, replacer(besselj,
torewrite(besselj, besseli), ifactors))
expr = expr.replace(
besseli, replacer(besseli,
torewrite(besseli, besselj), ifactors))
minusfactors = [-1, exp_polar(I*pi)]
expr = expr.replace(
besselj, replacer(besselj, tominus(besselj), minusfactors))
expr = expr.replace(
besseli, replacer(besseli, tominus(besseli), minusfactors))
z0 = Dummy('z')
def expander(fro):
def repl(nu, z):
if (nu % 1) == S.Half:
return simplify(trigsimp(unpolarify(
fro(nu, z0).rewrite(besselj).rewrite(jn).expand(
func=True)).subs(z0, z)))
elif nu.is_Integer and nu > 1:
return fro(nu, z).expand(func=True)
return fro(nu, z)
return repl
expr = expr.replace(besselj, expander(besselj))
expr = expr.replace(bessely, expander(bessely))
expr = expr.replace(besseli, expander(besseli))
expr = expr.replace(besselk, expander(besselk))
def _bessel_simp_recursion(expr):
def _use_recursion(bessel, expr):
while True:
bessels = expr.find(lambda x: isinstance(x, bessel))
try:
for ba in sorted(bessels, key=lambda x: re(x.args[0])):
a, x = ba.args
bap1 = bessel(a+1, x)
bap2 = bessel(a+2, x)
if expr.has(bap1) and expr.has(bap2):
expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2)
break
else:
return expr
except (ValueError, TypeError):
return expr
if expr.has(besselj):
expr = _use_recursion(besselj, expr)
if expr.has(bessely):
expr = _use_recursion(bessely, expr)
return expr
expr = _bessel_simp_recursion(expr)
if expr != orig_expr:
expr = expr.factor()
return expr
def nthroot(expr, n, max_len=4, prec=15):
"""
Compute a real nth-root of a sum of surds.
Parameters
==========
expr : sum of surds
n : integer
max_len : maximum number of surds passed as constants to ``nsimplify``
Algorithm
=========
First ``nsimplify`` is used to get a candidate root; if it is not a
root the minimal polynomial is computed; the answer is one of its
roots.
Examples
========
>>> from sympy.simplify.simplify import nthroot
>>> from sympy import sqrt
>>> nthroot(90 + 34*sqrt(7), 3)
sqrt(7) + 3
"""
expr = sympify(expr)
n = sympify(n)
p = expr**Rational(1, n)
if not n.is_integer:
return p
if not _is_sum_surds(expr):
return p
surds = []
coeff_muls = [x.as_coeff_Mul() for x in expr.args]
for x, y in coeff_muls:
if not x.is_rational:
return p
if y is S.One:
continue
if not (y.is_Pow and y.exp == S.Half and y.base.is_integer):
return p
surds.append(y)
surds.sort()
surds = surds[:max_len]
if expr < 0 and n % 2 == 1:
p = (-expr)**Rational(1, n)
a = nsimplify(p, constants=surds)
res = a if _mexpand(a**n) == _mexpand(-expr) else p
return -res
a = nsimplify(p, constants=surds)
if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr):
return _mexpand(a)
expr = _nthroot_solve(expr, n, prec)
if expr is None:
return p
return expr
def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None,
rational_conversion='base10'):
"""
Find a simple representation for a number or, if there are free symbols or
if ``rational=True``, then replace Floats with their Rational equivalents. If
no change is made and rational is not False then Floats will at least be
converted to Rationals.
Explanation
===========
For numerical expressions, a simple formula that numerically matches the
given numerical expression is sought (and the input should be possible
to evalf to a precision of at least 30 digits).
Optionally, a list of (rationally independent) constants to
include in the formula may be given.
A lower tolerance may be set to find less exact matches. If no tolerance
is given then the least precise value will set the tolerance (e.g. Floats
default to 15 digits of precision, so would be tolerance=10**-15).
With ``full=True``, a more extensive search is performed
(this is useful to find simpler numbers when the tolerance
is set low).
When converting to rational, if rational_conversion='base10' (the default), then
convert floats to rationals using their base-10 (string) representation.
When rational_conversion='exact' it uses the exact, base-2 representation.
Examples
========
>>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi
>>> nsimplify(4/(1+sqrt(5)), [GoldenRatio])
-2 + 2*GoldenRatio
>>> nsimplify((1/(exp(3*pi*I/5)+1)))
1/2 - I*sqrt(sqrt(5)/10 + 1/4)
>>> nsimplify(I**I, [pi])
exp(-pi/2)
>>> nsimplify(pi, tolerance=0.01)
22/7
>>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact')
6004799503160655/18014398509481984
>>> nsimplify(0.333333333333333, rational=True)
1/3
See Also
========
sympy.core.function.nfloat
"""
try:
return sympify(as_int(expr))
except (TypeError, ValueError):
pass
expr = sympify(expr).xreplace({
Float('inf'): S.Infinity,
Float('-inf'): S.NegativeInfinity,
})
if expr is S.Infinity or expr is S.NegativeInfinity:
return expr
if rational or expr.free_symbols:
return _real_to_rational(expr, tolerance, rational_conversion)
# SymPy's default tolerance for Rationals is 15; other numbers may have
# lower tolerances set, so use them to pick the largest tolerance if None
# was given
if tolerance is None:
tolerance = 10**-min([15] +
[mpmath.libmp.libmpf.prec_to_dps(n._prec)
for n in expr.atoms(Float)])
# XXX should prec be set independent of tolerance or should it be computed
# from tolerance?
prec = 30
bprec = int(prec*3.33)
constants_dict = {}
for constant in constants:
constant = sympify(constant)
v = constant.evalf(prec)
if not v.is_Float:
raise ValueError("constants must be real-valued")
constants_dict[str(constant)] = v._to_mpmath(bprec)
exprval = expr.evalf(prec, chop=True)
re, im = exprval.as_real_imag()
# safety check to make sure that this evaluated to a number
if not (re.is_Number and im.is_Number):
return expr
def nsimplify_real(x):
orig = mpmath.mp.dps
xv = x._to_mpmath(bprec)
try:
# We'll be happy with low precision if a simple fraction
if not (tolerance or full):
mpmath.mp.dps = 15
rat = mpmath.pslq([xv, 1])
if rat is not None:
return Rational(-int(rat[1]), int(rat[0]))
mpmath.mp.dps = prec
newexpr = mpmath.identify(xv, constants=constants_dict,
tol=tolerance, full=full)
if not newexpr:
raise ValueError
if full:
newexpr = newexpr[0]
expr = sympify(newexpr)
if x and not expr: # don't let x become 0
raise ValueError
if expr.is_finite is False and not xv in [mpmath.inf, mpmath.ninf]:
raise ValueError
return expr
finally:
# even though there are returns above, this is executed
# before leaving
mpmath.mp.dps = orig
try:
if re:
re = nsimplify_real(re)
if im:
im = nsimplify_real(im)
except ValueError:
if rational is None:
return _real_to_rational(expr, rational_conversion=rational_conversion)
return expr
rv = re + im*S.ImaginaryUnit
# if there was a change or rational is explicitly not wanted
# return the value, else return the Rational representation
if rv != expr or rational is False:
return rv
return _real_to_rational(expr, rational_conversion=rational_conversion)
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
>>> _real_to_rational(.76 + .1*x**.5)
sqrt(x)/10 + 19/25
If rational_conversion='base10', this uses the base-10 string. If
rational_conversion='exact', the exact, base-2 representation is used.
>>> _real_to_rational(0.333333333333333, rational_conversion='exact')
6004799503160655/18014398509481984
>>> _real_to_rational(0.333333333333333)
1/3
"""
expr = _sympify(expr)
inf = Float('inf')
p = expr
reps = {}
reduce_num = None
if tolerance is not None and tolerance < 1:
reduce_num = ceiling(1/tolerance)
for fl in p.atoms(Float):
key = fl
if reduce_num is not None:
r = Rational(fl).limit_denominator(reduce_num)
elif (tolerance is not None and tolerance >= 1 and
fl.is_Integer is False):
r = Rational(tolerance*round(fl/tolerance)
).limit_denominator(int(tolerance))
else:
if rational_conversion == 'exact':
r = Rational(fl)
reps[key] = r
continue
elif rational_conversion != 'base10':
raise ValueError("rational_conversion must be 'base10' or 'exact'")
r = nsimplify(fl, rational=False)
# e.g. log(3).n() -> log(3) instead of a Rational
if fl and not r:
r = Rational(fl)
elif not r.is_Rational:
if fl == inf or fl == -inf:
r = S.ComplexInfinity
elif fl < 0:
fl = -fl
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = -Rational(str(fl/d))*d
elif fl > 0:
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = Rational(str(fl/d))*d
else:
r = Integer(0)
reps[key] = r
return p.subs(reps, simultaneous=True)
def clear_coefficients(expr, rhs=S.Zero):
"""Return `p, r` where `p` is the expression obtained when Rational
additive and multiplicative coefficients of `expr` have been stripped
away in a naive fashion (i.e. without simplification). The operations
needed to remove the coefficients will be applied to `rhs` and returned
as `r`.
Examples
========
>>> from sympy.simplify.simplify import clear_coefficients
>>> from sympy.abc import x, y
>>> from sympy import Dummy
>>> expr = 4*y*(6*x + 3)
>>> clear_coefficients(expr - 2)
(y*(2*x + 1), 1/6)
When solving 2 or more expressions like `expr = a`,
`expr = b`, etc..., it is advantageous to provide a Dummy symbol
for `rhs` and simply replace it with `a`, `b`, etc... in `r`.
>>> rhs = Dummy('rhs')
>>> clear_coefficients(expr, rhs)
(y*(2*x + 1), _rhs/12)
>>> _[1].subs(rhs, 2)
1/6
"""
was = None
free = expr.free_symbols
if expr.is_Rational:
return (S.Zero, rhs - expr)
while expr and was != expr:
was = expr
m, expr = (
expr.as_content_primitive()
if free else
factor_terms(expr).as_coeff_Mul(rational=True))
rhs /= m
c, expr = expr.as_coeff_Add(rational=True)
rhs -= c
expr = signsimp(expr, evaluate = False)
if _coeff_isneg(expr):
expr = -expr
rhs = -rhs
return expr, rhs
def nc_simplify(expr, deep=True):
'''
Simplify a non-commutative expression composed of multiplication
and raising to a power by grouping repeated subterms into one power.
Priority is given to simplifications that give the fewest number
of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying
to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3).
If ``expr`` is a sum of such terms, the sum of the simplified terms
is returned.
Keyword argument ``deep`` controls whether or not subexpressions
nested deeper inside the main expression are simplified. See examples
below. Setting `deep` to `False` can save time on nested expressions
that don't need simplifying on all levels.
Examples
========
>>> from sympy import symbols
>>> from sympy.simplify.simplify import nc_simplify
>>> a, b, c = symbols("a b c", commutative=False)
>>> nc_simplify(a*b*a*b*c*a*b*c)
a*b*(a*b*c)**2
>>> expr = a**2*b*a**4*b*a**4
>>> nc_simplify(expr)
a**2*(b*a**4)**2
>>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2)
((a*b)**2*c**2)**2
>>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a)
(a*b)**2 + 2*(a*c*a)**3
>>> nc_simplify(b**-1*a**-1*(a*b)**2)
a*b
>>> nc_simplify(a**-1*b**-1*c*a)
(b*a)**(-1)*c*a
>>> expr = (a*b*a*b)**2*a*c*a*c
>>> nc_simplify(expr)
(a*b)**4*(a*c)**2
>>> nc_simplify(expr, deep=False)
(a*b*a*b)**2*(a*c)**2
'''
from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul,
MatPow, MatrixSymbol)
from sympy.core.exprtools import factor_nc
if isinstance(expr, MatrixExpr):
expr = expr.doit(inv_expand=False)
_Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol
else:
_Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol
# =========== Auxiliary functions ========================
def _overlaps(args):
# Calculate a list of lists m such that m[i][j] contains the lengths
# of all possible overlaps between args[:i+1] and args[i+1+j:].
# An overlap is a suffix of the prefix that matches a prefix
# of the suffix.
# For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains
# the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps
# are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0].
# All overlaps rather than only the longest one are recorded
# because this information helps calculate other overlap lengths.
m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]]
for i in range(1, len(args)):
overlaps = []
j = 0
for j in range(len(args) - i - 1):
overlap = []
for v in m[i-1][j+1]:
if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]:
overlap.append(v + 1)
overlap += [0]
overlaps.append(overlap)
m.append(overlaps)
return m
def _reduce_inverses(_args):
# replace consecutive negative powers by an inverse
# of a product of positive powers, e.g. a**-1*b**-1*c
# will simplify to (a*b)**-1*c;
# return that new args list and the number of negative
# powers in it (inv_tot)
inv_tot = 0 # total number of inverses
inverses = []
args = []
for arg in _args:
if isinstance(arg, _Pow) and arg.args[1] < 0:
inverses = [arg**-1] + inverses
inv_tot += 1
else:
if len(inverses) == 1:
args.append(inverses[0]**-1)
elif len(inverses) > 1:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
inverses = []
args.append(arg)
if inverses:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
return inv_tot, tuple(args)
def get_score(s):
# compute the number of arguments of s
# (including in nested expressions) overall
# but ignore exponents
if isinstance(s, _Pow):
return get_score(s.args[0])
elif isinstance(s, (_Add, _Mul)):
return sum([get_score(a) for a in s.args])
return 1
def compare(s, alt_s):
# compare two possible simplifications and return a
# "better" one
if s != alt_s and get_score(alt_s) < get_score(s):
return alt_s
return s
# ========================================================
if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative:
return expr
args = expr.args[:]
if isinstance(expr, _Pow):
if deep:
return _Pow(nc_simplify(args[0]), args[1]).doit()
else:
return expr
elif isinstance(expr, _Add):
return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit()
else:
# get the non-commutative part
c_args, args = expr.args_cnc()
com_coeff = Mul(*c_args)
if com_coeff != 1:
return com_coeff*nc_simplify(expr/com_coeff, deep=deep)
inv_tot, args = _reduce_inverses(args)
# if most arguments are negative, work with the inverse
# of the expression, e.g. a**-1*b*a**-1*c**-1 will become
# (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a
invert = False
if inv_tot > len(args)/2:
invert = True
args = [a**-1 for a in args[::-1]]
if deep:
args = tuple(nc_simplify(a) for a in args)
m = _overlaps(args)
# simps will be {subterm: end} where `end` is the ending
# index of a sequence of repetitions of subterm;
# this is for not wasting time with subterms that are part
# of longer, already considered sequences
simps = {}
post = 1
pre = 1
# the simplification coefficient is the number of
# arguments by which contracting a given sequence
# would reduce the word; e.g. in a*b*a*b*c*a*b*c,
# contracting a*b*a*b to (a*b)**2 removes 3 arguments
# while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's
# better to contract the latter so simplification
# with a maximum simplification coefficient will be chosen
max_simp_coeff = 0
simp = None # information about future simplification
for i in range(1, len(args)):
simp_coeff = 0
l = 0 # length of a subterm
p = 0 # the power of a subterm
if i < len(args) - 1:
rep = m[i][0]
start = i # starting index of the repeated sequence
end = i+1 # ending index of the repeated sequence
if i == len(args)-1 or rep == [0]:
# no subterm is repeated at this stage, at least as
# far as the arguments are concerned - there may be
# a repetition if powers are taken into account
if (isinstance(args[i], _Pow) and
not isinstance(args[i].args[0], _Symbol)):
subterm = args[i].args[0].args
l = len(subterm)
if args[i-l:i] == subterm:
# e.g. a*b in a*b*(a*b)**2 is not repeated
# in args (= [a, b, (a*b)**2]) but it
# can be matched here
p += 1
start -= l
if args[i+1:i+1+l] == subterm:
# e.g. a*b in (a*b)**2*a*b
p += 1
end += l
if p:
p += args[i].args[1]
else:
continue
else:
l = rep[0] # length of the longest repeated subterm at this point
start -= l - 1
subterm = args[start:end]
p = 2
end += l
if subterm in simps and simps[subterm] >= start:
# the subterm is part of a sequence that
# has already been considered
continue
# count how many times it's repeated
while end < len(args):
if l in m[end-1][0]:
p += 1
end += l
elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm:
# for cases like a*b*a*b*(a*b)**2*a*b
p += args[end].args[1]
end += 1
else:
break
# see if another match can be made, e.g.
# for b*a**2 in b*a**2*b*a**3 or a*b in
# a**2*b*a*b
pre_exp = 0
pre_arg = 1
if start - l >= 0 and args[start-l+1:start] == subterm[1:]:
if isinstance(subterm[0], _Pow):
pre_arg = subterm[0].args[0]
exp = subterm[0].args[1]
else:
pre_arg = subterm[0]
exp = 1
if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg:
pre_exp = args[start-l].args[1] - exp
start -= l
p += 1
elif args[start-l] == pre_arg:
pre_exp = 1 - exp
start -= l
p += 1
post_exp = 0
post_arg = 1
if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]:
if isinstance(subterm[-1], _Pow):
post_arg = subterm[-1].args[0]
exp = subterm[-1].args[1]
else:
post_arg = subterm[-1]
exp = 1
if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg:
post_exp = args[end+l-1].args[1] - exp
end += l
p += 1
elif args[end+l-1] == post_arg:
post_exp = 1 - exp
end += l
p += 1
# Consider a*b*a**2*b*a**2*b*a:
# b*a**2 is explicitly repeated, but note
# that in this case a*b*a is also repeated
# so there are two possible simplifications:
# a*(b*a**2)**3*a**-1 or (a*b*a)**3
# The latter is obviously simpler.
# But in a*b*a**2*b**2*a**2 the simplifications are
# a*(b*a**2)**2 and (a*b*a)**3*a in which case
# it's better to stick with the shorter subterm
if post_exp and exp % 2 == 0 and start > 0:
exp = exp/2
_pre_exp = 1
_post_exp = 1
if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg:
_post_exp = post_exp + exp
_pre_exp = args[start-1].args[1] - exp
elif args[start-1] == post_arg:
_post_exp = post_exp + exp
_pre_exp = 1 - exp
if _pre_exp == 0 or _post_exp == 0:
if not pre_exp:
start -= 1
post_exp = _post_exp
pre_exp = _pre_exp
pre_arg = post_arg
subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,)
simp_coeff += end-start
if post_exp:
simp_coeff -= 1
if pre_exp:
simp_coeff -= 1
simps[subterm] = end
if simp_coeff > max_simp_coeff:
max_simp_coeff = simp_coeff
simp = (start, _Mul(*subterm), p, end, l)
pre = pre_arg**pre_exp
post = post_arg**post_exp
if simp:
subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2])
pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep)
post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep)
simp = pre*subterm*post
if pre != 1 or post != 1:
# new simplifications may be possible but no need
# to recurse over arguments
simp = nc_simplify(simp, deep=False)
else:
simp = _Mul(*args)
if invert:
simp = _Pow(simp, -1)
# see if factor_nc(expr) is simplified better
if not isinstance(expr, MatrixExpr):
f_expr = factor_nc(expr)
if f_expr != expr:
alt_simp = nc_simplify(f_expr, deep=deep)
simp = compare(simp, alt_simp)
else:
simp = simp.doit(inv_expand=False)
return simp
def dotprodsimp(expr, withsimp=False):
"""Simplification for a sum of products targeted at the kind of blowup that
occurs during summation of products. Intended to reduce expression blowup
during matrix multiplication or other similar operations. Only works with
algebraic expressions and does not recurse into non.
Parameters
==========
withsimp : bool, optional
Specifies whether a flag should be returned along with the expression
to indicate roughly whether simplification was successful. It is used
in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to
simplify an expression repetitively which does not simplify.
"""
def count_ops_alg(expr):
"""Optimized count algebraic operations with no recursion into
non-algebraic args that ``core.function.count_ops`` does. Also returns
whether rational functions may be present according to negative
exponents of powers or non-number fractions.
Returns
=======
ops, ratfunc : int, bool
``ops`` is the number of algebraic operations starting at the top
level expression (not recursing into non-alg children). ``ratfunc``
specifies whether the expression MAY contain rational functions
which ``cancel`` MIGHT optimize.
"""
ops = 0
args = [expr]
ratfunc = False
while args:
a = args.pop()
if not isinstance(a, Basic):
continue
if a.is_Rational:
if a is not S.One: # -1/3 = NEG + DIV
ops += bool (a.p < 0) + bool (a.q != 1)
elif a.is_Mul:
if _coeff_isneg(a):
ops += 1
if a.args[0] is S.NegativeOne:
a = a.as_two_terms()[1]
else:
a = -a
n, d = fraction(a)
if n.is_Integer:
ops += 1 + bool (n < 0)
args.append(d) # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ratfunc=True
ops += 1
args.append(n) # could be -Mul
else:
ops += len(a.args) - 1
args.extend(a.args)
elif a.is_Add:
laargs = len(a.args)
negs = 0
for ai in a.args:
if _coeff_isneg(ai):
negs += 1
ai = -ai
args.append(ai)
ops += laargs - (negs != laargs) # -x - y = NEG + SUB
elif a.is_Pow:
ops += 1
args.append(a.base)
if not ratfunc:
ratfunc = a.exp.is_negative is not False
return ops, ratfunc
def nonalg_subs_dummies(expr, dummies):
"""Substitute dummy variables for non-algebraic expressions to avoid
evaluation of non-algebraic terms that ``polys.polytools.cancel`` does.
"""
if not expr.args:
return expr
if expr.is_Add or expr.is_Mul or expr.is_Pow:
args = None
for i, a in enumerate(expr.args):
c = nonalg_subs_dummies(a, dummies)
if c is a:
continue
if args is None:
args = list(expr.args)
args[i] = c
if args is None:
return expr
return expr.func(*args)
return dummies.setdefault(expr, Dummy())
simplified = False # doesn't really mean simplified, rather "can simplify again"
if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow):
expr2 = expr.expand(deep=True, modulus=None, power_base=False,
power_exp=False, mul=True, log=False, multinomial=True, basic=False)
if expr2 != expr:
expr = expr2
simplified = True
exprops, ratfunc = count_ops_alg(expr)
if exprops >= 6: # empirically tested cutoff for expensive simplification
if ratfunc:
dummies = {}
expr2 = nonalg_subs_dummies(expr, dummies)
if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution
expr3 = cancel(expr2)
if expr3 != expr2:
expr = expr3.subs([(d, e) for e, d in dummies.items()])
simplified = True
# very special case: x/(x-1) - 1/(x-1) -> 1
elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and
expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and
expr.args [1].args [-1].is_Pow and
expr.args [0].args [-1].exp is S.NegativeOne and
expr.args [1].args [-1].exp is S.NegativeOne):
expr2 = together (expr)
expr2ops = count_ops_alg(expr2)[0]
if expr2ops < exprops:
expr = expr2
simplified = True
else:
simplified = True
return (expr, simplified) if withsimp else expr
|
f35a171bae990aabaa7ea7a036cbc8d759f4dd00fbe9cef9d12988900e508062 | import bisect
import itertools
import operator
from functools import reduce, singledispatch
from itertools import accumulate
from collections import defaultdict
from sympy import Indexed, IndexedBase, Tuple, Sum, Add, S, Integer, diagonalize_vector, DiagMatrix, ZeroMatrix
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.core.basic import Basic
from sympy.core.compatibility import default_sort_key
from sympy.core.mul import Mul
from sympy.core.sympify import _sympify
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.expressions import (MatAdd, MatMul, Trace, Transpose)
from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement
from sympy.tensor.array import NDimArray
from sympy.tensor.array.expressions.array_expressions import ZeroArray
class _CodegenArrayAbstract(Basic):
@property
def subranks(self):
"""
Returns the ranks of the objects in the uppermost tensor product inside
the current object. In case no tensor products are contained, return
the atomic ranks.
Examples
========
>>> from sympy.codegen.array_utils import CodegenArrayTensorProduct, CodegenArrayContraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> P = MatrixSymbol("P", 3, 3)
Important: do not confuse the rank of the matrix with the rank of an array.
>>> tp = CodegenArrayTensorProduct(M, N, P)
>>> tp.subranks
[2, 2, 2]
>>> co = CodegenArrayContraction(tp, (1, 2), (3, 4))
>>> co.subranks
[2, 2, 2]
"""
return self._subranks[:]
def subrank(self):
"""
The sum of ``subranks``.
"""
return sum(self.subranks)
@property
def shape(self):
return self._shape
class CodegenArrayContraction(_CodegenArrayAbstract):
r"""
This class is meant to represent contractions of arrays in a form easily
processable by the code printers.
"""
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, CodegenArrayContraction):
return cls._flatten(expr, *contraction_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
contraction_indices_flat = [j for i in contraction_indices for j in i]
shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
return ZeroArray(*shape)
if isinstance(expr, CodegenArrayPermuteDims):
return cls._handle_nested_permute_dims(expr, *contraction_indices)
if isinstance(expr, CodegenArrayTensorProduct):
expr, contraction_indices = cls._sort_fully_contracted_args(expr, contraction_indices)
expr, contraction_indices = cls._lower_contraction_to_addends(expr, contraction_indices)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, CodegenArrayDiagonal):
return cls._handle_nested_diagonal(expr, *contraction_indices)
if isinstance(expr, CodegenArrayElementwiseAdd):
return CodegenArrayElementwiseAdd(*[CodegenArrayContraction(i, *contraction_indices) for i in expr.args])
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all([i not in cind for cind in contraction_indices])}
obj._free_indices_to_position = free_indices_to_position
shape = expr.shape
cls._validate(expr, *contraction_indices)
if shape:
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
return obj
def __mul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
def __rmul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
@staticmethod
def _validate(expr, *contraction_indices):
shape = expr.shape
if shape is None:
return
# Check that no contraction happens when the shape is mismatched:
for i in contraction_indices:
if len({shape[j] for j in i if shape[j] != -1}) != 1:
raise ValueError("contracting indices of different dimensions")
@classmethod
def _push_indices_down(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _lower_contraction_to_addends(cls, expr, contraction_indices):
if isinstance(expr, CodegenArrayElementwiseAdd):
raise NotImplementedError()
if not isinstance(expr, CodegenArrayTensorProduct):
return expr, contraction_indices
subranks = expr.subranks
cumranks = list(accumulate([0] + subranks))
contraction_indices_remaining = []
contraction_indices_args = [[] for i in expr.args]
backshift = set([])
for i, contraction_group in enumerate(contraction_indices):
for j in range(len(expr.args)):
if not isinstance(expr.args[j], CodegenArrayElementwiseAdd):
continue
if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
backshift.update(contraction_group)
break
else:
contraction_indices_remaining.append(contraction_group)
if len(contraction_indices_remaining) == len(contraction_indices):
return expr, contraction_indices
total_rank = get_rank(expr)
shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
ret = CodegenArrayTensorProduct(*[
CodegenArrayContraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
])
return ret, contraction_indices_remaining
def split_multiple_contractions(self):
"""
Recognize multiple contractions and attempt at rewriting them as paired-contractions.
"""
from sympy import ask, Q
contraction_indices = self.contraction_indices
if isinstance(self.expr, CodegenArrayTensorProduct):
args = list(self.expr.args)
else:
args = [self.expr]
# TODO: unify API, best location in CodegenArrayTensorProduct
subranks = [get_rank(i) for i in args]
# TODO: unify API
mapping = _get_mapping_from_subranks(subranks)
reverse_mapping = {v:k for k, v in mapping.items()}
new_contraction_indices = []
for indl, links in enumerate(contraction_indices):
if len(links) <= 2:
new_contraction_indices.append(links)
continue
# Check multiple contractions:
#
# Examples:
#
# * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
#
# Care for:
# - matrix being diagonalized (i.e. `A_ii`)
# - vectors being diagonalized (i.e. `a_i0`)
# Also consider the case of diagonal matrices being contracted:
current_dimension = self.expr.shape[links[0]]
tuple_links = [mapping[i] for i in links]
arg_indices, arg_positions = zip(*tuple_links)
args_updates = {}
if len(arg_indices) != len(set(arg_indices)):
# Maybe trace should be supported?
raise NotImplementedError
not_vectors = []
vectors = []
for arg_ind, arg_pos in tuple_links:
mat = args[arg_ind]
other_arg_pos = 1-arg_pos
other_arg_abs = reverse_mapping[arg_ind, other_arg_pos]
if (((1 not in mat.shape) and (not ask(Q.diagonal(mat)))) or
((current_dimension == 1) is True and mat.shape != (1, 1)) or
any([other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl])
):
not_vectors.append((arg_ind, arg_pos))
continue
args_updates[arg_ind] = diagonalize_vector(mat)
vectors.append((arg_ind, arg_pos))
vectors.append((arg_ind, 1-arg_pos))
if len(not_vectors) > 2:
new_contraction_indices.append(links)
continue
if len(not_vectors) == 0:
new_sequence = vectors[:1] + vectors[2:]
elif len(not_vectors) == 1:
new_sequence = not_vectors[:1] + vectors[:-1]
else:
new_sequence = not_vectors[:1] + vectors + not_vectors[1:]
for i in range(0, len(new_sequence) - 1, 2):
arg1, pos1 = new_sequence[i]
arg2, pos2 = new_sequence[i+1]
if arg1 == arg2:
raise NotImplementedError
continue
abspos1 = reverse_mapping[arg1, pos1]
abspos2 = reverse_mapping[arg2, pos2]
new_contraction_indices.append((abspos1, abspos2))
for ind, newarg in args_updates.items():
args[ind] = newarg
return CodegenArrayContraction(
CodegenArrayTensorProduct(*args),
*new_contraction_indices
)
def flatten_contraction_of_diagonal(self):
if not isinstance(self.expr, CodegenArrayDiagonal):
return self
contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
new_contraction_indices = []
diagonal_indices = self.expr.diagonal_indices[:]
for i in contraction_down:
contraction_group = list(i)
for j in i:
diagonal_with = [k for k in diagonal_indices if j in k]
contraction_group.extend([l for k in diagonal_with for l in k])
diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
new_contraction_indices.append(sorted(set(contraction_group)))
new_contraction_indices = CodegenArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
return CodegenArrayContraction(
CodegenArrayDiagonal(
self.expr.expr,
*diagonal_indices
),
*new_contraction_indices
)
@staticmethod
def _get_free_indices_to_position_map(free_indices, contraction_indices):
free_indices_to_position = {}
flattened_contraction_indices = [j for i in contraction_indices for j in i]
counter = 0
for ind in free_indices:
while counter in flattened_contraction_indices:
counter += 1
free_indices_to_position[ind] = counter
counter += 1
return free_indices_to_position
@staticmethod
def _get_index_shifts(expr):
"""
Get the mapping of indices at the positions before the contraction
occurs.
Examples
========
>>> from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> cg = CodegenArrayContraction(CodegenArrayTensorProduct(M, N), [1, 2])
>>> cg._get_index_shifts(cg)
[0, 2]
Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
need to be shifted by 0 and 2 to get the corresponding positions before
the contraction (that is, 0 and 3).
"""
inner_contraction_indices = expr.contraction_indices
all_inner = [j for i in inner_contraction_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
return shifts
@staticmethod
def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
shifts = CodegenArrayContraction._get_index_shifts(expr)
outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
return outer_contraction_indices
@staticmethod
def _flatten(expr, *outer_contraction_indices):
inner_contraction_indices = expr.contraction_indices
outer_contraction_indices = CodegenArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
contraction_indices = inner_contraction_indices + outer_contraction_indices
return CodegenArrayContraction(expr.expr, *contraction_indices)
@classmethod
def _handle_nested_permute_dims(cls, expr, *contraction_indices):
permutation = expr.permutation
plist = permutation.array_form
new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
new_plist = [i for i in plist if all(i not in j for j in new_contraction_indices)]
new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
return CodegenArrayPermuteDims(
CodegenArrayContraction(expr.expr, *new_contraction_indices),
Permutation(new_plist)
)
@classmethod
def _handle_nested_diagonal(cls, expr: 'CodegenArrayDiagonal', *contraction_indices):
diagonal_indices = list(expr.diagonal_indices)
down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
# Flatten diagonally contracted indices:
down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
new_contraction_indices = []
for contr_indgrp in down_contraction_indices:
ind = contr_indgrp[:]
for j, diag_indgrp in enumerate(diagonal_indices):
if diag_indgrp is None:
continue
if any(i in diag_indgrp for i in contr_indgrp):
ind.extend(diag_indgrp)
diagonal_indices[j] = None
new_contraction_indices.append(sorted(set(ind)))
new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
new_diagonal_indices = CodegenArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
return CodegenArrayDiagonal(
CodegenArrayContraction(expr.expr, *new_contraction_indices),
*new_diagonal_indices
)
@classmethod
def _sort_fully_contracted_args(cls, expr, contraction_indices):
if expr.shape is None:
return expr, contraction_indices
cumul = list(accumulate([0] + expr.subranks))
index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
contraction_indices_flat = {j for i in contraction_indices for j in i}
fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
new_args = [expr.args[i] for i in new_pos]
new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
index_permutation_array_form = _af_invert(new_index_blocks_flat)
new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
return CodegenArrayTensorProduct(*new_args), new_contraction_indices
def _get_contraction_tuples(self):
r"""
Return tuples containing the argument index and position within the
argument of the index position.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, B), (1, 2))
>>> cg._get_contraction_tuples()
[[(0, 1), (1, 0)]]
Notes
=====
Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
of the tensor product `A\otimes B` are contracted, has been transformed
into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
notation. `(0, 1)` is the second index (1) of the first argument (i.e.
0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
argument (i.e. 1 or `B`).
"""
mapping = self._mapping
return [[mapping[j] for j in i] for i in self.contraction_indices]
@staticmethod
def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
# TODO: check that `expr` has `.subranks`:
ranks = expr.subranks
cumulative_ranks = [0] + list(accumulate(ranks))
return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
@property
def free_indices(self):
return self._free_indices[:]
@property
def free_indices_to_position(self):
return dict(self._free_indices_to_position)
@property
def expr(self):
return self.args[0]
@property
def contraction_indices(self):
return self.args[1:]
def _contraction_indices_to_components(self):
expr = self.expr
if not isinstance(expr, CodegenArrayTensorProduct):
raise NotImplementedError("only for contractions of tensor products")
ranks = expr.subranks
mapping = {}
counter = 0
for i, rank in enumerate(ranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def sort_args_by_name(self):
"""
Sort arguments in the tensor product so that their order is lexicographical.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.codegen.array_utils import parse_matrix_expression
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> cg = parse_matrix_expression(C*D*A*B)
>>> cg
CodegenArrayContraction(CodegenArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
>>> cg.sort_args_by_name()
CodegenArrayContraction(CodegenArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
"""
expr = self.expr
if not isinstance(expr, CodegenArrayTensorProduct):
return self
args = expr.args
sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
pos_sorted, args_sorted = zip(*sorted_data)
reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
contraction_tuples = self._get_contraction_tuples()
contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
c_tp = CodegenArrayTensorProduct(*args_sorted)
new_contr_indices = self._contraction_tuples_to_contraction_indices(
c_tp,
contraction_tuples
)
return CodegenArrayContraction(c_tp, *new_contr_indices)
def _get_contraction_links(self):
r"""
Returns a dictionary of links between arguments in the tensor product
being contracted.
See the example for an explanation of the values.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.codegen.array_utils import parse_matrix_expression
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
Matrix multiplications are pairwise contractions between neighboring
matrices:
`A_{ij} B_{jk} C_{kl} D_{lm}`
>>> cg = parse_matrix_expression(A*B*C*D)
>>> cg
CodegenArrayContraction(CodegenArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
>>> cg._get_contraction_links()
{0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
This dictionary is interpreted as follows: argument in position 0 (i.e.
matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
is argument in position 1 (matrix `B`) on the first index slot of `B`,
this is the contraction provided by the index `j` from `A`.
The argument in position 1 (that is, matrix `B`) has two contractions,
the ones provided by the indices `j` and `k`, respectively the first
and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
`(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
argument in position 0 (that is, `A_{\ldot j}`), and so on.
"""
args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
return dlinks
def get_shape(expr):
if hasattr(expr, "shape"):
return expr.shape
return ()
class CodegenArrayTensorProduct(_CodegenArrayAbstract):
r"""
Class to represent the tensor product of array-like objects.
"""
def __new__(cls, *args):
args = [_sympify(arg) for arg in args]
args = cls._flatten(args)
ranks = [_get_subrank(arg) for arg in args]
# Check if there are nested permutation and lift them up:
permutation_cycles = []
for i, arg in enumerate(args):
if not isinstance(arg, CodegenArrayPermuteDims):
continue
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
args[i] = arg.expr
if permutation_cycles:
return CodegenArrayPermuteDims(CodegenArrayTensorProduct(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
if len(args) == 1:
return args[0]
# If any object is a ZeroArray, return a ZeroArray:
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
return ZeroArray(*shapes)
# If there are contraction objects inside, transform the whole
# expression into `CodegenArrayContraction`:
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, CodegenArrayContraction)}
if contractions:
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
tp = cls(*[arg.expr if isinstance(arg, CodegenArrayContraction) else arg for arg in args])
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
return CodegenArrayContraction(tp, *contraction_indices)
#newargs = [i for i in args if hasattr(i, "shape")]
#coeff = reduce(lambda x, y: x*y, [i for i in args if not hasattr(i, "shape")], S.One)
#newargs[0] *= coeff
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
shapes = [get_shape(i) for i in args]
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = tuple(j for i in shapes for j in i)
return obj
@classmethod
def _flatten(cls, args):
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
return args
class CodegenArrayElementwiseAdd(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError("summing arrays of different ranks")
shapes = [arg.shape for arg in args]
if len({i for i in shapes if i is not None}) > 1:
raise ValueError("mismatching shapes in addition")
# Flatten:
args = cls._flatten_args(args)
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
if len(args) == 0:
if any(i for i in shapes if i is None):
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
return ZeroArray(*shapes[0])
elif len(args) == 1:
return args[0]
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = shapes[0]
return obj
@classmethod
def _flatten_args(cls, args):
new_args = []
for arg in args:
if isinstance(arg, CodegenArrayElementwiseAdd):
new_args.extend(arg.args)
else:
new_args.append(arg)
return new_args
class CodegenArrayPermuteDims(_CodegenArrayAbstract):
r"""
Class to represent permutation of axes of arrays.
Examples
========
>>> from sympy.codegen.array_utils import CodegenArrayPermuteDims
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> cg = CodegenArrayPermuteDims(M, [1, 0])
The object ``cg`` represents the transposition of ``M``, as the permutation
``[1, 0]`` will act on its indices by switching them:
`M_{ij} \Rightarrow M_{ji}`
This is evident when transforming back to matrix form:
>>> from sympy.codegen.array_utils import recognize_matrix_expression
>>> recognize_matrix_expression(cg)
M.T
>>> N = MatrixSymbol("N", 3, 2)
>>> cg = CodegenArrayPermuteDims(N, [1, 0])
>>> cg.shape
(2, 3)
Permutations of tensor products are simplified in order to achieve a
standard form:
>>> from sympy.codegen.array_utils import CodegenArrayTensorProduct
>>> M = MatrixSymbol("M", 4, 5)
>>> tp = CodegenArrayTensorProduct(M, N)
>>> tp.shape
(4, 5, 3, 2)
>>> perm1 = CodegenArrayPermuteDims(tp, [2, 3, 1, 0])
The args ``(M, N)`` have been sorted and the permutation has been
simplified, the expression is equivalent:
>>> perm1.expr.args
(N, M)
>>> perm1.shape
(3, 2, 5, 4)
>>> perm1.permutation
(2 3)
The permutation in its array form has been simplified from
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
product `M` and `N` have been switched:
>>> perm1.permutation.array_form
[0, 1, 3, 2]
We can nest a second permutation:
>>> perm2 = CodegenArrayPermuteDims(perm1, [1, 0, 2, 3])
>>> perm2.shape
(2, 3, 5, 4)
>>> perm2.permutation.array_form
[1, 0, 3, 2]
"""
def __new__(cls, expr, permutation, nest_permutation=True):
from sympy.combinatorics import Permutation
expr = _sympify(expr)
permutation = Permutation(permutation)
permutation_size = permutation.size
expr_rank = get_rank(expr)
if permutation_size != expr_rank:
raise ValueError("Permutation size must be the length of the shape of expr")
if isinstance(expr, CodegenArrayPermuteDims):
subexpr = expr.expr
subperm = expr.permutation
permutation = permutation * subperm
expr = subexpr
if isinstance(expr, CodegenArrayContraction):
expr, permutation = cls._handle_nested_contraction(expr, permutation)
if isinstance(expr, CodegenArrayTensorProduct):
expr, permutation = cls._sort_components(expr, permutation)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
plist = permutation.array_form
if plist == sorted(plist):
return expr
obj = Basic.__new__(cls, expr, permutation)
obj._subranks = [get_rank(expr)]
shape = expr.shape
if shape is None:
obj._shape = None
else:
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
return obj
@property
def expr(self):
return self.args[0]
@property
def permutation(self):
return self.args[1]
@classmethod
def _sort_components(cls, expr, permutation):
# Get the permutation in its image-form:
perm_image_form = _af_invert(permutation.array_form)
args = list(expr.args)
# Starting index global position for every arg:
cumul = list(accumulate([0] + expr.subranks))
# Split `perm_image_form` into a list of list corresponding to the indices
# of every argument:
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
# Create an index, target-position-key array:
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
# Sort the array according to the target-position-key:
# In this way, we define a canonical way to sort the arguments according
# to the permutation.
ps.sort(key=lambda x: x[1])
# Read the inverse-permutation (i.e. image-form) of the args:
perm_args_image_form = [i[0] for i in ps]
# Apply the args-permutation to the `args`:
args_sorted = [args[i] for i in perm_args_image_form]
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
return CodegenArrayTensorProduct(*args_sorted), new_permutation
@classmethod
def _handle_nested_contraction(cls, expr, permutation):
if not isinstance(expr, CodegenArrayContraction):
return expr, permutation
if not isinstance(expr.expr, CodegenArrayTensorProduct):
return expr, permutation
args = expr.expr.args
contraction_indices = expr.contraction_indices
contraction_indices_flat = [j for i in contraction_indices for j in i]
cumul = list(accumulate([0] + expr.subranks))
# Spread the permutation in its array form across the args in the corresponding
# tensor-product arguments with free indices:
permutation_array_blocks_up = []
image_form = _af_invert(permutation.array_form)
counter = 0
for i, e in enumerate(expr.subranks):
current = []
for j in range(cumul[i], cumul[i+1]):
if j in contraction_indices_flat:
continue
current.append(image_form[counter])
counter += 1
permutation_array_blocks_up.append(current)
# Get the map of axis repositioning for every argument of tensor-product:
index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)]
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
inverse_permutation = permutation**(-1)
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
# Sorting key is a list of tuple, first element is the index of `args`, second element of
# the tuple is the sorting key to sort `args` of the tensor product:
sorting_keys = list(enumerate(index_blocks_up_permuted))
sorting_keys.sort(key=lambda x: x[1])
# Now we can get the permutation acting on the args in its image-form:
new_perm_image_form = [i[0] for i in sorting_keys]
# Apply the args-level permutation to various elements:
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
new_args = [args[i] for i in new_perm_image_form]
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
new_expr = CodegenArrayContraction(CodegenArrayTensorProduct(*new_args), *new_contraction_indices)
new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
return new_expr, new_permutation
@classmethod
def _check_permutation_mapping(cls, expr, permutation):
subranks = expr.subranks
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
permuted_indices = [permutation(i) for i in range(expr.subrank())]
new_args = list(expr.args)
arg_candidate_index = index2arg[permuted_indices[0]]
current_indices = []
new_permutation = []
inserted_arg_cand_indices = set([])
for i, idx in enumerate(permuted_indices):
if index2arg[idx] != arg_candidate_index:
new_permutation.extend(current_indices)
current_indices = []
arg_candidate_index = index2arg[idx]
current_indices.append(idx)
arg_candidate_rank = subranks[arg_candidate_index]
if len(current_indices) == arg_candidate_rank:
new_permutation.extend(sorted(current_indices))
local_current_indices = [j - min(current_indices) for j in current_indices]
i1 = index2arg[i]
new_args[i1] = CodegenArrayPermuteDims(new_args[i1], Permutation(local_current_indices))
inserted_arg_cand_indices.add(arg_candidate_index)
current_indices = []
new_permutation.extend(current_indices)
# TODO: swap args positions in order to simplify the expression:
# TODO: this should be in a function
args_positions = list(range(len(new_args)))
# Get possible shifts:
maps = {}
cumulative_subranks = [0] + list(accumulate(subranks))
for i in range(0, len(subranks)):
s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])])
if len(s) != 1:
continue
elem = next(iter(s))
if i != elem:
maps[i] = elem
# Find cycles in the map:
lines = []
current_line = []
while maps:
if len(current_line) == 0:
k, v = maps.popitem()
current_line.append(k)
else:
k = current_line[-1]
if k not in maps:
current_line = []
continue
v = maps.pop(k)
if v in current_line:
lines.append(current_line)
current_line = []
continue
current_line.append(v)
for line in lines:
for i, e in enumerate(line):
args_positions[line[(i + 1) % len(line)]] = e
# TODO: function in order to permute the args:
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
new_args = [new_args[i] for i in args_positions]
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
new_permutation2 = [j for i in new_permutation_blocks for j in i]
return CodegenArrayTensorProduct(*new_args), Permutation(new_permutation2) # **(-1)
@classmethod
def _check_if_there_are_closed_cycles(cls, expr, permutation):
args = list(expr.args)
subranks = expr.subranks
cyclic_form = permutation.cyclic_form
cumulative_subranks = [0] + list(accumulate(subranks))
cyclic_min = [min(i) for i in cyclic_form]
cyclic_max = [max(i) for i in cyclic_form]
cyclic_keep = []
for i, cycle in enumerate(cyclic_form):
flag = True
for j in range(0, len(cumulative_subranks) - 1):
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
# Found a sinkable cycle.
args[j] = CodegenArrayPermuteDims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
flag = False
break
if flag:
cyclic_keep.append(cyclic_form[i])
return CodegenArrayTensorProduct(*args), Permutation(cyclic_keep, size=permutation.size)
def nest_permutation(self):
r"""
DEPRECATED.
"""
ret = self._nest_permutation(self.expr, self.permutation)
if ret is None:
return self
return ret
@classmethod
def _nest_permutation(cls, expr, permutation):
if isinstance(expr, CodegenArrayTensorProduct):
return CodegenArrayPermuteDims(*cls._check_if_there_are_closed_cycles(expr, permutation))
elif isinstance(expr, CodegenArrayContraction):
# Invert tree hierarchy: put the contraction above.
cycles = permutation.cyclic_form
newcycles = CodegenArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
newpermutation = Permutation(newcycles)
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
return CodegenArrayContraction(CodegenArrayPermuteDims(expr.expr, newpermutation), *new_contr_indices)
elif isinstance(expr, CodegenArrayElementwiseAdd):
return CodegenArrayElementwiseAdd(*[CodegenArrayPermuteDims(arg, permutation) for arg in expr.args])
return None
def nest_permutation(expr):
if isinstance(expr, CodegenArrayPermuteDims):
return expr.nest_permutation()
else:
return expr
class CodegenArrayDiagonal(_CodegenArrayAbstract):
r"""
Class to represent the diagonal operator.
Explanation
===========
In a 2-dimensional array it returns the diagonal, this looks like the
operation:
`A_{ij} \rightarrow A_{ii}`
The diagonal over axes 1 and 2 (the second and third) of the tensor product
of two 2-dimensional arrays `A \otimes B` is
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
In this last example the array expression has been reduced from
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
rather there is a new index `i` for the diagonal, contraction would have
reduced the array to 2 dimensions.
Notice that the diagonalized out dimensions are added as new dimensions at
the end of the indices.
"""
def __new__(cls, expr, *diagonal_indices):
expr = _sympify(expr)
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
if isinstance(expr, CodegenArrayElementwiseAdd):
return CodegenArrayElementwiseAdd(*[CodegenArrayDiagonal(arg, *diagonal_indices) for arg in expr.args])
if isinstance(expr, CodegenArrayDiagonal):
return cls._flatten(expr, *diagonal_indices)
if isinstance(expr, CodegenArrayPermuteDims):
return cls._handle_nested_permutedims_in_diag(expr, *diagonal_indices)
shape = expr.shape
if shape is not None:
cls._validate(expr, *diagonal_indices)
# Get new shape:
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
else:
positions = None
if len(diagonal_indices) == 0:
return expr
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*shape)
obj = Basic.__new__(cls, expr, *diagonal_indices)
obj._positions = positions
obj._subranks = _get_subranks(expr)
obj._shape = shape
return obj
@staticmethod
def _validate(expr, *diagonal_indices):
# Check that no diagonalization happens on indices with mismatched
# dimensions:
shape = expr.shape
for i in diagonal_indices:
if len({shape[j] for j in i}) != 1:
raise ValueError("diagonalizing indices of different dimensions")
if len(i) <= 1:
raise ValueError("need at least two axes to diagonalize")
@staticmethod
def _remove_trivial_dimensions(shape, *diagonal_indices):
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
@property
def expr(self):
return self.args[0]
@property
def diagonal_indices(self):
return self.args[1:]
@staticmethod
def _flatten(expr, *outer_diagonal_indices):
inner_diagonal_indices = expr.diagonal_indices
all_inner = [j for i in inner_diagonal_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
return CodegenArrayDiagonal(expr.expr, *diagonal_indices)
@classmethod
def _handle_nested_permutedims_in_diag(cls, expr: CodegenArrayPermuteDims, *diagonal_indices):
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
back_nondiag = [expr.permutation(i) for i in nondiag]
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
new_permutation1 = [remap[i] for i in back_nondiag]
shift = len(new_permutation1)
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
new_permutation = new_permutation1 + diag_block_perm
return CodegenArrayPermuteDims(
CodegenArrayDiagonal(
expr.expr,
*back_diagonal_indices
),
new_permutation
)
def _push_indices_down_nonstatic(self, indices):
transform = lambda x: self._positions[x] if x < len(self._positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
def _push_indices_up_nonstatic(self, indices):
def transform(x):
for i, e in enumerate(self._positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_down(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
transform = lambda x: positions[x] if x < len(positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
def transform(x):
for i, e in enumerate(positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
def transform_to_product(self):
from sympy import ask, Q
diagonal_indices = self.diagonal_indices
if isinstance(self.expr, CodegenArrayContraction):
# invert Diagonal and Contraction:
diagonal_down = CodegenArrayContraction._push_indices_down(
self.expr.contraction_indices,
diagonal_indices
)
newexpr = CodegenArrayDiagonal(
self.expr.expr,
*diagonal_down
).transform_to_product()
contraction_up = newexpr._push_indices_up(
diagonal_down,
self.expr.contraction_indices
)
return CodegenArrayContraction(
newexpr,
*contraction_up
)
if not isinstance(self.expr, CodegenArrayTensorProduct):
return self
args = list(self.expr.args)
# TODO: unify API
subranks = [get_rank(i) for i in args]
# TODO: unify API
mapping = _get_mapping_from_subranks(subranks)
new_contraction_indices = []
drop_diagonal_indices = []
for indl, links in enumerate(diagonal_indices):
if len(links) > 2:
continue
# Also consider the case of diagonal matrices being contracted:
current_dimension = self.expr.shape[links[0]]
if current_dimension == 1:
drop_diagonal_indices.append(indl)
continue
tuple_links = [mapping[i] for i in links]
arg_indices, arg_positions = zip(*tuple_links)
if len(arg_indices) != len(set(arg_indices)):
# Maybe trace should be supported?
raise NotImplementedError
args_updates = {}
count_nondiagonal = 0
last = None
expression_is_square = False
# Check that all args are vectors:
for arg_ind, arg_pos in tuple_links:
mat = args[arg_ind]
if 1 in mat.shape and mat.shape != (1, 1):
args_updates[arg_ind] = DiagMatrix(mat)
last = arg_ind
else:
expression_is_square = True
if not ask(Q.diagonal(mat)):
count_nondiagonal += 1
if count_nondiagonal > 1:
break
if count_nondiagonal > 1:
continue
# TODO: if count_nondiagonal == 0 then the sub-expression can be recognized as HadamardProduct.
for arg_ind, newmat in args_updates.items():
if not expression_is_square and arg_ind == last:
continue
args[arg_ind] = newmat
drop_diagonal_indices.append(indl)
new_contraction_indices.append(links)
new_diagonal_indices = CodegenArrayContraction._push_indices_up(
new_contraction_indices,
[e for i, e in enumerate(diagonal_indices) if i not in drop_diagonal_indices]
)
return CodegenArrayDiagonal(
CodegenArrayContraction(
CodegenArrayTensorProduct(*args),
*new_contraction_indices
),
*new_diagonal_indices
)
@classmethod
def _get_positions_shape(cls, shape, diagonal_indices):
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
pos1, shp1 = zip(*data1) if data1 else ((), ())
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
pos2, shp2 = zip(*data2) if data2 else ((), ())
positions = pos1 + pos2
shape = shp1 + shp2
return positions, shape
def get_rank(expr):
if isinstance(expr, (MatrixExpr, MatrixElement)):
return 2
if isinstance(expr, _CodegenArrayAbstract):
return len(expr.shape)
if isinstance(expr, NDimArray):
return expr.rank()
if isinstance(expr, Indexed):
return expr.rank
if isinstance(expr, IndexedBase):
shape = expr.shape
if shape is None:
return -1
else:
return len(shape)
if hasattr(expr, "shape"):
return len(expr.shape)
return 0
def _get_subrank(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subrank()
return get_rank(expr)
def _get_subranks(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subranks
else:
return [get_rank(expr)]
def _get_mapping_from_subranks(subranks):
mapping = {}
counter = 0
for i, rank in enumerate(subranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def _get_contraction_links(args, subranks, *contraction_indices):
mapping = _get_mapping_from_subranks(subranks)
contraction_tuples = [[mapping[j] for j in i] for i in contraction_indices]
dlinks = defaultdict(dict)
for links in contraction_tuples:
if len(links) == 2:
(arg1, pos1), (arg2, pos2) = links
dlinks[arg1][pos1] = (arg2, pos2)
dlinks[arg2][pos2] = (arg1, pos1)
continue
return args, dict(dlinks)
def _sort_contraction_indices(pairing_indices):
pairing_indices = [Tuple(*sorted(i)) for i in pairing_indices]
pairing_indices.sort(key=lambda x: min(x))
return pairing_indices
def _get_diagonal_indices(flattened_indices):
axes_contraction = defaultdict(list)
for i, ind in enumerate(flattened_indices):
if isinstance(ind, (int, Integer)):
# If the indices is a number, there can be no diagonal operation:
continue
axes_contraction[ind].append(i)
axes_contraction = {k: v for k, v in axes_contraction.items() if len(v) > 1}
# Put the diagonalized indices at the end:
ret_indices = [i for i in flattened_indices if i not in axes_contraction]
diag_indices = list(axes_contraction)
diag_indices.sort(key=lambda x: flattened_indices.index(x))
diagonal_indices = [tuple(axes_contraction[i]) for i in diag_indices]
ret_indices += diag_indices
ret_indices = tuple(ret_indices)
return diagonal_indices, ret_indices
def _get_argindex(subindices, ind):
for i, sind in enumerate(subindices):
if ind == sind:
return i
if isinstance(sind, (set, frozenset)) and ind in sind:
return i
raise IndexError("%s not found in %s" % (ind, subindices))
def _codegen_array_parse(expr):
if isinstance(expr, Sum):
function = expr.function
summation_indices = expr.variables
subexpr, subindices = _codegen_array_parse(function)
# Check dimensional consistency:
shape = subexpr.shape
if shape:
for ind, istart, iend in expr.limits:
i = _get_argindex(subindices, ind)
if istart != 0 or iend+1 != shape[i]:
raise ValueError("summation index and array dimension mismatch: %s" % ind)
contraction_indices = []
subindices = list(subindices)
if isinstance(subexpr, CodegenArrayDiagonal):
diagonal_indices = list(subexpr.diagonal_indices)
dindices = subindices[-len(diagonal_indices):]
subindices = subindices[:-len(diagonal_indices)]
for index in summation_indices:
if index in dindices:
position = dindices.index(index)
contraction_indices.append(diagonal_indices[position])
diagonal_indices[position] = None
diagonal_indices = [i for i in diagonal_indices if i is not None]
for i, ind in enumerate(subindices):
if ind in summation_indices:
pass
if diagonal_indices:
subexpr = CodegenArrayDiagonal(subexpr.expr, *diagonal_indices)
else:
subexpr = subexpr.expr
axes_contraction = defaultdict(list)
for i, ind in enumerate(subindices):
if ind in summation_indices:
axes_contraction[ind].append(i)
subindices[i] = None
for k, v in axes_contraction.items():
contraction_indices.append(tuple(v))
free_indices = [i for i in subindices if i is not None]
indices_ret = list(free_indices)
indices_ret.sort(key=lambda x: free_indices.index(x))
return CodegenArrayContraction(
subexpr,
*contraction_indices,
free_indices=free_indices
), tuple(indices_ret)
if isinstance(expr, Mul):
args, indices = zip(*[_codegen_array_parse(arg) for arg in expr.args])
# Check if there are KroneckerDelta objects:
kronecker_delta_repl = {}
for arg in args:
if not isinstance(arg, KroneckerDelta):
continue
# Diagonalize two indices:
i, j = arg.indices
kindices = set(arg.indices)
if i in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[i])
if j in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[j])
kindices = frozenset(kindices)
for index in kindices:
kronecker_delta_repl[index] = kindices
# Remove KroneckerDelta objects, their relations should be handled by
# CodegenArrayDiagonal:
newargs = []
newindices = []
for arg, loc_indices in zip(args, indices):
if isinstance(arg, KroneckerDelta):
continue
newargs.append(arg)
newindices.append(loc_indices)
flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i]
diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices)
tp = CodegenArrayTensorProduct(*newargs)
if diagonal_indices:
return (CodegenArrayDiagonal(tp, *diagonal_indices), ret_indices)
else:
return tp, ret_indices
if isinstance(expr, MatrixElement):
indices = expr.args[1:]
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return (CodegenArrayDiagonal(expr.args[0], *diagonal_indices), ret_indices)
else:
return expr.args[0], ret_indices
if isinstance(expr, Indexed):
indices = expr.indices
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return (CodegenArrayDiagonal(expr.base, *diagonal_indices), ret_indices)
else:
return expr.args[0], ret_indices
if isinstance(expr, IndexedBase):
raise NotImplementedError
if isinstance(expr, KroneckerDelta):
return expr, expr.indices
if isinstance(expr, Add):
args, indices = zip(*[_codegen_array_parse(arg) for arg in expr.args])
args = list(args)
# Check if all indices are compatible. Otherwise expand the dimensions:
index0set = set(indices[0])
index0 = indices[0]
for i in range(1, len(args)):
if set(indices[i]) != index0set:
raise NotImplementedError("indices must be the same")
permutation = Permutation([index0.index(j) for j in indices[i]])
# Perform index permutations:
args[i] = CodegenArrayPermuteDims(args[i], permutation)
return CodegenArrayElementwiseAdd(*args), index0
return expr, ()
def parse_matrix_expression(expr: MatrixExpr) -> Basic:
if isinstance(expr, MatMul):
args_nonmat = []
args = []
for arg in expr.args:
if isinstance(arg, MatrixExpr):
args.append(arg)
else:
args_nonmat.append(arg)
contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)]
scalar = Mul.fromiter(args_nonmat)
if scalar == 1:
tprod = CodegenArrayTensorProduct(
*[parse_matrix_expression(arg) for arg in args])
else:
tprod = CodegenArrayTensorProduct(
scalar,
*[parse_matrix_expression(arg) for arg in args])
return CodegenArrayContraction(
tprod,
*contractions
)
elif isinstance(expr, MatAdd):
return CodegenArrayElementwiseAdd(
*[parse_matrix_expression(arg) for arg in expr.args]
)
elif isinstance(expr, Transpose):
return CodegenArrayPermuteDims(
parse_matrix_expression(expr.args[0]), [1, 0]
)
elif isinstance(expr, Trace):
inner_expr = parse_matrix_expression(expr.arg)
return CodegenArrayContraction(inner_expr, (0, len(inner_expr.shape) - 1))
else:
return expr
def parse_indexed_expression(expr, first_indices=None):
r"""
Parse indexed expression into a form useful for code generation.
Examples
========
>>> from sympy.codegen.array_utils import parse_indexed_expression
>>> from sympy import MatrixSymbol, Sum, symbols
>>> i, j, k, d = symbols("i j k d")
>>> M = MatrixSymbol("M", d, d)
>>> N = MatrixSymbol("N", d, d)
Recognize the trace in summation form:
>>> expr = Sum(M[i, i], (i, 0, d-1))
>>> parse_indexed_expression(expr)
CodegenArrayContraction(M, (0, 1))
Recognize the extraction of the diagonal by using the same index `i` on
both axes of the matrix:
>>> expr = M[i, i]
>>> parse_indexed_expression(expr)
CodegenArrayDiagonal(M, (0, 1))
This function can help perform the transformation expressed in two
different mathematical notations as:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Recognize the matrix multiplication in summation form:
>>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1))
>>> parse_indexed_expression(expr)
CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2))
Specify that ``k`` has to be the starting index:
>>> parse_indexed_expression(expr, first_indices=[k])
CodegenArrayContraction(CodegenArrayTensorProduct(N, M), (0, 3))
"""
result, indices = _codegen_array_parse(expr)
if not first_indices:
return result
for i in first_indices:
if i not in indices:
first_indices.remove(i)
first_indices.extend([i for i in indices if i not in first_indices])
permutation = [first_indices.index(i) for i in indices]
return CodegenArrayPermuteDims(result, permutation)
def _a2m_mul(*args):
if all(not isinstance(i, _CodegenArrayAbstract) for i in args):
return MatMul(*args).doit()
else:
return CodegenArrayContraction(
CodegenArrayTensorProduct(*args),
*[(2*i-1, 2*i) for i in range(1, len(args))]
)
def _a2m_tensor_product(*args):
scalars = []
arrays = []
for arg in args:
if isinstance(arg, (MatrixExpr, _CodegenArrayAbstract)):
arrays.append(arg)
else:
scalars.append(arg)
scalar = Mul.fromiter(scalars)
if len(arrays) == 0:
return scalar
if scalar != 1:
if isinstance(arrays[0], _CodegenArrayAbstract):
arrays = [scalar] + arrays
else:
arrays[0] *= scalar
return CodegenArrayTensorProduct(*arrays)
def _a2m_add(*args):
if all(not isinstance(i, _CodegenArrayAbstract) for i in args):
return MatAdd(*args).doit()
else:
return CodegenArrayElementwiseAdd(*args)
def _a2m_trace(arg):
if isinstance(arg, _CodegenArrayAbstract):
return CodegenArrayContraction(arg, (0, 1))
else:
return Trace(arg)
def _a2m_transpose(arg):
if isinstance(arg, _CodegenArrayAbstract):
return CodegenArrayPermuteDims(arg, [1, 0])
else:
return Transpose(arg)
def _support_function_tp1_recognize(contraction_indices, args):
if not isinstance(args, list):
args = [args]
subranks = [get_rank(i) for i in args]
coeff = reduce(lambda x, y: x*y, [arg for arg, srank in zip(args, subranks) if srank == 0], S.One)
mapping = _get_mapping_from_subranks(subranks)
reverse_mapping = {v: k for k, v in mapping.items()}
args, dlinks = _get_contraction_links(args, subranks, *contraction_indices)
flatten_contractions = [j for i in contraction_indices for j in i]
total_rank = sum(subranks)
# TODO: turn `free_indices` into a list?
free_indices = {i: i for i in range(total_rank) if i not in flatten_contractions}
return_list = []
while free_indices or dlinks:
if free_indices:
first_index, starting_argind = min(free_indices.items(), key=lambda x: x[1])
free_indices.pop(first_index)
starting_argind, starting_pos = mapping[starting_argind]
else:
# Maybe a Trace
starting_argind = min(dlinks)
starting_pos = 0
current_argind, current_pos = starting_argind, starting_pos
matmul_args = []
last_index = None
while True:
elem = array2matrix(args[current_argind])
if current_pos == 1:
elem = _a2m_transpose(elem)
matmul_args.append(elem)
other_pos = 1 - current_pos
if current_argind not in dlinks:
other_absolute = reverse_mapping[current_argind, other_pos]
free_indices.pop(other_absolute, None)
break
link_dict = dlinks.pop(current_argind)
if other_pos not in link_dict:
if free_indices:
last_index = [i for i, j in free_indices.items() if mapping[j] == (current_argind, other_pos)][0]
else:
last_index = None
break
if len(link_dict) > 2:
raise NotImplementedError("not a matrix multiplication line")
# Get the last element of `link_dict` as the next link. The last
# element is the correct start for trace expressions:
current_argind, current_pos = link_dict[other_pos]
if current_argind == starting_argind:
# This is a trace:
if len(matmul_args) > 1:
matmul_args = [_a2m_trace(_a2m_mul(*matmul_args))]
elif args[current_argind].shape != (1, 1):
matmul_args = [_a2m_trace(*matmul_args)]
break
dlinks.pop(starting_argind, None)
free_indices.pop(last_index, None)
return_list.append(_a2m_mul(*matmul_args))
if coeff != 1:
# Let's inject the coefficient:
return_list[0] = coeff*return_list[0]
return _a2m_tensor_product(*return_list)
@singledispatch
def array2matrix(expr):
return expr
@array2matrix.register(ZeroArray)
def _(expr: ZeroArray):
if get_rank(expr) == 2:
return ZeroMatrix(*expr.shape)
else:
return expr
@array2matrix.register(CodegenArrayTensorProduct)
def _(expr: CodegenArrayTensorProduct):
return _a2m_tensor_product(*[array2matrix(arg) for arg in expr.args])
@array2matrix.register(CodegenArrayContraction)
def _(expr: CodegenArrayContraction):
expr = expr.flatten_contraction_of_diagonal()
expr = expr.split_multiple_contractions()
subexpr = expr.expr
contraction_indices: Tuple[Tuple[int]] = expr.contraction_indices
if isinstance(subexpr, CodegenArrayTensorProduct):
newexpr = CodegenArrayContraction(array2matrix(subexpr), *contraction_indices)
contraction_indices = newexpr.contraction_indices
if any(i > 2 for i in newexpr.subranks):
addends = CodegenArrayElementwiseAdd(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, CodegenArrayElementwiseAdd) else [i] for i in expr.expr.args])])
newexpr = CodegenArrayContraction(addends, *contraction_indices)
if isinstance(newexpr, CodegenArrayElementwiseAdd):
ret = array2matrix(newexpr)
return ret
assert isinstance(newexpr, CodegenArrayContraction)
ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args))
return ret
elif not isinstance(subexpr, _CodegenArrayAbstract):
ret = array2matrix(subexpr)
if isinstance(ret, MatrixExpr):
assert expr.contraction_indices == ((0, 1),)
return _a2m_trace(ret)
else:
return CodegenArrayContraction(ret, *expr.contraction_indices)
@array2matrix.register(CodegenArrayDiagonal)
def _(expr: CodegenArrayDiagonal):
pexpr = expr.transform_to_product()
if expr == pexpr:
return expr
return array2matrix(pexpr)
@array2matrix.register(CodegenArrayPermuteDims)
def _(expr: CodegenArrayPermuteDims):
if expr.permutation.array_form == [1, 0]:
return _a2m_transpose(array2matrix(expr.expr))
elif isinstance(expr.expr, CodegenArrayTensorProduct):
ranks = expr.expr.subranks
newrange = [expr.permutation(i) for i in range(sum(ranks))]
newpos = []
counter = 0
for rank in ranks:
newpos.append(newrange[counter:counter+rank])
counter += rank
newargs = []
newperm = []
for pos, arg in zip(newpos, expr.expr.args):
if pos == sorted(pos):
newargs.append((array2matrix(arg), pos[0]))
newperm.extend(pos)
elif len(pos) == 2:
newargs.append((_a2m_transpose(array2matrix(arg)), pos[0]))
newperm.extend(reversed(pos))
else:
raise NotImplementedError()
newargs = [i[0] for i in newargs]
return CodegenArrayPermuteDims(_a2m_tensor_product(*newargs), newperm)
elif isinstance(expr.expr, CodegenArrayContraction):
mat_mul_lines = array2matrix(expr.expr)
if not isinstance(mat_mul_lines, CodegenArrayTensorProduct):
flat_cyclic_form = [j for i in expr.permutation.cyclic_form for j in i]
expr_shape = get_shape(expr)
if all(expr_shape[i] == 1 for i in flat_cyclic_form):
return mat_mul_lines
raise NotImplementedError()
permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation
permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))]
args_array = [None for i in mat_mul_lines.args]
for i in range(len(mat_mul_lines.args)):
p1 = permuted[2*i]
p2 = permuted[2*i+1]
if p1 // 2 != p2 // 2:
return CodegenArrayPermuteDims(mat_mul_lines, permutation)
pos = p1 // 2
if p1 > p2:
args_array[i] = _a2m_transpose(mat_mul_lines.args[pos])
else:
args_array[i] = mat_mul_lines.args[pos]
return _a2m_tensor_product(*args_array)
else:
raise NotImplementedError()
@array2matrix.register(CodegenArrayElementwiseAdd)
def _(expr: CodegenArrayElementwiseAdd):
addends = [array2matrix(arg) for arg in expr.args]
return _a2m_add(*addends)
def _squash_trivial_dims_in_tensorproduct(expr):
if isinstance(expr, CodegenArrayTensorProduct):
return _a2m_tensor_product(*_suppress_trivial_dims_in_tensor_product(expr.args))
if isinstance(expr, CodegenArrayElementwiseAdd):
return _a2m_add(*[_squash_trivial_dims_in_tensorproduct(a) for a in expr.args])
return expr
def recognize_matrix_expression(expr):
r"""
Recognize matrix expressions in codegen objects.
If more than one matrix multiplication line have been detected, return a
list with the matrix expressions.
Examples
========
>>> from sympy import MatrixSymbol, Sum
>>> from sympy.abc import i, j, k, l, N
>>> from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
>>> from sympy.codegen.array_utils import recognize_matrix_expression, parse_indexed_expression, parse_matrix_expression
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> cg = parse_indexed_expression(expr)
>>> recognize_matrix_expression(cg)
A*B
>>> cg = parse_indexed_expression(expr, first_indices=[k])
>>> recognize_matrix_expression(cg)
B.T*A.T
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> cg = parse_indexed_expression(expr)
>>> recognize_matrix_expression(cg)
A.T*B
>>> cg = parse_indexed_expression(expr, first_indices=[k])
>>> recognize_matrix_expression(cg)
B.T*A
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> cg = parse_indexed_expression(expr)
>>> recognize_matrix_expression(cg)
Trace(A)
Recognize some more complex traces:
>>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1))
>>> cg = parse_indexed_expression(expr)
>>> recognize_matrix_expression(cg)
Trace(A*B)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> cg = parse_indexed_expression(expr)
>>> recognize_matrix_expression(cg)
A*B.T*A.T
Expressions constructed from matrix expressions do not contain literal
indices, the positions of free indices are returned instead:
>>> expr = A*B
>>> cg = parse_matrix_expression(expr)
>>> recognize_matrix_expression(cg)
A*B
If more than one line of matrix multiplications is detected, return
separate matrix multiplication factors embedded in a tensor product object:
>>> cg = CodegenArrayContraction(CodegenArrayTensorProduct(A, B, C, D), (1, 2), (5, 6))
>>> recognize_matrix_expression(cg)
CodegenArrayTensorProduct(A*B, C*D)
The two lines have free indices at axes 0, 3 and 4, 7, respectively.
"""
rec = array2matrix(expr)
rec = _squash_trivial_dims_in_tensorproduct(rec)
return rec
def _suppress_trivial_dims_in_tensor_product(mat_list):
# Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`.
# The matrix expression has to be equivalent to the tensor product of the
# matrices, with trivial dimensions (i.e. dim=1) dropped.
# That is, add contractions over trivial dimensions:
mat_11 = []
mat_k1 = []
mat_list = [i for i in mat_list if i != 1 and not getattr(i, "is_Identity", False)]
for mat in mat_list:
if mat.shape == (1, 1):
mat_11.append(mat)
elif 1 in mat.shape:
if mat.shape[0] == 1:
mat_k1.append(mat.T)
else:
mat_k1.append(mat)
else:
return mat_list
if len(mat_k1) > 2:
return mat_list
a = MatMul.fromiter(mat_k1[:1])
b = MatMul.fromiter(mat_k1[1:])
x = MatMul.fromiter(mat_11)
return [a*x*b.T]
def _apply_recursively_over_nested_lists(func, arr):
if isinstance(arr, (tuple, list, Tuple)):
return tuple(_apply_recursively_over_nested_lists(func, i) for i in arr)
elif isinstance(arr, Tuple):
return Tuple.fromiter(_apply_recursively_over_nested_lists(func, i) for i in arr)
else:
return func(arr)
def _build_push_indices_up_func_transformation(flattened_contraction_indices):
shifts = {0: 0}
i = 0
cumulative = 0
while i < len(flattened_contraction_indices):
j = 1
while i+j < len(flattened_contraction_indices):
if flattened_contraction_indices[i] + j != flattened_contraction_indices[i+j]:
break
j += 1
cumulative += j
shifts[flattened_contraction_indices[i]] = cumulative
i += j
shift_keys = sorted(shifts.keys())
def func(idx):
return shifts[shift_keys[bisect.bisect_right(shift_keys, idx)-1]]
def transform(j):
if j in flattened_contraction_indices:
return None
else:
return j - func(j)
return transform
def _build_push_indices_down_func_transformation(flattened_contraction_indices):
N = flattened_contraction_indices[-1]+2
shifts = [i for i in range(N) if i not in flattened_contraction_indices]
def transform(j):
if j < len(shifts):
return shifts[j]
else:
return j + shifts[-1] - len(shifts) + 1
return transform
|
4c8ad04b137abcc9098ce1238bbcea83c7f936d52cdd9b9de02a2e61d64dc85c | """
Classes and functions useful for rewriting expressions for optimized code
generation. Some languages (or standards thereof), e.g. C99, offer specialized
math functions for better performance and/or precision.
Using the ``optimize`` function in this module, together with a collection of
rules (represented as instances of ``Optimization``), one can rewrite the
expressions for this purpose::
>>> from sympy import Symbol, exp, log
>>> from sympy.codegen.rewriting import optimize, optims_c99
>>> x = Symbol('x')
>>> optimize(3*exp(2*x) - 3, optims_c99)
3*expm1(2*x)
>>> optimize(exp(2*x) - 3, optims_c99)
exp(2*x) - 3
>>> optimize(log(3*x + 3), optims_c99)
log1p(x) + log(3)
>>> optimize(log(2*x + 3), optims_c99)
log(2*x + 3)
The ``optims_c99`` imported above is tuple containing the following instances
(which may be imported from ``sympy.codegen.rewriting``):
- ``expm1_opt``
- ``log1p_opt``
- ``exp2_opt``
- ``log2_opt``
- ``log2const_opt``
"""
from itertools import chain
from sympy import cos, exp, log, Max, Min, Wild, expand_log, Dummy, sin, sinc
from sympy.assumptions import Q, ask
from sympy.codegen.cfunctions import log1p, log2, exp2, expm1
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core.expr import UnevaluatedExpr
from sympy.core.power import Pow
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
from sympy.core.mul import Mul
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.utilities.iterables import sift
class Optimization:
""" Abstract base class for rewriting optimization.
Subclasses should implement ``__call__`` taking an expression
as argument.
Parameters
==========
cost_function : callable returning number
priority : number
"""
def __init__(self, cost_function=None, priority=1):
self.cost_function = cost_function
self.priority=priority
class ReplaceOptim(Optimization):
""" Rewriting optimization calling replace on expressions.
Explanation
===========
The instance can be used as a function on expressions for which
it will apply the ``replace`` method (see
:meth:`sympy.core.basic.Basic.replace`).
Parameters
==========
query :
First argument passed to replace.
value :
Second argument passed to replace.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.rewriting import ReplaceOptim
>>> from sympy.codegen.cfunctions import exp2
>>> x = Symbol('x')
>>> exp2_opt = ReplaceOptim(lambda p: p.is_Pow and p.base == 2,
... lambda p: exp2(p.exp))
>>> exp2_opt(2**x)
exp2(x)
"""
def __init__(self, query, value, **kwargs):
super().__init__(**kwargs)
self.query = query
self.value = value
def __call__(self, expr):
return expr.replace(self.query, self.value)
def optimize(expr, optimizations):
""" Apply optimizations to an expression.
Parameters
==========
expr : expression
optimizations : iterable of ``Optimization`` instances
The optimizations will be sorted with respect to ``priority`` (highest first).
Examples
========
>>> from sympy import log, Symbol
>>> from sympy.codegen.rewriting import optims_c99, optimize
>>> x = Symbol('x')
>>> optimize(log(x+3)/log(2) + log(x**2 + 1), optims_c99)
log1p(x**2) + log2(x + 3)
"""
for optim in sorted(optimizations, key=lambda opt: opt.priority, reverse=True):
new_expr = optim(expr)
if optim.cost_function is None:
expr = new_expr
else:
before, after = map(lambda x: optim.cost_function(x), (expr, new_expr))
if before > after:
expr = new_expr
return expr
exp2_opt = ReplaceOptim(
lambda p: p.is_Pow and p.base == 2,
lambda p: exp2(p.exp)
)
_d = Wild('d', properties=[lambda x: x.is_Dummy])
_u = Wild('u', properties=[lambda x: not x.is_number and not x.is_Add])
_v = Wild('v')
_w = Wild('w')
_n = Wild('n', properties=[lambda x: x.is_number])
sinc_opt1 = ReplaceOptim(
sin(_w)/_w, sinc(_w)
)
sinc_opt2 = ReplaceOptim(
sin(_n*_w)/_w, _n*sinc(_n*_w)
)
sinc_opts = (sinc_opt1, sinc_opt2)
log2_opt = ReplaceOptim(_v*log(_w)/log(2), _v*log2(_w), cost_function=lambda expr: expr.count(
lambda e: ( # division & eval of transcendentals are expensive floating point operations...
e.is_Pow and e.exp.is_negative # division
or (isinstance(e, (log, log2)) and not e.args[0].is_number)) # transcendental
)
)
log2const_opt = ReplaceOptim(log(2)*log2(_w), log(_w))
logsumexp_2terms_opt = ReplaceOptim(
lambda l: (isinstance(l, log)
and l.args[0].is_Add
and len(l.args[0].args) == 2
and all(isinstance(t, exp) for t in l.args[0].args)),
lambda l: (
Max(*[e.args[0] for e in l.args[0].args]) +
log1p(exp(Min(*[e.args[0] for e in l.args[0].args])))
)
)
class _FuncMinusOne:
def __init__(self, func, func_m_1):
self.func = func
self.func_m_1 = func_m_1
def _try_func_m_1(self, expr):
protected, old_new = expr.replace(self.func, lambda arg: Dummy(), map=True)
factored = protected.factor()
new_old = {v: k for k, v in old_new.items()}
return factored.replace(_d - 1, lambda d: self.func_m_1(new_old[d].args[0])).xreplace(new_old)
def __call__(self, e):
numbers, non_num = sift(e.args, lambda arg: arg.is_number, binary=True)
non_num_func, non_num_other = sift(non_num, lambda arg: arg.has(self.func),
binary=True)
numsum = sum(numbers)
new_func_terms, done = [], False
for func_term in non_num_func:
if done:
new_func_terms.append(func_term)
else:
looking_at = func_term + numsum
attempt = self._try_func_m_1(looking_at)
if looking_at == attempt:
new_func_terms.append(func_term)
else:
done = True
new_func_terms.append(attempt)
if not done:
new_func_terms.append(numsum)
return e.func(*chain(new_func_terms, non_num_other))
expm1_opt = ReplaceOptim(lambda e: e.is_Add, _FuncMinusOne(exp, expm1))
cosm1_opt = ReplaceOptim(lambda e: e.is_Add, _FuncMinusOne(cos, cosm1))
log1p_opt = ReplaceOptim(
lambda e: isinstance(e, log),
lambda l: expand_log(l.replace(
log, lambda arg: log(arg.factor())
)).replace(log(_u+1), log1p(_u))
)
def create_expand_pow_optimization(limit, *, base_req=lambda b: b.is_symbol):
""" Creates an instance of :class:`ReplaceOptim` for expanding ``Pow``.
Explanation
===========
The requirements for expansions are that the base needs to be a symbol
and the exponent needs to be an Integer (and be less than or equal to
``limit``).
Parameters
==========
limit : int
The highest power which is expanded into multiplication.
base_req : function returning bool
Requirement on base for expansion to happen, default is to return
the ``is_symbol`` attribute of the base.
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.codegen.rewriting import create_expand_pow_optimization
>>> x = Symbol('x')
>>> expand_opt = create_expand_pow_optimization(3)
>>> expand_opt(x**5 + x**3)
x**5 + x*x*x
>>> expand_opt(x**5 + x**3 + sin(x)**3)
x**5 + sin(x)**3 + x*x*x
>>> opt2 = create_expand_pow_optimization(3 , base_req=lambda b: not b.is_Function)
>>> opt2((x+1)**2 + sin(x)**2)
sin(x)**2 + (x + 1)*(x + 1)
"""
return ReplaceOptim(
lambda e: e.is_Pow and base_req(e.base) and e.exp.is_Integer and abs(e.exp) <= limit,
lambda p: (
UnevaluatedExpr(Mul(*([p.base]*+p.exp), evaluate=False)) if p.exp > 0 else
1/UnevaluatedExpr(Mul(*([p.base]*-p.exp), evaluate=False))
))
# Optimization procedures for turning A**(-1) * x into MatrixSolve(A, x)
def _matinv_predicate(expr):
# TODO: We should be able to support more than 2 elements
if expr.is_MatMul and len(expr.args) == 2:
left, right = expr.args
if left.is_Inverse and right.shape[1] == 1:
inv_arg = left.arg
if isinstance(inv_arg, MatrixSymbol):
return bool(ask(Q.fullrank(left.arg)))
return False
def _matinv_transform(expr):
left, right = expr.args
inv_arg = left.arg
return MatrixSolve(inv_arg, right)
matinv_opt = ReplaceOptim(_matinv_predicate, _matinv_transform)
logaddexp_opt = ReplaceOptim(log(exp(_v)+exp(_w)), logaddexp(_v, _w))
logaddexp2_opt = ReplaceOptim(log(Pow(2, _v)+Pow(2, _w)), logaddexp2(_v, _w)*log(2))
# Collections of optimizations:
optims_c99 = (expm1_opt, log1p_opt, exp2_opt, log2_opt, log2const_opt)
optims_numpy = optims_c99 + (logaddexp_opt, logaddexp2_opt,) + sinc_opts
optims_scipy = (cosm1_opt,)
|
0fc52f7fd5e8a687c3503b915da983fded00080c19f88bf560c86d1ba4842528 | """
The contents of this file are the return value of
``sympy.assumptions.ask.compute_known_facts``.
Do NOT manually edit this file.
Instead, run ./bin/ask_update.py.
"""
from sympy.core.cache import cacheit
from sympy.logic.boolalg import And
from sympy.assumptions.cnf import Literal
from sympy.assumptions.ask import Q
# -{ Known facts as a set }-
@cacheit
def get_all_known_facts():
return {
frozenset((Literal(Q.algebraic, False), Literal(Q.complex, True), Literal(Q.finite, True), Literal(Q.transcendental, False))),
frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))),
frozenset((Literal(Q.algebraic, True), Literal(Q.complex, False))),
frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))),
frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))),
frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))),
frozenset((Literal(Q.antihermitian, True), Literal(Q.hermitian, True))),
frozenset((Literal(Q.complex, False), Literal(Q.imaginary, True))),
frozenset((Literal(Q.complex, False), Literal(Q.real, True))),
frozenset((Literal(Q.complex, False), Literal(Q.transcendental, True))),
frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))),
frozenset((Literal(Q.composite, True), Literal(Q.prime, True))),
frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))),
frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))),
frozenset((Literal(Q.even, False), Literal(Q.integer, True), Literal(Q.odd, False))),
frozenset((Literal(Q.even, False), Literal(Q.zero, True))),
frozenset((Literal(Q.even, True), Literal(Q.integer, False))),
frozenset((Literal(Q.even, True), Literal(Q.odd, True))),
frozenset((Literal(Q.extended_real, False), Literal(Q.infinite, True))),
frozenset((Literal(Q.extended_real, False), Literal(Q.real, True))),
frozenset((Literal(Q.extended_real, True), Literal(Q.infinite, False), Literal(Q.real, False))),
frozenset((Literal(Q.finite, False), Literal(Q.irrational, True))),
frozenset((Literal(Q.finite, False), Literal(Q.rational, True))),
frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))),
frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))),
frozenset((Literal(Q.finite, True), Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.real, True))),
frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))),
frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))),
frozenset((Literal(Q.hermitian, False), Literal(Q.real, True))),
frozenset((Literal(Q.imaginary, True), Literal(Q.real, True))),
frozenset((Literal(Q.integer, False), Literal(Q.odd, True))),
frozenset((Literal(Q.integer, False), Literal(Q.prime, True))),
frozenset((Literal(Q.integer, True), Literal(Q.rational, False))),
frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))),
frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))),
frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))),
frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))),
frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))),
frozenset((Literal(Q.invertible, True), Literal(Q.square, False))),
frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))),
frozenset((Literal(Q.irrational, True), Literal(Q.real, False))),
frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))),
frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))),
frozenset((Literal(Q.negative, False), Literal(Q.nonpositive, True), Literal(Q.zero, False))),
frozenset((Literal(Q.negative, False), Literal(Q.nonzero, True), Literal(Q.positive, False))),
frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.real, True), Literal(Q.zero, False))),
frozenset((Literal(Q.negative, True), Literal(Q.nonpositive, False))),
frozenset((Literal(Q.negative, True), Literal(Q.nonzero, False))),
frozenset((Literal(Q.negative, True), Literal(Q.positive, True))),
frozenset((Literal(Q.negative, True), Literal(Q.real, False))),
frozenset((Literal(Q.negative, True), Literal(Q.zero, True))),
frozenset((Literal(Q.nonnegative, False), Literal(Q.positive, True))),
frozenset((Literal(Q.nonnegative, False), Literal(Q.zero, True))),
frozenset((Literal(Q.nonnegative, True), Literal(Q.positive, False), Literal(Q.zero, False))),
frozenset((Literal(Q.nonpositive, False), Literal(Q.zero, True))),
frozenset((Literal(Q.nonzero, False), Literal(Q.positive, True))),
frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))),
frozenset((Literal(Q.normal, True), Literal(Q.square, False))),
frozenset((Literal(Q.orthogonal, False), Literal(Q.real, True), Literal(Q.unitary, True))),
frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))),
frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))),
frozenset((Literal(Q.positive, False), Literal(Q.prime, True))),
frozenset((Literal(Q.positive, True), Literal(Q.real, False))),
frozenset((Literal(Q.positive, True), Literal(Q.zero, True))),
frozenset((Literal(Q.rational, True), Literal(Q.real, False))),
frozenset((Literal(Q.real, False), Literal(Q.zero, True))),
frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))),
frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))),
frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True)))
}
# -{ Known facts in Conjunctive Normal Form }-
@cacheit
def get_known_facts_cnf():
return And(
Q.invertible | Q.singular,
Q.algebraic | ~Q.rational,
Q.antihermitian | ~Q.imaginary,
Q.complex_elements | ~Q.real_elements,
Q.complex | ~Q.algebraic,
Q.complex | ~Q.imaginary,
Q.complex | ~Q.real,
Q.complex | ~Q.transcendental,
Q.even | ~Q.zero,
Q.extended_real | ~Q.infinite,
Q.extended_real | ~Q.real,
Q.finite | ~Q.algebraic,
Q.finite | ~Q.irrational,
Q.finite | ~Q.rational,
Q.finite | ~Q.transcendental,
Q.fullrank | ~Q.invertible,
Q.hermitian | ~Q.real,
Q.integer | ~Q.even,
Q.integer | ~Q.odd,
Q.integer | ~Q.prime,
Q.invertible | ~Q.positive_definite,
Q.invertible | ~Q.unitary,
Q.lower_triangular | ~Q.diagonal,
Q.nonnegative | ~Q.positive,
Q.nonnegative | ~Q.zero,
Q.nonpositive | ~Q.negative,
Q.nonpositive | ~Q.zero,
Q.nonzero | ~Q.negative,
Q.nonzero | ~Q.positive,
Q.normal | ~Q.diagonal,
Q.normal | ~Q.unitary,
Q.positive_definite | ~Q.orthogonal,
Q.positive | ~Q.prime,
Q.rational | ~Q.integer,
Q.real_elements | ~Q.integer_elements,
Q.real | ~Q.irrational,
Q.real | ~Q.negative,
Q.real | ~Q.positive,
Q.real | ~Q.rational,
Q.real | ~Q.zero,
Q.square | ~Q.invertible,
Q.square | ~Q.normal,
Q.square | ~Q.symmetric,
Q.symmetric | ~Q.diagonal,
Q.triangular | ~Q.lower_triangular,
Q.triangular | ~Q.unit_triangular,
Q.triangular | ~Q.upper_triangular,
Q.unitary | ~Q.orthogonal,
Q.upper_triangular | ~Q.diagonal,
~Q.algebraic | ~Q.transcendental,
~Q.antihermitian | ~Q.hermitian,
~Q.composite | ~Q.prime,
~Q.even | ~Q.odd,
~Q.finite | ~Q.infinite,
~Q.imaginary | ~Q.real,
~Q.invertible | ~Q.singular,
~Q.irrational | ~Q.rational,
~Q.negative | ~Q.positive,
~Q.negative | ~Q.zero,
~Q.positive | ~Q.zero,
Q.even | Q.odd | ~Q.integer,
Q.infinite | Q.real | ~Q.extended_real,
Q.lower_triangular | Q.upper_triangular | ~Q.triangular,
Q.negative | Q.positive | ~Q.nonzero,
Q.negative | Q.zero | ~Q.nonpositive,
Q.positive | Q.zero | ~Q.nonnegative,
Q.diagonal | ~Q.lower_triangular | ~Q.upper_triangular,
Q.invertible | ~Q.fullrank | ~Q.square,
Q.orthogonal | ~Q.real | ~Q.unitary,
Q.negative | Q.positive | Q.zero | ~Q.real,
Q.algebraic | Q.transcendental | ~Q.complex | ~Q.finite,
Q.irrational | Q.rational | ~Q.finite | ~Q.real
)
# -{ Known facts in compressed sets }-
@cacheit
def get_known_facts_dict():
return {
Q.algebraic: set([Q.algebraic, Q.complex, Q.finite]),
Q.antihermitian: set([Q.antihermitian]),
Q.commutative: set([Q.commutative]),
Q.complex: set([Q.complex]),
Q.complex_elements: set([Q.complex_elements]),
Q.composite: set([Q.composite]),
Q.diagonal: set([Q.diagonal, Q.lower_triangular, Q.normal, Q.square,
Q.symmetric, Q.triangular, Q.upper_triangular]),
Q.even: set([Q.algebraic, Q.complex, Q.even, Q.extended_real,
Q.finite, Q.hermitian, Q.integer, Q.rational, Q.real]),
Q.extended_real: set([Q.extended_real]),
Q.finite: set([Q.finite]),
Q.fullrank: set([Q.fullrank]),
Q.hermitian: set([Q.hermitian]),
Q.imaginary: set([Q.antihermitian, Q.complex, Q.imaginary]),
Q.infinite: set([Q.extended_real, Q.infinite]),
Q.integer: set([Q.algebraic, Q.complex, Q.extended_real, Q.finite,
Q.hermitian, Q.integer, Q.rational, Q.real]),
Q.integer_elements: set([Q.complex_elements, Q.integer_elements,
Q.real_elements]),
Q.invertible: set([Q.fullrank, Q.invertible, Q.square]),
Q.irrational: set([Q.complex, Q.extended_real, Q.finite, Q.hermitian,
Q.irrational, Q.nonzero, Q.real]),
Q.is_true: set([Q.is_true]),
Q.lower_triangular: set([Q.lower_triangular, Q.triangular]),
Q.negative: set([Q.complex, Q.extended_real, Q.hermitian, Q.negative,
Q.nonpositive, Q.nonzero, Q.real]),
Q.nonnegative: set([Q.complex, Q.extended_real, Q.hermitian,
Q.nonnegative, Q.real]),
Q.nonpositive: set([Q.complex, Q.extended_real, Q.hermitian,
Q.nonpositive, Q.real]),
Q.nonzero: set([Q.complex, Q.extended_real, Q.hermitian, Q.nonzero,
Q.real]),
Q.normal: set([Q.normal, Q.square]),
Q.odd: set([Q.algebraic, Q.complex, Q.extended_real, Q.finite,
Q.hermitian, Q.integer, Q.nonzero, Q.odd, Q.rational, Q.real]),
Q.orthogonal: set([Q.fullrank, Q.invertible, Q.normal, Q.orthogonal,
Q.positive_definite, Q.square, Q.unitary]),
Q.positive: set([Q.complex, Q.extended_real, Q.hermitian,
Q.nonnegative, Q.nonzero, Q.positive, Q.real]),
Q.positive_definite: set([Q.fullrank, Q.invertible,
Q.positive_definite, Q.square]),
Q.prime: set([Q.algebraic, Q.complex, Q.extended_real, Q.finite,
Q.hermitian, Q.integer, Q.nonnegative, Q.nonzero, Q.positive,
Q.prime, Q.rational, Q.real]),
Q.rational: set([Q.algebraic, Q.complex, Q.extended_real, Q.finite,
Q.hermitian, Q.rational, Q.real]),
Q.real: set([Q.complex, Q.extended_real, Q.hermitian, Q.real]),
Q.real_elements: set([Q.complex_elements, Q.real_elements]),
Q.singular: set([Q.singular]),
Q.square: set([Q.square]),
Q.symmetric: set([Q.square, Q.symmetric]),
Q.transcendental: set([Q.complex, Q.finite, Q.transcendental]),
Q.triangular: set([Q.triangular]),
Q.unit_triangular: set([Q.triangular, Q.unit_triangular]),
Q.unitary: set([Q.fullrank, Q.invertible, Q.normal, Q.square,
Q.unitary]),
Q.upper_triangular: set([Q.triangular, Q.upper_triangular]),
Q.zero: set([Q.algebraic, Q.complex, Q.even, Q.extended_real,
Q.finite, Q.hermitian, Q.integer, Q.nonnegative,
Q.nonpositive, Q.rational, Q.real, Q.zero]),
}
|
a563257e0e2ce6848c4d9fda3a0a6b2d3f198e821b4f31c4f7f5ccec7e03ebeb | from typing import Dict, Callable
from sympy.core import S, Add, Expr, Basic, Mul
from sympy.logic.boolalg import Boolean
from sympy.assumptions import Q, ask # type: ignore
def refine(expr, assumptions=True):
"""
Simplify an expression using assumptions.
Explanation
===========
Unlike :func:`~.simplify()` which performs structural simplification
without any assumption, this function transforms the expression into
the form which is only valid under certain assumptions. Note that
``simplify()`` is generally not done in refining process.
Refining boolean expression involves reducing it to ``True`` or
``False``. Unlike :func:~.`ask()`, the expression will not be reduced
if the truth value cannot be determined.
Examples
========
>>> from sympy import refine, sqrt, Q
>>> from sympy.abc import x
>>> refine(sqrt(x**2), Q.real(x))
Abs(x)
>>> refine(sqrt(x**2), Q.positive(x))
x
>>> refine(Q.real(x), Q.positive(x))
True
>>> refine(Q.positive(x), Q.real(x))
Q.positive(x)
See Also
========
sympy.simplify.simplify.simplify : Structural simplification without assumptions.
sympy.assumptions.ask.ask : Query for boolean expressions using assumptions.
"""
if not isinstance(expr, Basic):
return expr
if not expr.is_Atom:
args = [refine(arg, assumptions) for arg in expr.args]
# TODO: this will probably not work with Integral or Polynomial
expr = expr.func(*args)
if hasattr(expr, '_eval_refine'):
ref_expr = expr._eval_refine(assumptions)
if ref_expr is not None:
return ref_expr
name = expr.__class__.__name__
handler = handlers_dict.get(name, None)
if handler is None:
return expr
new_expr = handler(expr, assumptions)
if (new_expr is None) or (expr == new_expr):
return expr
if not isinstance(new_expr, Expr):
return new_expr
return refine(new_expr, assumptions)
def refine_abs(expr, assumptions):
"""
Handler for the absolute value.
Examples
========
>>> from sympy import Q, Abs
>>> from sympy.assumptions.refine import refine_abs
>>> from sympy.abc import x
>>> refine_abs(Abs(x), Q.real(x))
>>> refine_abs(Abs(x), Q.positive(x))
x
>>> refine_abs(Abs(x), Q.negative(x))
-x
"""
from sympy.core.logic import fuzzy_not
from sympy import Abs
arg = expr.args[0]
if ask(Q.real(arg), assumptions) and \
fuzzy_not(ask(Q.negative(arg), assumptions)):
# if it's nonnegative
return arg
if ask(Q.negative(arg), assumptions):
return -arg
# arg is Mul
if isinstance(arg, Mul):
r = [refine(abs(a), assumptions) for a in arg.args]
non_abs = []
in_abs = []
for i in r:
if isinstance(i, Abs):
in_abs.append(i.args[0])
else:
non_abs.append(i)
return Mul(*non_abs) * Abs(Mul(*in_abs))
def refine_Pow(expr, assumptions):
"""
Handler for instances of Pow.
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.refine import refine_Pow
>>> from sympy.abc import x,y,z
>>> refine_Pow((-1)**x, Q.real(x))
>>> refine_Pow((-1)**x, Q.even(x))
1
>>> refine_Pow((-1)**x, Q.odd(x))
-1
For powers of -1, even parts of the exponent can be simplified:
>>> refine_Pow((-1)**(x+y), Q.even(x))
(-1)**y
>>> refine_Pow((-1)**(x+y+z), Q.odd(x) & Q.odd(z))
(-1)**y
>>> refine_Pow((-1)**(x+y+2), Q.odd(x))
(-1)**(y + 1)
>>> refine_Pow((-1)**(x+3), True)
(-1)**(x + 1)
"""
from sympy.core import Pow, Rational
from sympy.functions.elementary.complexes import Abs
from sympy.functions import sign
if isinstance(expr.base, Abs):
if ask(Q.real(expr.base.args[0]), assumptions) and \
ask(Q.even(expr.exp), assumptions):
return expr.base.args[0] ** expr.exp
if ask(Q.real(expr.base), assumptions):
if expr.base.is_number:
if ask(Q.even(expr.exp), assumptions):
return abs(expr.base) ** expr.exp
if ask(Q.odd(expr.exp), assumptions):
return sign(expr.base) * abs(expr.base) ** expr.exp
if isinstance(expr.exp, Rational):
if type(expr.base) is Pow:
return abs(expr.base.base) ** (expr.base.exp * expr.exp)
if expr.base is S.NegativeOne:
if expr.exp.is_Add:
old = expr
# For powers of (-1) we can remove
# - even terms
# - pairs of odd terms
# - a single odd term + 1
# - A numerical constant N can be replaced with mod(N,2)
coeff, terms = expr.exp.as_coeff_add()
terms = set(terms)
even_terms = set()
odd_terms = set()
initial_number_of_terms = len(terms)
for t in terms:
if ask(Q.even(t), assumptions):
even_terms.add(t)
elif ask(Q.odd(t), assumptions):
odd_terms.add(t)
terms -= even_terms
if len(odd_terms) % 2:
terms -= odd_terms
new_coeff = (coeff + S.One) % 2
else:
terms -= odd_terms
new_coeff = coeff % 2
if new_coeff != coeff or len(terms) < initial_number_of_terms:
terms.add(new_coeff)
expr = expr.base**(Add(*terms))
# Handle (-1)**((-1)**n/2 + m/2)
e2 = 2*expr.exp
if ask(Q.even(e2), assumptions):
if e2.could_extract_minus_sign():
e2 *= expr.base
if e2.is_Add:
i, p = e2.as_two_terms()
if p.is_Pow and p.base is S.NegativeOne:
if ask(Q.integer(p.exp), assumptions):
i = (i + 1)/2
if ask(Q.even(i), assumptions):
return expr.base**p.exp
elif ask(Q.odd(i), assumptions):
return expr.base**(p.exp + 1)
else:
return expr.base**(p.exp + i)
if old != expr:
return expr
def refine_atan2(expr, assumptions):
"""
Handler for the atan2 function.
Examples
========
>>> from sympy import Q, atan2
>>> from sympy.assumptions.refine import refine_atan2
>>> from sympy.abc import x, y
>>> refine_atan2(atan2(y,x), Q.real(y) & Q.positive(x))
atan(y/x)
>>> refine_atan2(atan2(y,x), Q.negative(y) & Q.negative(x))
atan(y/x) - pi
>>> refine_atan2(atan2(y,x), Q.positive(y) & Q.negative(x))
atan(y/x) + pi
>>> refine_atan2(atan2(y,x), Q.zero(y) & Q.negative(x))
pi
>>> refine_atan2(atan2(y,x), Q.positive(y) & Q.zero(x))
pi/2
>>> refine_atan2(atan2(y,x), Q.negative(y) & Q.zero(x))
-pi/2
>>> refine_atan2(atan2(y,x), Q.zero(y) & Q.zero(x))
nan
"""
from sympy.functions.elementary.trigonometric import atan
from sympy.core import S
y, x = expr.args
if ask(Q.real(y) & Q.positive(x), assumptions):
return atan(y / x)
elif ask(Q.negative(y) & Q.negative(x), assumptions):
return atan(y / x) - S.Pi
elif ask(Q.positive(y) & Q.negative(x), assumptions):
return atan(y / x) + S.Pi
elif ask(Q.zero(y) & Q.negative(x), assumptions):
return S.Pi
elif ask(Q.positive(y) & Q.zero(x), assumptions):
return S.Pi/2
elif ask(Q.negative(y) & Q.zero(x), assumptions):
return -S.Pi/2
elif ask(Q.zero(y) & Q.zero(x), assumptions):
return S.NaN
else:
return expr
def refine_re(expr, assumptions):
"""
Handler for real part.
Examples
========
>>> from sympy.assumptions.refine import refine_re
>>> from sympy import Q, re
>>> from sympy.abc import x
>>> refine_re(re(x), Q.real(x))
x
>>> refine_re(re(x), Q.imaginary(x))
0
"""
arg = expr.args[0]
if ask(Q.real(arg), assumptions):
return arg
if ask(Q.imaginary(arg), assumptions):
return S.Zero
return _refine_reim(expr, assumptions)
def refine_im(expr, assumptions):
"""
Handler for imaginary part.
Explanation
===========
>>> from sympy.assumptions.refine import refine_im
>>> from sympy import Q, im
>>> from sympy.abc import x
>>> refine_im(im(x), Q.real(x))
0
>>> refine_im(im(x), Q.imaginary(x))
-I*x
"""
arg = expr.args[0]
if ask(Q.real(arg), assumptions):
return S.Zero
if ask(Q.imaginary(arg), assumptions):
return - S.ImaginaryUnit * arg
return _refine_reim(expr, assumptions)
def _refine_reim(expr, assumptions):
# Helper function for refine_re & refine_im
expanded = expr.expand(complex = True)
if expanded != expr:
refined = refine(expanded, assumptions)
if refined != expanded:
return refined
# Best to leave the expression as is
return None
def refine_sign(expr, assumptions):
"""
Handler for sign.
Examples
========
>>> from sympy.assumptions.refine import refine_sign
>>> from sympy import Symbol, Q, sign, im
>>> x = Symbol('x', real = True)
>>> expr = sign(x)
>>> refine_sign(expr, Q.positive(x) & Q.nonzero(x))
1
>>> refine_sign(expr, Q.negative(x) & Q.nonzero(x))
-1
>>> refine_sign(expr, Q.zero(x))
0
>>> y = Symbol('y', imaginary = True)
>>> expr = sign(y)
>>> refine_sign(expr, Q.positive(im(y)))
I
>>> refine_sign(expr, Q.negative(im(y)))
-I
"""
arg = expr.args[0]
if ask(Q.zero(arg), assumptions):
return S.Zero
if ask(Q.real(arg)):
if ask(Q.positive(arg), assumptions):
return S.One
if ask(Q.negative(arg), assumptions):
return S.NegativeOne
if ask(Q.imaginary(arg)):
arg_re, arg_im = arg.as_real_imag()
if ask(Q.positive(arg_im), assumptions):
return S.ImaginaryUnit
if ask(Q.negative(arg_im), assumptions):
return -S.ImaginaryUnit
return expr
def refine_matrixelement(expr, assumptions):
"""
Handler for symmetric part.
Examples
========
>>> from sympy.assumptions.refine import refine_matrixelement
>>> from sympy import Q
>>> from sympy.matrices.expressions.matexpr import MatrixSymbol
>>> X = MatrixSymbol('X', 3, 3)
>>> refine_matrixelement(X[0, 1], Q.symmetric(X))
X[0, 1]
>>> refine_matrixelement(X[1, 0], Q.symmetric(X))
X[0, 1]
"""
from sympy.matrices.expressions.matexpr import MatrixElement
matrix, i, j = expr.args
if ask(Q.symmetric(matrix), assumptions):
if (i - j).could_extract_minus_sign():
return expr
return MatrixElement(matrix, j, i)
handlers_dict = {
'Abs': refine_abs,
'Pow': refine_Pow,
'atan2': refine_atan2,
're': refine_re,
'im': refine_im,
'sign': refine_sign,
'MatrixElement': refine_matrixelement
} # type: Dict[str, Callable[[Expr, Boolean], Expr]]
|
fa8cb3cc55bcd556b992cc93870f83b708185056b05ee26bd6277c6f47619267 | """Module for querying SymPy objects about assumptions."""
from sympy.assumptions.assume import (global_assumptions, Predicate,
AppliedPredicate)
from sympy.core import sympify
from sympy.core.cache import cacheit
from sympy.core.relational import Relational
from sympy.core.kind import BooleanKind
from sympy.logic.boolalg import (to_cnf, And, Not, Or, Implies, Equivalent)
from sympy.logic.inference import satisfiable
from sympy.utilities.decorator import memoize_property
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.assumptions.cnf import CNF, EncodedCNF, Literal
# Memoization is necessary for the properties of AssumptionKeys to
# ensure that only one object of Predicate objects are created.
# This is because assumption handlers are registered on those objects.
class AssumptionKeys:
"""
This class contains all the supported keys by ``ask``.
It should be accessed via the instance ``sympy.Q``.
"""
# DO NOT add methods or properties other than predicate keys.
# SAT solver checks the properties of Q and use them to compute the
# fact system. Non-predicate attributes will break this.
@memoize_property
def hermitian(self):
from .handlers.sets import HermitianPredicate
return HermitianPredicate()
@memoize_property
def antihermitian(self):
from .handlers.sets import AntihermitianPredicate
return AntihermitianPredicate()
@memoize_property
def real(self):
from .handlers.sets import RealPredicate
return RealPredicate()
@memoize_property
def extended_real(self):
from .handlers.sets import ExtendedRealPredicate
return ExtendedRealPredicate()
@memoize_property
def imaginary(self):
from .handlers.sets import ImaginaryPredicate
return ImaginaryPredicate()
@memoize_property
def complex(self):
from .handlers.sets import ComplexPredicate
return ComplexPredicate()
@memoize_property
def algebraic(self):
from .handlers.sets import AlgebraicPredicate
return AlgebraicPredicate()
@memoize_property
def transcendental(self):
from .predicates.sets import TranscendentalPredicate
return TranscendentalPredicate()
@memoize_property
def integer(self):
from .handlers.sets import IntegerPredicate
return IntegerPredicate()
@memoize_property
def rational(self):
from .handlers.sets import RationalPredicate
return RationalPredicate()
@memoize_property
def irrational(self):
from .handlers.sets import IrrationalPredicate
return IrrationalPredicate()
@memoize_property
def finite(self):
from .handlers.calculus import FinitePredicate
return FinitePredicate()
@memoize_property
def infinite(self):
from .predicates.calculus import InfinitePredicate
return InfinitePredicate()
@memoize_property
def positive(self):
from .handlers.order import PositivePredicate
return PositivePredicate()
@memoize_property
def negative(self):
from .handlers.order import NegativePredicate
return NegativePredicate()
@memoize_property
def zero(self):
from .handlers.order import ZeroPredicate
return ZeroPredicate()
@memoize_property
def nonzero(self):
from .handlers.order import NonZeroPredicate
return NonZeroPredicate()
@memoize_property
def nonpositive(self):
from .handlers.order import NonPositivePredicate
return NonPositivePredicate()
@memoize_property
def nonnegative(self):
from .handlers.order import NonNegativePredicate
return NonNegativePredicate()
@memoize_property
def even(self):
from .handlers.ntheory import EvenPredicate
return EvenPredicate()
@memoize_property
def odd(self):
from .handlers.ntheory import OddPredicate
return OddPredicate()
@memoize_property
def prime(self):
from .handlers.ntheory import PrimePredicate
return PrimePredicate()
@memoize_property
def composite(self):
from .handlers.ntheory import CompositePredicate
return CompositePredicate()
@memoize_property
def commutative(self):
from .handlers.common import CommutativePredicate
return CommutativePredicate()
@memoize_property
def is_true(self):
from .handlers.common import IsTruePredicate
return IsTruePredicate()
@memoize_property
def symmetric(self):
from .handlers.matrices import SymmetricPredicate
return SymmetricPredicate()
@memoize_property
def invertible(self):
from .handlers.matrices import InvertiblePredicate
return InvertiblePredicate()
@memoize_property
def orthogonal(self):
from .handlers.matrices import OrthogonalPredicate
return OrthogonalPredicate()
@memoize_property
def unitary(self):
from .handlers.matrices import UnitaryPredicate
return UnitaryPredicate()
@memoize_property
def positive_definite(self):
from .handlers.matrices import PositiveDefinitePredicate
return PositiveDefinitePredicate()
@memoize_property
def upper_triangular(self):
from .handlers.matrices import UpperTriangularPredicate
return UpperTriangularPredicate()
@memoize_property
def lower_triangular(self):
from .handlers.matrices import LowerTriangularPredicate
return LowerTriangularPredicate()
@memoize_property
def diagonal(self):
from .handlers.matrices import DiagonalPredicate
return DiagonalPredicate()
@memoize_property
def fullrank(self):
from .handlers.matrices import FullRankPredicate
return FullRankPredicate()
@memoize_property
def square(self):
from .handlers.matrices import SquarePredicate
return SquarePredicate()
@memoize_property
def integer_elements(self):
from .handlers.matrices import IntegerElementsPredicate
return IntegerElementsPredicate()
@memoize_property
def real_elements(self):
from .handlers.matrices import RealElementsPredicate
return RealElementsPredicate()
@memoize_property
def complex_elements(self):
from .handlers.matrices import ComplexElementsPredicate
return ComplexElementsPredicate()
@memoize_property
def singular(self):
from .predicates.matrices import SingularPredicate
return SingularPredicate()
@memoize_property
def normal(self):
from .predicates.matrices import NormalPredicate
return NormalPredicate()
@memoize_property
def triangular(self):
from .predicates.matrices import TriangularPredicate
return TriangularPredicate()
@memoize_property
def unit_triangular(self):
from .predicates.matrices import UnitTriangularPredicate
return UnitTriangularPredicate()
Q = AssumptionKeys()
def _extract_facts(expr, symbol, check_reversed_rel=True):
"""
Helper for ask().
Explanation
===========
Extracts the facts relevant to the symbol from an assumption.
Returns None if there is nothing to extract.
"""
if isinstance(symbol, Relational):
if check_reversed_rel:
rev = _extract_facts(expr, symbol.reversed, False)
if rev is not None:
return rev
if isinstance(expr, bool):
return
if not expr.has(symbol):
return
if isinstance(expr, AppliedPredicate):
if expr.arg == symbol:
return expr.func
else:
return
if isinstance(expr, Not) and expr.args[0].func in (And, Or):
cls = Or if expr.args[0] == And else And
expr = cls(*[~arg for arg in expr.args[0].args])
args = [_extract_facts(arg, symbol) for arg in expr.args]
if isinstance(expr, And):
args = [x for x in args if x is not None]
if args:
return expr.func(*args)
if args and all(x is not None for x in args):
return expr.func(*args)
def _extract_all_facts(expr, symbols):
facts = set()
if len(symbols) == 1 and isinstance(symbols[0], Relational):
rel = symbols[0]
symbols = (rel, rel.reversed)
for clause in expr.clauses:
args = []
for literal in clause:
if isinstance(literal.lit, AppliedPredicate):
if literal.lit.arg in symbols:
# Add literal if it has 'symbol' in it
args.append(Literal(literal.lit.func, literal.is_Not))
else:
# If any of the literals doesn't have 'symbol' don't add the whole clause.
break
else:
if args:
facts.add(frozenset(args))
return CNF(facts)
def ask(proposition, assumptions=True, context=global_assumptions):
"""
Function to evaluate the proposition with assumptions.
**Syntax**
* ask(proposition)
Evaluate the *proposition* in global assumption context.
* ask(proposition, assumptions)
Evaluate the *proposition* with respect to *assumptions* in
global assumption context.
This function evaluates the proposition to ``True`` or ``False`` if
the truth value can be determined. If not, it returns ``None``.
It should be discerned from :func:`~.refine()` which does not reduce
the expression to ``None``.
Parameters
==========
proposition : any boolean expression
Proposition which will be evaluated to boolean value. If this is
not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``.
assumptions : any boolean expression, optional
Local assumptions to evaluate the *proposition*.
context : AssumptionsContext, optional
Default assumptions to evaluate the *proposition*. By default,
this is ``sympy.assumptions.global_assumptions`` variable.
Examples
========
>>> from sympy import ask, Q, pi
>>> from sympy.abc import x, y
>>> ask(Q.rational(pi))
False
>>> ask(Q.even(x*y), Q.even(x) & Q.integer(y))
True
>>> ask(Q.prime(4*x), Q.integer(x))
False
If the truth value cannot be determined, ``None`` will be returned.
>>> print(ask(Q.odd(3*x))) # cannot determine unless we know x
None
**Remarks**
Relations in assumptions are not implemented (yet), so the following
will not give a meaningful result.
>>> ask(Q.positive(x), Q.is_true(x > 0))
It is however a work in progress.
See Also
========
sympy.assumptions.refine.refine : Simplification using assumptions.
Proposition is not reduced to ``None`` if the truth value cannot
be determined.
"""
from sympy.assumptions.satask import satask
proposition = sympify(proposition)
assumptions = sympify(assumptions)
if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind:
raise TypeError("proposition must be a valid logical expression")
if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind:
raise TypeError("assumptions must be a valid logical expression")
if isinstance(proposition, AppliedPredicate):
key, args = proposition.function, proposition.arguments
else:
key, args = Q.is_true, (proposition,)
assump = CNF.from_prop(assumptions)
assump.extend(context)
local_facts = _extract_all_facts(assump, args)
known_facts_cnf = get_all_known_facts()
known_facts_dict = get_known_facts_dict()
enc_cnf = EncodedCNF()
enc_cnf.from_cnf(CNF(known_facts_cnf))
enc_cnf.add_from_cnf(local_facts)
if local_facts.clauses and satisfiable(enc_cnf) is False:
raise ValueError("inconsistent assumptions %s" % assumptions)
if local_facts.clauses:
if len(local_facts.clauses) == 1:
cl, = local_facts.clauses
f, = cl if len(cl)==1 else [None]
if f and f.is_Not and f.arg in known_facts_dict.get(key, []):
return False
for clause in local_facts.clauses:
if len(clause) == 1:
f, = clause
fdict = known_facts_dict.get(f.arg, None) if not f.is_Not else None
if fdict and key in fdict:
return True
if fdict and Not(key) in known_facts_dict[f.arg]:
return False
# direct resolution method, no logic
res = key(*args)._eval_ask(assumptions)
if res is not None:
return bool(res)
# using satask (still costly)
res = satask(proposition, assumptions=assumptions, context=context)
return res
def ask_full_inference(proposition, assumptions, known_facts_cnf):
"""
Method for inferring properties about objects.
"""
if not satisfiable(And(known_facts_cnf, assumptions, proposition)):
return False
if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))):
return True
return None
def register_handler(key, handler):
"""
Register a handler in the ask system. key must be a string and handler a
class inheriting from AskHandler.
.. deprecated:: 1.8.
Use multipledispatch handler instead. See :obj:`~.Predicate`.
"""
SymPyDeprecationWarning(
feature="register_handler() function",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
if isinstance(key, Predicate):
key = key.name.name
Qkey = getattr(Q, key, None)
if Qkey is not None:
Qkey.add_handler(handler)
else:
setattr(Q, key, Predicate(key, handlers=[handler]))
def remove_handler(key, handler):
"""
Removes a handler from the ask system. Same syntax as register_handler
.. deprecated:: 1.8.
Use multipledispatch handler instead. See :obj:`~.Predicate`.
"""
SymPyDeprecationWarning(
feature="remove_handler() function",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
if isinstance(key, Predicate):
key = key.name.name
getattr(Q, key).remove_handler(handler)
def single_fact_lookup(known_facts_keys, known_facts_cnf):
# Compute the quick lookup for single facts
mapping = {}
for key in known_facts_keys:
mapping[key] = {key}
for other_key in known_facts_keys:
if other_key != key:
if ask_full_inference(other_key, key, known_facts_cnf):
mapping[key].add(other_key)
return mapping
def compute_known_facts(known_facts, known_facts_keys):
"""Compute the various forms of knowledge compilation used by the
assumptions system.
Explanation
===========
This function is typically applied to the results of the ``get_known_facts``
and ``get_known_facts_keys`` functions defined at the bottom of
this file.
"""
from textwrap import dedent, wrap
fact_string = dedent('''\
"""
The contents of this file are the return value of
``sympy.assumptions.ask.compute_known_facts``.
Do NOT manually edit this file.
Instead, run ./bin/ask_update.py.
"""
from sympy.core.cache import cacheit
from sympy.logic.boolalg import And
from sympy.assumptions.cnf import Literal
from sympy.assumptions.ask import Q
# -{ Known facts as a set }-
@cacheit
def get_all_known_facts():
return {
%s
}
# -{ Known facts in Conjunctive Normal Form }-
@cacheit
def get_known_facts_cnf():
return And(
%s
)
# -{ Known facts in compressed sets }-
@cacheit
def get_known_facts_dict():
return {
%s
}
''')
# Compute the known facts in CNF form for logical inference
LINE = ",\n "
HANG = ' '*8
cnf = to_cnf(known_facts)
cnf_ = CNF.to_CNF(known_facts)
c = LINE.join([str(a) for a in cnf.args])
p = LINE.join(sorted(['frozenset((' + ', '.join(str(lit) for lit in sorted(clause, key=str)) +'))' for clause in cnf_.clauses]))
mapping = single_fact_lookup(known_facts_keys, cnf)
items = sorted(mapping.items(), key=str)
keys = [str(i[0]) for i in items]
values = ['set(%s)' % sorted(i[1], key=str) for i in items]
m = LINE.join(['\n'.join(
wrap("{}: {}".format(k, v),
subsequent_indent=HANG,
break_long_words=False))
for k, v in zip(keys, values)]) + ','
return fact_string % (p, c, m)
@cacheit
def get_known_facts_keys():
return [
getattr(Q, attr)
for attr in Q.__class__.__dict__
if not attr.startswith('__')]
@cacheit
def get_known_facts():
return And(
Implies(Q.infinite, ~Q.finite),
Implies(Q.real, Q.complex),
Implies(Q.real, Q.hermitian),
Equivalent(Q.extended_real, Q.real | Q.infinite),
Equivalent(Q.even | Q.odd, Q.integer),
Implies(Q.even, ~Q.odd),
Implies(Q.prime, Q.integer & Q.positive & ~Q.composite),
Implies(Q.integer, Q.rational),
Implies(Q.rational, Q.algebraic),
Implies(Q.algebraic, Q.complex),
Implies(Q.algebraic, Q.finite),
Equivalent(Q.transcendental | Q.algebraic, Q.complex & Q.finite),
Implies(Q.transcendental, ~Q.algebraic),
Implies(Q.transcendental, Q.finite),
Implies(Q.imaginary, Q.complex & ~Q.real),
Implies(Q.imaginary, Q.antihermitian),
Implies(Q.antihermitian, ~Q.hermitian),
Equivalent(Q.irrational | Q.rational, Q.real & Q.finite),
Implies(Q.irrational, ~Q.rational),
Implies(Q.zero, Q.even),
Equivalent(Q.real, Q.negative | Q.zero | Q.positive),
Implies(Q.zero, ~Q.negative & ~Q.positive),
Implies(Q.negative, ~Q.positive),
Equivalent(Q.nonnegative, Q.zero | Q.positive),
Equivalent(Q.nonpositive, Q.zero | Q.negative),
Equivalent(Q.nonzero, Q.negative | Q.positive),
Implies(Q.orthogonal, Q.positive_definite),
Implies(Q.orthogonal, Q.unitary),
Implies(Q.unitary & Q.real, Q.orthogonal),
Implies(Q.unitary, Q.normal),
Implies(Q.unitary, Q.invertible),
Implies(Q.normal, Q.square),
Implies(Q.diagonal, Q.normal),
Implies(Q.positive_definite, Q.invertible),
Implies(Q.diagonal, Q.upper_triangular),
Implies(Q.diagonal, Q.lower_triangular),
Implies(Q.lower_triangular, Q.triangular),
Implies(Q.upper_triangular, Q.triangular),
Implies(Q.triangular, Q.upper_triangular | Q.lower_triangular),
Implies(Q.upper_triangular & Q.lower_triangular, Q.diagonal),
Implies(Q.diagonal, Q.symmetric),
Implies(Q.unit_triangular, Q.triangular),
Implies(Q.invertible, Q.fullrank),
Implies(Q.invertible, Q.square),
Implies(Q.symmetric, Q.square),
Implies(Q.fullrank & Q.square, Q.invertible),
Equivalent(Q.invertible, ~Q.singular),
Implies(Q.integer_elements, Q.real_elements),
Implies(Q.real_elements, Q.complex_elements),
)
from sympy.assumptions.ask_generated import (
get_known_facts_dict, get_all_known_facts)
|
aee01dbc603d1e9f02a0bc30d72ebe6ffd8276db626892c71c1cfaba86094a75 | """A module which implements predicates and assumption context."""
from contextlib import contextmanager
import inspect
from sympy.core.assumptions import ManagedProperties
from sympy.core.symbol import Str
from sympy.core.sympify import _sympify
from sympy.logic.boolalg import Boolean
from sympy.multipledispatch.dispatcher import (
Dispatcher, MDNotImplementedError, str_signature
)
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import is_sequence
from sympy.utilities.source import get_class
class AssumptionsContext(set):
"""
Set containing default assumptions which are applied to the ``ask()``
function.
Explanation
===========
This is used to represent global assumptions, but you can also use this
class to create your own local assumptions contexts. It is basically a thin
wrapper to Python's set, so see its documentation for advanced usage.
Examples
========
The default assumption context is ``global_assumptions``, which is initially empty:
>>> from sympy import ask, Q
>>> from sympy.assumptions import global_assumptions
>>> global_assumptions
AssumptionsContext()
You can add default assumptions:
>>> from sympy.abc import x
>>> global_assumptions.add(Q.real(x))
>>> global_assumptions
AssumptionsContext({Q.real(x)})
>>> ask(Q.real(x))
True
And remove them:
>>> global_assumptions.remove(Q.real(x))
>>> print(ask(Q.real(x)))
None
The ``clear()`` method removes every assumption:
>>> global_assumptions.add(Q.positive(x))
>>> global_assumptions
AssumptionsContext({Q.positive(x)})
>>> global_assumptions.clear()
>>> global_assumptions
AssumptionsContext()
See Also
========
assuming
"""
def add(self, *assumptions):
"""Add an assumption."""
for a in assumptions:
super().add(a)
def _sympystr(self, printer):
if not self:
return "%s()" % self.__class__.__name__
return "{}({})".format(self.__class__.__name__, printer._print_set(self))
global_assumptions = AssumptionsContext()
class AppliedPredicate(Boolean):
"""
The class of expressions resulting from applying ``Predicate`` to
the arguments. ``AppliedPredicate`` merely wraps its argument and
remain unevaluated. To evaluate it, use the ``ask()`` function.
Examples
========
>>> from sympy import Q, ask
>>> Q.integer(1)
Q.integer(1)
The ``function`` attribute returns the predicate, and the ``arguments``
attribute returns the tuple of arguments.
>>> type(Q.integer(1))
<class 'sympy.assumptions.assume.AppliedPredicate'>
>>> Q.integer(1).function
Q.integer
>>> Q.integer(1).arguments
(1,)
Applied predicates can be evaluated to a boolean value with ``ask``:
>>> ask(Q.integer(1))
True
"""
__slots__ = ()
is_Atom = True # do not attempt to decompose this
def __new__(cls, predicate, *args):
if not isinstance(predicate, Predicate):
raise TypeError("%s is not a Predicate." % predicate)
args = map(_sympify, args)
return super().__new__(cls, predicate, *args)
@property
def arg(self):
"""
Return the expression used by this assumption.
Examples
========
>>> from sympy import Q, Symbol
>>> x = Symbol('x')
>>> a = Q.integer(x + 1)
>>> a.arg
x + 1
"""
# Will be deprecated
args = self._args
if len(args) == 2:
# backwards compatibility
return args[1]
raise TypeError("'arg' property is allowed only for unary predicates.")
@property
def args(self):
# Will be deprecated and return normal Basic.func
return self._args[1:]
@property
def func(self):
# Will be deprecated and return normal Basic.func
return self._args[0]
@property
def function(self):
"""
Return the predicate.
"""
# Will be changed to self.args[0] after args overridding is removed
return self._args[0]
@property
def arguments(self):
"""
Return the arguments which are applied to the predicate.
"""
# Will be changed to self.args[1:] after args overridding is removed
return self._args[1:]
def _eval_ask(self, assumptions):
return self.function.eval(self.arguments, assumptions)
@property
def binary_symbols(self):
from sympy.core.relational import Eq, Ne
from .ask import Q
if self.function == Q.is_true:
i = self.arguments[0]
if i.is_Boolean or i.is_Symbol or isinstance(i, (Eq, Ne)):
return i.binary_symbols
return set()
class PredicateMeta(ManagedProperties):
def __new__(cls, clsname, bases, dct):
# If handler is not defined, assign empty dispatcher.
if "handler" not in dct:
name = f"Ask{clsname.capitalize()}Handler"
handler = Dispatcher(name, doc="Handler for key %s" % name)
dct["handler"] = handler
dct["_orig_doc"] = dct.get("__doc__", "")
return super().__new__(cls, clsname, bases, dct)
@property
def __doc__(cls):
handler = cls.handler
doc = cls._orig_doc
if cls is not Predicate and handler is not None:
doc += "Handler\n"
doc += " =======\n\n"
# Append the handler's doc without breaking sphinx documentation.
docs = [" Multiply dispatched method: %s" % handler.name]
if handler.doc:
for line in handler.doc.splitlines():
if not line:
continue
docs.append(" %s" % line)
other = []
for sig in handler.ordering[::-1]:
func = handler.funcs[sig]
if func.__doc__:
s = ' Inputs: <%s>' % str_signature(sig)
lines = []
for line in func.__doc__.splitlines():
lines.append(" %s" % line)
s += "\n".join(lines)
docs.append(s)
else:
other.append(str_signature(sig))
if other:
othersig = " Other signatures:"
for line in other:
othersig += "\n * %s" % line
docs.append(othersig)
doc += '\n\n'.join(docs)
return doc
class Predicate(Boolean, metaclass=PredicateMeta):
"""
Base class for mathematical predicates. It also serves as a
constructor for undefined predicate objects.
Explanation
===========
Predicate is a function that returns a boolean value [1].
Predicate function is object, and it is instance of predicate class.
When a predicate is applied to arguments, ``AppliedPredicate``
instance is returned. This merely wraps the argument and remain
unevaluated. To obtain the truth value of applied predicate, use the
function ``ask``.
Evaluation of predicate is done by multiple dispatching. You can
register new handler to the predicate to support new types.
Every predicate in SymPy can be accessed via the property of ``Q``.
For example, ``Q.even`` returns the predicate which checks if the
argument is even number.
To define a predicate which can be evaluated, you must subclass this
class, make an instance of it, and register it to ``Q``. After then,
dispatch the handler by argument types.
If you directly construct predicate using this class, you will get
``UndefinedPredicate`` which cannot be dispatched. This is useful
when you are building boolean expressions which do not need to be
evaluated.
Examples
========
Applying and evaluating to boolean value:
>>> from sympy import Q, ask
>>> from sympy.abc import x
>>> ask(Q.prime(7))
True
You can define a new predicate by subclassing and dispatching. Here,
we define a predicate for sexy primes [2] as an example.
>>> from sympy import Predicate, Integer
>>> class SexyPrimePredicate(Predicate):
... name = "sexyprime"
>>> Q.sexyprime = SexyPrimePredicate()
>>> @Q.sexyprime.register(Integer, Integer)
... def _(int1, int2, assumptions):
... args = sorted([int1, int2])
... if not all(ask(Q.prime(a), assumptions) for a in args):
... return False
... return args[1] - args[0] == 6
>>> ask(Q.sexyprime(5, 11))
True
Direct constructing returns ``UndefinedPredicate``, which can be
applied but cannot be dispatched.
>>> from sympy import Predicate, Integer
>>> Q.P = Predicate("P")
>>> type(Q.P)
<class 'sympy.assumptions.assume.UndefinedPredicate'>
>>> Q.P(1)
Q.P(1)
>>> Q.P.register(Integer)(lambda expr, assump: True)
Traceback (most recent call last):
...
TypeError: <class 'sympy.assumptions.assume.UndefinedPredicate'> cannot be dispatched.
The tautological predicate ``Q.is_true`` can be used to wrap other objects:
>>> Q.is_true(x > 1)
Q.is_true(x > 1)
References
==========
.. [1] https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)
.. [2] https://en.wikipedia.org/wiki/Sexy_prime
"""
is_Atom = True
def __new__(cls, *args, **kwargs):
if cls is Predicate:
return UndefinedPredicate(*args, **kwargs)
obj = super().__new__(cls, *args)
return obj
@property
def name(self):
# May be overridden
return type(self).__name__
@classmethod
def register(cls, *types, **kwargs):
"""
Register the signature to the handler.
"""
if cls.handler is None:
raise TypeError("%s cannot be dispatched." % type(cls))
return cls.handler.register(*types, **kwargs)
@classmethod
def register_many(cls, *types, **kwargs):
"""
Register multiple signatures to same handler.
"""
def _(func):
for t in types:
if not is_sequence(t):
t = (t,) # for convenience, allow passing `type` to mean `(type,)`
cls.register(*t, **kwargs)(func)
return _
def __call__(self, *args):
return AppliedPredicate(self, *args)
def eval(self, args, assumptions=True):
"""
Evaluate ``self(*args)`` under the given assumptions.
This uses only direct resolution methods, not logical inference.
"""
types = tuple(type(a) for a in args)
result = None
for func in self.handler.dispatch_iter(*types):
try:
result = func(*args, assumptions)
except MDNotImplementedError:
continue
else:
if result is not None:
return result
return result
class UndefinedPredicate(Predicate):
"""
Predicate without handler.
Explanation
===========
This predicate is generated by using ``Predicate`` directly for
construction. It does not have a handler, and evaluating this with
arguments is done by SAT solver.
Examples
========
>>> from sympy import Predicate, Q
>>> Q.P = Predicate('P')
>>> Q.P.func
<class 'sympy.assumptions.assume.UndefinedPredicate'>
>>> Q.P.name
Str('P')
"""
handler = None
def __new__(cls, name, handlers=None):
# "handlers" parameter supports old design
if not isinstance(name, Str):
name = Str(name)
obj = super(Boolean, cls).__new__(cls, name)
obj.handlers = handlers or []
return obj
@property
def name(self):
return self.args[0]
def _hashable_content(self):
return (self.name,)
def __getnewargs__(self):
return (self.name,)
def __call__(self, expr):
return AppliedPredicate(self, expr)
def add_handler(self, handler):
SymPyDeprecationWarning(
feature="Predicate.add_handler() method",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
self.handlers.append(handler)
def remove_handler(self, handler):
SymPyDeprecationWarning(
feature="Predicate.remove_handler() method",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
self.handlers.remove(handler)
def eval(self, args, assumptions=True):
# Support for deprecated design
# When old design is removed, this will always return None
SymPyDeprecationWarning(
feature="Evaluating UndefinedPredicate",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
expr, = args
res, _res = None, None
mro = inspect.getmro(type(expr))
for handler in self.handlers:
cls = get_class(handler)
for subclass in mro:
eval_ = getattr(cls, subclass.__name__, None)
if eval_ is None:
continue
res = eval_(expr, assumptions)
# Do not stop if value returned is None
# Try to check for higher classes
if res is None:
continue
if _res is None:
_res = res
elif res is None:
# since first resolutor was conclusive, we keep that value
res = _res
else:
# only check consistency if both resolutors have concluded
if _res != res:
raise ValueError('incompatible resolutors')
break
return res
@contextmanager
def assuming(*assumptions):
"""
Context manager for assumptions.
Examples
========
>>> from sympy.assumptions import assuming, Q, ask
>>> from sympy.abc import x, y
>>> print(ask(Q.integer(x + y)))
None
>>> with assuming(Q.integer(x), Q.integer(y)):
... print(ask(Q.integer(x + y)))
True
"""
old_global_assumptions = global_assumptions.copy()
global_assumptions.update(assumptions)
try:
yield
finally:
global_assumptions.clear()
global_assumptions.update(old_global_assumptions)
|
d15ee8b643558531b072ca25f4f877d6ebb069d2d990e9d82065105295a699e3 | """A functions module, includes all the standard functions.
Combinatorial - factorial, fibonacci, harmonic, bernoulli...
Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
Special - gamma, zeta,spherical harmonics...
"""
from sympy.functions.combinatorial.factorials import (factorial, factorial2,
rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
from sympy.functions.combinatorial.numbers import (carmichael, fibonacci, lucas, tribonacci,
harmonic, bernoulli, bell, euler, catalan, genocchi, partition, motzkin)
from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
Id, real_root, cbrt)
from sympy.functions.elementary.complexes import (re, im, sign, Abs,
conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
principal_branch, transpose, adjoint, polarify, unpolarify)
from sympy.functions.elementary.trigonometric import (sin, cos, tan,
sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
from sympy.functions.elementary.exponential import (exp_polar, exp, log,
LambertW)
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
from sympy.functions.elementary.integers import floor, ceiling, frac
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
fresnels, fresnelc)
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
lerchphi, polylog, stieltjes)
from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
KroneckerDelta)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
from sympy.functions.special.hyper import hyper, meijerg, appellf1
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
hermite, chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root,
laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
from sympy.functions.special.elliptic_integrals import (elliptic_k,
elliptic_f, elliptic_e, elliptic_pi)
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
mathieusprime, mathieucprime)
ln = log
__all__ = [
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
'FallingFactorial', 'subfactorial',
'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'partition',
'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt',
're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
'periodic_argument', 'unbranched_argument', 'principal_branch',
'transpose', 'adjoint', 'polarify', 'unpolarify',
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
'asec', 'acsc', 'acot', 'atan2',
'exp_polar', 'exp', 'ln', 'log', 'LambertW',
'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
'acoth', 'asech', 'acsch',
'floor', 'ceiling', 'frac',
'Piecewise', 'piecewise_fold',
'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
'fresnelc',
'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
'trigamma', 'multigamma',
'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes',
'Eijk', 'LeviCivita', 'KroneckerDelta',
'SingularityFunction',
'DiracDelta', 'Heaviside',
'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
'airybiprime', 'marcumq',
'hyper', 'meijerg', 'appellf1',
'legendre', 'assoc_legendre', 'hermite', 'chebyshevt', 'chebyshevu',
'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
'gegenbauer', 'jacobi', 'jacobi_normalized',
'Ynm', 'Ynm_c', 'Znm',
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
'beta',
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
]
|
eb331532fbd81a8a630baa35f59032e6333ffb5add7d24e20916b601d132a02f | """
A Printer which converts an expression into its LaTeX equivalent.
"""
from typing import Any, Dict
import itertools
from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol
from sympy.core.alphabets import greeks
from sympy.core.containers import Tuple
from sympy.core.function import _coeff_isneg, AppliedUndef, Derivative
from sympy.core.operations import AssocOp
from sympy.core.sympify import SympifyError
from sympy.logic.boolalg import true
# sympy.printing imports
from sympy.printing.precedence import precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.conventions import split_super_sub, requires_partial
from sympy.printing.precedence import precedence, PRECEDENCE
import mpmath.libmp as mlib
from mpmath.libmp import prec_to_dps
from sympy.core.compatibility import default_sort_key
from sympy.utilities.iterables import has_variety
import re
# Hand-picked functions which can be used directly in both LaTeX and MathJax
# Complete list at
# https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands
# This variable only contains those functions which sympy uses.
accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
'arg',
]
tex_greek_dictionary = {
'Alpha': 'A',
'Beta': 'B',
'Gamma': r'\Gamma',
'Delta': r'\Delta',
'Epsilon': 'E',
'Zeta': 'Z',
'Eta': 'H',
'Theta': r'\Theta',
'Iota': 'I',
'Kappa': 'K',
'Lambda': r'\Lambda',
'Mu': 'M',
'Nu': 'N',
'Xi': r'\Xi',
'omicron': 'o',
'Omicron': 'O',
'Pi': r'\Pi',
'Rho': 'P',
'Sigma': r'\Sigma',
'Tau': 'T',
'Upsilon': r'\Upsilon',
'Phi': r'\Phi',
'Chi': 'X',
'Psi': r'\Psi',
'Omega': r'\Omega',
'lamda': r'\lambda',
'Lamda': r'\Lambda',
'khi': r'\chi',
'Khi': r'X',
'varepsilon': r'\varepsilon',
'varkappa': r'\varkappa',
'varphi': r'\varphi',
'varpi': r'\varpi',
'varrho': r'\varrho',
'varsigma': r'\varsigma',
'vartheta': r'\vartheta',
}
other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
'hslash', 'mho', 'wp'}
# Variable name modifiers
modifier_dict = {
# Accents
'mathring': lambda s: r'\mathring{'+s+r'}',
'ddddot': lambda s: r'\ddddot{'+s+r'}',
'dddot': lambda s: r'\dddot{'+s+r'}',
'ddot': lambda s: r'\ddot{'+s+r'}',
'dot': lambda s: r'\dot{'+s+r'}',
'check': lambda s: r'\check{'+s+r'}',
'breve': lambda s: r'\breve{'+s+r'}',
'acute': lambda s: r'\acute{'+s+r'}',
'grave': lambda s: r'\grave{'+s+r'}',
'tilde': lambda s: r'\tilde{'+s+r'}',
'hat': lambda s: r'\hat{'+s+r'}',
'bar': lambda s: r'\bar{'+s+r'}',
'vec': lambda s: r'\vec{'+s+r'}',
'prime': lambda s: "{"+s+"}'",
'prm': lambda s: "{"+s+"}'",
# Faces
'bold': lambda s: r'\boldsymbol{'+s+r'}',
'bm': lambda s: r'\boldsymbol{'+s+r'}',
'cal': lambda s: r'\mathcal{'+s+r'}',
'scr': lambda s: r'\mathscr{'+s+r'}',
'frak': lambda s: r'\mathfrak{'+s+r'}',
# Brackets
'norm': lambda s: r'\left\|{'+s+r'}\right\|',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
'mag': lambda s: r'\left|{'+s+r'}\right|',
}
greek_letters_set = frozenset(greeks)
_between_two_numbers_p = (
re.compile(r'[0-9][} ]*$'), # search
re.compile(r'[{ ]*[-+0-9]'), # match
)
def latex_escape(s):
"""
Escape a string such that latex interprets it as plaintext.
We can't use verbatim easily with mathjax, so escaping is easier.
Rules from https://tex.stackexchange.com/a/34586/41112.
"""
s = s.replace('\\', r'\textbackslash')
for c in '&%$#_{}':
s = s.replace(c, '\\' + c)
s = s.replace('~', r'\textasciitilde')
s = s.replace('^', r'\textasciicircum')
return s
class LatexPrinter(Printer):
printmethod = "_latex"
_default_settings = {
"full_prec": False,
"fold_frac_powers": False,
"fold_func_brackets": False,
"fold_short_frac": None,
"inv_trig_style": "abbreviated",
"itex": False,
"ln_notation": False,
"long_frac_ratio": None,
"mat_delim": "[",
"mat_str": None,
"mode": "plain",
"mul_symbol": None,
"order": None,
"symbol_names": {},
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"gothic_re_im": False,
"decimal_separator": "period",
"perm_cyclic": True,
"parenthesize_super": True,
"min": None,
"max": None,
} # type: Dict[str, Any]
def __init__(self, settings=None):
Printer.__init__(self, settings)
if 'mode' in self._settings:
valid_modes = ['inline', 'plain', 'equation',
'equation*']
if self._settings['mode'] not in valid_modes:
raise ValueError("'mode' must be one of 'inline', 'plain', "
"'equation' or 'equation*'")
if self._settings['fold_short_frac'] is None and \
self._settings['mode'] == 'inline':
self._settings['fold_short_frac'] = True
mul_symbol_table = {
None: r" ",
"ldot": r" \,.\, ",
"dot": r" \cdot ",
"times": r" \times "
}
try:
self._settings['mul_symbol_latex'] = \
mul_symbol_table[self._settings['mul_symbol']]
except KeyError:
self._settings['mul_symbol_latex'] = \
self._settings['mul_symbol']
try:
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table[self._settings['mul_symbol'] or 'dot']
except KeyError:
if (self._settings['mul_symbol'].strip() in
['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table['dot']
else:
self._settings['mul_symbol_latex_numbers'] = \
self._settings['mul_symbol']
self._delim_dict = {'(': ')', '[': ']'}
imaginary_unit_table = {
None: r"i",
"i": r"i",
"ri": r"\mathrm{i}",
"ti": r"\text{i}",
"j": r"j",
"rj": r"\mathrm{j}",
"tj": r"\text{j}",
}
try:
self._settings['imaginary_unit_latex'] = \
imaginary_unit_table[self._settings['imaginary_unit']]
except KeyError:
self._settings['imaginary_unit_latex'] = \
self._settings['imaginary_unit']
def _add_parens(self, s):
return r"\left({}\right)".format(s)
# TODO: merge this with the above, which requires a lot of test changes
def _add_parens_lspace(self, s):
return r"\left( {}\right)".format(s)
def parenthesize(self, item, level, is_neg=False, strict=False):
prec_val = precedence_traditional(item)
if is_neg and strict:
return self._add_parens(self._print(item))
if (prec_val < level) or ((not strict) and prec_val <= level):
return self._add_parens(self._print(item))
else:
return self._print(item)
def parenthesize_super(self, s):
"""
Protect superscripts in s
If the parenthesize_super option is set, protect with parentheses, else
wrap in braces.
"""
if "^" in s:
if self._settings['parenthesize_super']:
return self._add_parens(s)
else:
return "{{{}}}".format(s)
return s
def doprint(self, expr):
tex = Printer.doprint(self, expr)
if self._settings['mode'] == 'plain':
return tex
elif self._settings['mode'] == 'inline':
return r"$%s$" % tex
elif self._settings['itex']:
return r"$$%s$$" % tex
else:
env_str = self._settings['mode']
return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)
def _needs_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed, False otherwise. For example: a + b => True; a => False;
10 => False; -10 => True.
"""
return not ((expr.is_Integer and expr.is_nonnegative)
or (expr.is_Atom and (expr is not S.NegativeOne
and expr.is_Rational is False)))
def _needs_function_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
passed as an argument to a function, False otherwise. This is a more
liberal version of _needs_brackets, in that many expressions which need
to be wrapped in brackets when added/subtracted/raised to a power do
not need them when passed to a function. Such an example is a*b.
"""
if not self._needs_brackets(expr):
return False
else:
# Muls of the form a*b*c... can be folded
if expr.is_Mul and not self._mul_is_clean(expr):
return True
# Pows which don't need brackets can be folded
elif expr.is_Pow and not self._pow_is_clean(expr):
return True
# Add and Function always need brackets
elif expr.is_Add or expr.is_Function:
return True
else:
return False
def _needs_mul_brackets(self, expr, first=False, last=False):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of a Mul, False otherwise. This is True for Add,
but also for some container objects that would not need brackets
when appearing last in a Mul, e.g. an Integral. ``last=True``
specifies that this expr is the last to appear in a Mul.
``first=True`` specifies that this expr is the first to appear in
a Mul.
"""
from sympy import Integral, Product, Sum
if expr.is_Mul:
if not first and _coeff_isneg(expr):
return True
elif precedence_traditional(expr) < PRECEDENCE["Mul"]:
return True
elif expr.is_Relational:
return True
if expr.is_Piecewise:
return True
if any([expr.has(x) for x in (Mod,)]):
return True
if (not last and
any([expr.has(x) for x in (Integral, Product, Sum)])):
return True
return False
def _needs_add_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of an Add, False otherwise. This is False for most
things.
"""
if expr.is_Relational:
return True
if any([expr.has(x) for x in (Mod,)]):
return True
if expr.is_Add:
return True
return False
def _mul_is_clean(self, expr):
for arg in expr.args:
if arg.is_Function:
return False
return True
def _pow_is_clean(self, expr):
return not self._needs_brackets(expr.base)
def _do_exponent(self, expr, exp):
if exp is not None:
return r"\left(%s\right)^{%s}" % (expr, exp)
else:
return expr
def _print_Basic(self, expr):
ls = [self._print(o) for o in expr.args]
return self._deal_with_super_sub(expr.__class__.__name__) + \
r"\left(%s\right)" % ", ".join(ls)
def _print_bool(self, e):
return r"\text{%s}" % e
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
return r"\text{%s}" % e
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
tex = ""
for i, term in enumerate(terms):
if i == 0:
pass
elif _coeff_isneg(term):
tex += " - "
term = -term
else:
tex += " + "
term_tex = self._print(term)
if self._needs_add_brackets(term):
term_tex = r"\left(%s\right)" % term_tex
tex += term_tex
return tex
def _print_Cycle(self, expr):
from sympy.combinatorics.permutations import Permutation
if expr.size == 0:
return r"\left( \right)"
expr = Permutation(expr)
expr_perm = expr.cyclic_form
siz = expr.size
if expr.array_form[-1] == siz - 1:
expr_perm = expr_perm + [[siz - 1]]
term_tex = ''
for i in expr_perm:
term_tex += str(i).replace(',', r"\;")
term_tex = term_tex.replace('[', r"\left( ")
term_tex = term_tex.replace(']', r"\right)")
return term_tex
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(expr)
if expr.size == 0:
return r"\left( \right)"
lower = [self._print(arg) for arg in expr.array_form]
upper = [self._print(arg) for arg in range(len(lower))]
row1 = " & ".join(upper)
row2 = " & ".join(lower)
mat = r" \\ ".join((row1, row2))
return r"\begin{pmatrix} %s \end{pmatrix}" % mat
def _print_AppliedPermutation(self, expr):
perm, var = expr.args
return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var))
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
strip = False if self._settings['full_prec'] else True
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
str_real = mlib.to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_latex_numbers']
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
if self._settings['decimal_separator'] == 'comma':
mant = mant.replace('.','{,}')
return r"%s%s10^{%s}" % (mant, separator, exp)
elif str_real == "+inf":
return r"\infty"
elif str_real == "-inf":
return r"- \infty"
else:
if self._settings['decimal_separator'] == 'comma':
str_real = str_real.replace('.','{,}')
return str_real
def _print_Cross(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Curl(self, expr):
vec = expr._expr
return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Divergence(self, expr):
vec = expr._expr
return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Dot(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Gradient(self, expr):
func = expr._expr
return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Laplacian(self, expr):
func = expr._expr
return r"\triangle %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Mul(self, expr):
from sympy.core.power import Pow
from sympy.physics.units import Quantity
from sympy.simplify import fraction
separator = self._settings['mul_symbol_latex']
numbersep = self._settings['mul_symbol_latex_numbers']
def convert(expr):
if not expr.is_Mul:
return str(self._print(expr))
else:
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
args = list(expr.args)
# If quantities are present append them at the back
args = sorted(args, key=lambda x: isinstance(x, Quantity) or
(isinstance(x, Pow) and
isinstance(x.base, Quantity)))
return convert_args(args)
def convert_args(args):
_tex = last_term_tex = ""
for i, term in enumerate(args):
term_tex = self._print(term)
if self._needs_mul_brackets(term, first=(i == 0),
last=(i == len(args) - 1)):
term_tex = r"\left(%s\right)" % term_tex
if _between_two_numbers_p[0].search(last_term_tex) and \
_between_two_numbers_p[1].match(term_tex):
# between two numbers
_tex += numbersep
elif _tex:
_tex += separator
_tex += term_tex
last_term_tex = term_tex
return _tex
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
# XXX: _print_Pow calls this routine with instances of Pow...
if isinstance(expr, Mul):
args = expr.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
return convert_args(args)
include_parens = False
if _coeff_isneg(expr):
expr = -expr
tex = "- "
if expr.is_Add:
tex += "("
include_parens = True
else:
tex = ""
numer, denom = fraction(expr, exact=True)
if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args:
# use the original expression here, since fraction() may have
# altered it when producing numer and denom
tex += convert(expr)
else:
snumer = convert(numer)
sdenom = convert(denom)
ldenom = len(sdenom.split())
ratio = self._settings['long_frac_ratio']
if self._settings['fold_short_frac'] and ldenom <= 2 and \
"^" not in sdenom:
# handle short fractions
if self._needs_mul_brackets(numer, last=False):
tex += r"\left(%s\right) / %s" % (snumer, sdenom)
else:
tex += r"%s / %s" % (snumer, sdenom)
elif ratio is not None and \
len(snumer.split()) > ratio*ldenom:
# handle long fractions
if self._needs_mul_brackets(numer, last=True):
tex += r"\frac{1}{%s}%s\left(%s\right)" \
% (sdenom, separator, snumer)
elif numer.is_Mul:
# split a long numerator
a = S.One
b = S.One
for x in numer.args:
if self._needs_mul_brackets(x, last=False) or \
len(convert(a*x).split()) > ratio*ldenom or \
(b.is_commutative is x.is_commutative is False):
b *= x
else:
a *= x
if self._needs_mul_brackets(b, last=True):
tex += r"\frac{%s}{%s}%s\left(%s\right)" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{%s}{%s}%s%s" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)
else:
tex += r"\frac{%s}{%s}" % (snumer, sdenom)
if include_parens:
tex += ")"
return tex
def _print_Pow(self, expr):
# Treat x**Rational(1,n) as special case
if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1 \
and self._settings['root_notation']:
base = self._print(expr.base)
expq = expr.exp.q
if expq == 2:
tex = r"\sqrt{%s}" % base
elif self._settings['itex']:
tex = r"\root{%d}{%s}" % (expq, base)
else:
tex = r"\sqrt[%d]{%s}" % (expq, base)
if expr.exp.is_negative:
return r"\frac{1}{%s}" % tex
else:
return tex
elif self._settings['fold_frac_powers'] \
and expr.exp.is_Rational \
and expr.exp.q != 1:
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
p, q = expr.exp.p, expr.exp.q
# issue #12886: add parentheses for superscripts raised to powers
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
if expr.base.is_Function:
return self._print(expr.base, exp="%s/%s" % (p, q))
return r"%s^{%s/%s}" % (base, p, q)
elif expr.exp.is_Rational and expr.exp.is_negative and \
expr.base.is_commutative:
# special case for 1^(-x), issue 9216
if expr.base == 1:
return r"%s^{%s}" % (expr.base, expr.exp)
# things like 1/x
return self._print_Mul(expr)
else:
if expr.base.is_Function:
return self._print(expr.base, exp=self._print(expr.exp))
else:
tex = r"%s^{%s}"
return self._helper_print_standard_power(expr, tex)
def _helper_print_standard_power(self, expr, template):
exp = self._print(expr.exp)
# issue #12886: add parentheses around superscripts raised
# to powers
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
elif (isinstance(expr.base, Derivative)
and base.startswith(r'\left(')
and re.match(r'\\left\(\\d?d?dot', base)
and base.endswith(r'\right)')):
# don't use parentheses around dotted derivative
base = base[6: -7] # remove outermost added parens
return template % (base, exp)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_Sum(self, expr):
if len(expr.limits) == 1:
tex = r"\sum_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\sum_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Product(self, expr):
if len(expr.limits) == 1:
tex = r"\prod_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\prod_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
o1 = []
if expr == expr.zero:
return expr.zero._latex_form
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key=lambda x: x[0].__str__())
for k, v in inneritems:
if v == 1:
o1.append(' + ' + k._latex_form)
elif v == -1:
o1.append(' - ' + k._latex_form)
else:
arg_str = '(' + self._print(v) + ')'
o1.append(' + ' + arg_str + k._latex_form)
outstr = (''.join(o1))
if outstr[1] != '-':
outstr = outstr[3:]
else:
outstr = outstr[1:]
return outstr
def _print_Indexed(self, expr):
tex_base = self._print(expr.base)
tex = '{'+tex_base+'}'+'_{%s}' % ','.join(
map(self._print, expr.indices))
return tex
def _print_IndexedBase(self, expr):
return self._print(expr.label)
def _print_Derivative(self, expr):
if requires_partial(expr.expr):
diff_symbol = r'\partial'
else:
diff_symbol = r'd'
tex = ""
dim = 0
for x, num in reversed(expr.variable_count):
dim += num
if num == 1:
tex += r"%s %s" % (diff_symbol, self._print(x))
else:
tex += r"%s %s^{%s}" % (diff_symbol,
self.parenthesize_super(self._print(x)),
self._print(num))
if dim == 1:
tex = r"\frac{%s}{%s}" % (diff_symbol, tex)
else:
tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
if any(_coeff_isneg(i) for i in expr.args):
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=True,
strict=True))
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=False,
strict=True))
def _print_Subs(self, subs):
expr, old, new = subs.args
latex_expr = self._print(expr)
latex_old = (self._print(e) for e in old)
latex_new = (self._print(e) for e in new)
latex_subs = r'\\ '.join(
e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,
latex_subs)
def _print_Integral(self, expr):
tex, symbols = "", []
# Only up to \iiiint exists
if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
# Use len(expr.limits)-1 so that syntax highlighters don't think
# \" is an escaped quote
tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"
symbols = [r"\, d%s" % self._print(symbol[0])
for symbol in expr.limits]
else:
for lim in reversed(expr.limits):
symbol = lim[0]
tex += r"\int"
if len(lim) > 1:
if self._settings['mode'] != 'inline' \
and not self._settings['itex']:
tex += r"\limits"
if len(lim) == 3:
tex += "_{%s}^{%s}" % (self._print(lim[1]),
self._print(lim[2]))
if len(lim) == 2:
tex += "^{%s}" % (self._print(lim[1]))
symbols.insert(0, r"\, d%s" % self._print(symbol))
return r"%s %s%s" % (tex, self.parenthesize(expr.function,
PRECEDENCE["Mul"],
is_neg=any(_coeff_isneg(i) for i in expr.args),
strict=True),
"".join(symbols))
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
tex = r"\lim_{%s \to " % self._print(z)
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
tex += r"%s}" % self._print(z0)
else:
tex += r"%s^%s}" % (self._print(z0), self._print(dir))
if isinstance(e, AssocOp):
return r"%s\left(%s\right)" % (tex, self._print(e))
else:
return r"%s %s" % (tex, self._print(e))
def _hprint_Function(self, func):
r'''
Logic to decide how to render a function to latex
- if it is a recognized latex name, use the appropriate latex command
- if it is a single letter, just use that letter
- if it is a longer name, then put \operatorname{} around it and be
mindful of undercores in the name
'''
func = self._deal_with_super_sub(func)
if func in accepted_latex_functions:
name = r"\%s" % func
elif len(func) == 1 or func.startswith('\\'):
name = func
else:
name = r"\operatorname{%s}" % func
return name
def _print_Function(self, expr, exp=None):
r'''
Render functions to LaTeX, handling functions that LaTeX knows about
e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
For single-letter function names, render them as regular LaTeX math
symbols. For multi-letter function names that LaTeX does not know
about, (e.g., Li, sech) use \operatorname{} so that the function name
is rendered in Roman font and LaTeX handles spacing properly.
expr is the expression involving the function
exp is an exponent
'''
func = expr.func.__name__
if hasattr(self, '_print_' + func) and \
not isinstance(expr, AppliedUndef):
return getattr(self, '_print_' + func)(expr, exp)
else:
args = [str(self._print(arg)) for arg in expr.args]
# How inverse trig functions should be displayed, formats are:
# abbreviated: asin, full: arcsin, power: sin^-1
inv_trig_style = self._settings['inv_trig_style']
# If we are dealing with a power-style inverse trig function
inv_trig_power_case = False
# If it is applicable to fold the argument brackets
can_fold_brackets = self._settings['fold_func_brackets'] and \
len(args) == 1 and \
not self._needs_function_brackets(expr.args[0])
inv_trig_table = [
"asin", "acos", "atan",
"acsc", "asec", "acot",
"asinh", "acosh", "atanh",
"acsch", "asech", "acoth",
]
# If the function is an inverse trig function, handle the style
if func in inv_trig_table:
if inv_trig_style == "abbreviated":
pass
elif inv_trig_style == "full":
func = "arc" + func[1:]
elif inv_trig_style == "power":
func = func[1:]
inv_trig_power_case = True
# Can never fold brackets if we're raised to a power
if exp is not None:
can_fold_brackets = False
if inv_trig_power_case:
if func in accepted_latex_functions:
name = r"\%s^{-1}" % func
else:
name = r"\operatorname{%s}^{-1}" % func
elif exp is not None:
func_tex = self._hprint_Function(func)
func_tex = self.parenthesize_super(func_tex)
name = r'%s^{%s}' % (func_tex, exp)
else:
name = self._hprint_Function(func)
if can_fold_brackets:
if func in accepted_latex_functions:
# Wrap argument safely to avoid parse-time conflicts
# with the function name itself
name += r" {%s}"
else:
name += r"%s"
else:
name += r"{\left(%s \right)}"
if inv_trig_power_case and exp is not None:
name += r"^{%s}" % exp
return name % ",".join(args)
def _print_UndefinedFunction(self, expr):
return self._hprint_Function(str(expr))
def _print_ElementwiseApplyFunction(self, expr):
return r"{%s}_{\circ}\left({%s}\right)" % (
self._print(expr.function),
self._print(expr.expr),
)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: r'\delta',
gamma: r'\Gamma',
lowergamma: r'\gamma',
beta: r'\operatorname{B}',
DiracDelta: r'\delta',
Chi: r'\operatorname{Chi}'}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
return self._special_function_classes[cls]
return self._hprint_Function(str(expr))
def _print_Lambda(self, expr):
symbols, expr = expr.args
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(tuple(symbols))
tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))
return tex
def _print_IdentityFunction(self, expr):
return r"\left( x \mapsto x \right)"
def _hprint_variadic_function(self, expr, exp=None):
args = sorted(expr.args, key=default_sort_key)
texargs = [r"%s" % self._print(symbol) for symbol in args]
tex = r"\%s\left(%s\right)" % (str(expr.func).lower(),
", ".join(texargs))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Min = _print_Max = _hprint_variadic_function
def _print_floor(self, expr, exp=None):
tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_ceiling(self, expr, exp=None):
tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_log(self, expr, exp=None):
if not self._settings["ln_notation"]:
tex = r"\log{\left(%s \right)}" % self._print(expr.args[0])
else:
tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_Abs(self, expr, exp=None):
tex = r"\left|{%s}\right|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Determinant = _print_Abs
def _print_re(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_im(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_Not(self, e):
from sympy import Equivalent, Implies
if isinstance(e.args[0], Equivalent):
return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow")
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args[0], r"\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg \left(%s\right)" % self._print(e.args[0])
else:
return r"\neg %s" % self._print(e.args[0])
def _print_LogOp(self, args, char):
arg = args[0]
if arg.is_Boolean and not arg.is_Not:
tex = r"\left(%s\right)" % self._print(arg)
else:
tex = r"%s" % self._print(arg)
for arg in args[1:]:
if arg.is_Boolean and not arg.is_Not:
tex += r" %s \left(%s\right)" % (char, self._print(arg))
else:
tex += r" %s %s" % (char, self._print(arg))
return tex
def _print_And(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\wedge")
def _print_Or(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\vee")
def _print_Xor(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\veebar")
def _print_Implies(self, e, altchar=None):
return self._print_LogOp(e.args, altchar or r"\Rightarrow")
def _print_Equivalent(self, e, altchar=None):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, altchar or r"\Leftrightarrow")
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_polar_lift(self, expr, exp=None):
func = r"\operatorname{polar\_lift}"
arg = r"{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (func, exp, arg)
else:
return r"%s%s" % (func, arg)
def _print_ExpBase(self, expr, exp=None):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
tex = r"e^{%s}" % self._print(expr.args[0])
return self._do_exponent(tex, exp)
def _print_Exp1(self, expr, exp=None):
return "e"
def _print_elliptic_k(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"K^{%s}%s" % (exp, tex)
else:
return r"K%s" % tex
def _print_elliptic_f(self, expr, exp=None):
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"F^{%s}%s" % (exp, tex)
else:
return r"F%s" % tex
def _print_elliptic_e(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"E^{%s}%s" % (exp, tex)
else:
return r"E%s" % tex
def _print_elliptic_pi(self, expr, exp=None):
if len(expr.args) == 3:
tex = r"\left(%s; %s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]),
self._print(expr.args[2]))
else:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"\Pi^{%s}%s" % (exp, tex)
else:
return r"\Pi%s" % tex
def _print_beta(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\operatorname{B}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{B}%s" % tex
def _print_uppergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\Gamma^{%s}%s" % (exp, tex)
else:
return r"\Gamma%s" % tex
def _print_lowergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\gamma^{%s}%s" % (exp, tex)
else:
return r"\gamma%s" % tex
def _hprint_one_arg_func(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (self._print(expr.func), exp, tex)
else:
return r"%s%s" % (self._print(expr.func), tex)
_print_gamma = _hprint_one_arg_func
def _print_Chi(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\operatorname{Chi}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{Chi}%s" % tex
def _print_expint(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[1])
nu = self._print(expr.args[0])
if exp is not None:
return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)
else:
return r"\operatorname{E}_{%s}%s" % (nu, tex)
def _print_fresnels(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"S^{%s}%s" % (exp, tex)
else:
return r"S%s" % tex
def _print_fresnelc(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"C^{%s}%s" % (exp, tex)
else:
return r"C%s" % tex
def _print_subfactorial(self, expr, exp=None):
tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"\left(%s\right)^{%s}" % (tex, exp)
else:
return tex
def _print_factorial(self, expr, exp=None):
tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_factorial2(self, expr, exp=None):
tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_binomial(self, expr, exp=None):
tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_RisingFactorial(self, expr, exp=None):
n, k = expr.args
base = r"%s" % self.parenthesize(n, PRECEDENCE['Func'])
tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k))
return self._do_exponent(tex, exp)
def _print_FallingFactorial(self, expr, exp=None):
n, k = expr.args
sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func'])
tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub)
return self._do_exponent(tex, exp)
def _hprint_BesselBase(self, expr, exp, sym):
tex = r"%s" % (sym)
need_exp = False
if exp is not None:
if tex.find('^') == -1:
tex = r"%s^{%s}" % (tex, exp)
else:
need_exp = True
tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),
self._print(expr.argument))
if need_exp:
tex = self._do_exponent(tex, exp)
return tex
def _hprint_vec(self, vec):
if not vec:
return ""
s = ""
for i in vec[:-1]:
s += "%s, " % self._print(i)
s += self._print(vec[-1])
return s
def _print_besselj(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'J')
def _print_besseli(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'I')
def _print_besselk(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'K')
def _print_bessely(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'Y')
def _print_yn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'y')
def _print_jn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'j')
def _print_hankel1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
def _print_hn1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
def _print_hn2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
def _hprint_airy(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (notation, exp, tex)
else:
return r"%s%s" % (notation, tex)
def _hprint_airy_prime(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)
else:
return r"%s^\prime%s" % (notation, tex)
def _print_airyai(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Ai')
def _print_airybi(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Bi')
def _print_airyaiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Ai')
def _print_airybiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Bi')
def _print_hyper(self, expr, exp=None):
tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \
r"\middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_meijerg(self, expr, exp=None):
tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \
r"%s & %s \end{matrix} \middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._print(len(expr.bm)), self._print(len(expr.an)),
self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_dirichlet_eta(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\eta^{%s}%s" % (exp, tex)
return r"\eta%s" % tex
def _print_zeta(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\zeta^{%s}%s" % (exp, tex)
return r"\zeta%s" % tex
def _print_stieltjes(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"_{%s}" % self._print(expr.args[0])
if exp is not None:
return r"\gamma%s^{%s}" % (tex, exp)
return r"\gamma%s" % tex
def _print_lerchphi(self, expr, exp=None):
tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))
if exp is None:
return r"\Phi%s" % tex
return r"\Phi^{%s}%s" % (exp, tex)
def _print_polylog(self, expr, exp=None):
s, z = map(self._print, expr.args)
tex = r"\left(%s\right)" % z
if exp is None:
return r"\operatorname{Li}_{%s}%s" % (s, tex)
return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex)
def _print_jacobi(self, expr, exp=None):
n, a, b, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_gegenbauer(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevt(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"T_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevu(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"U_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_legendre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"P_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_legendre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_hermite(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"H_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_laguerre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"L_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_laguerre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Ynm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Znm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def __print_mathieu_functions(self, character, args, prime=False, exp=None):
a, q, z = map(self._print, args)
sup = r"^{\prime}" if prime else ""
exp = "" if not exp else "^{%s}" % exp
return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp)
def _print_mathieuc(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, exp=exp)
def _print_mathieus(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, exp=exp)
def _print_mathieucprime(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp)
def _print_mathieusprime(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp)
def _print_Rational(self, expr):
if expr.q != 1:
sign = ""
p = expr.p
if expr.p < 0:
sign = "- "
p = -p
if self._settings['fold_short_frac']:
return r"%s%d / %d" % (sign, p, expr.q)
return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
else:
return self._print(expr.p)
def _print_Order(self, expr):
s = self._print(expr.expr)
if expr.point and any(p != S.Zero for p in expr.point) or \
len(expr.variables) > 1:
s += '; '
if len(expr.variables) > 1:
s += self._print(expr.variables)
elif expr.variables:
s += self._print(expr.variables[0])
s += r'\rightarrow '
if len(expr.point) > 1:
s += self._print(expr.point)
else:
s += self._print(expr.point[0])
return r"O\left(%s\right)" % s
def _print_Symbol(self, expr, style='plain'):
if expr in self._settings['symbol_names']:
return self._settings['symbol_names'][expr]
return self._deal_with_super_sub(expr.name, style=style)
_print_RandomSymbol = _print_Symbol
def _deal_with_super_sub(self, string, style='plain'):
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
# apply the style only to the name
if style == 'bold':
name = "\\mathbf{{{}}}".format(name)
# glue all items together:
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Relational(self, expr):
if self._settings['itex']:
gt = r"\gt"
lt = r"\lt"
else:
gt = ">"
lt = "<"
charmap = {
"==": "=",
">": gt,
"<": lt,
">=": r"\geq",
"<=": r"\leq",
"!=": r"\neq",
}
return "%s %s %s" % (self._print(expr.lhs),
charmap[expr.rel_op], self._print(expr.rhs))
def _print_Piecewise(self, expr):
ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))
for e, c in expr.args[:-1]]
if expr.args[-1].cond == true:
ecpairs.append(r"%s & \text{otherwise}" %
self._print(expr.args[-1].expr))
else:
ecpairs.append(r"%s & \text{for}\: %s" %
(self._print(expr.args[-1].expr),
self._print(expr.args[-1].cond)))
tex = r"\begin{cases} %s \end{cases}"
return tex % r" \\".join(ecpairs)
def _print_MatrixBase(self, expr):
lines = []
for line in range(expr.rows): # horrible, should be 'rows'
lines.append(" & ".join([self._print(i) for i in expr[line, :]]))
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.cols <= 10) is True:
mat_str = 'matrix'
else:
mat_str = 'array'
out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
out_str = out_str.replace('%MATSTR%', mat_str)
if mat_str == 'array':
out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
out_str = r'\left' + left_delim + out_str + \
r'\right' + right_delim
return out_str % r"\\".join(lines)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\
+ '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))
def _print_MatrixSlice(self, expr):
def latexslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = None
if x[1] == dim:
x[1] = None
return ':'.join(self._print(xi) if xi is not None else '' for xi in x)
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +
latexslice(expr.rowslice, expr.parent.rows) + ', ' +
latexslice(expr.colslice, expr.parent.cols) + r'\right]')
def _print_BlockMatrix(self, expr):
return self._print(expr.blocks)
def _print_Transpose(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol):
return r"\left(%s\right)^{T}" % self._print(mat)
else:
return "%s^{T}" % self.parenthesize(mat, precedence_traditional(expr), True)
def _print_Trace(self, expr):
mat = expr.arg
return r"\operatorname{tr}\left(%s \right)" % self._print(mat)
def _print_Adjoint(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol):
return r"\left(%s\right)^{\dagger}" % self._print(mat)
else:
return r"%s^{\dagger}" % self._print(mat)
def _print_MatMul(self, expr):
from sympy import MatMul, Mul
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
args = expr.args
if isinstance(args[0], Mul):
args = args[0].as_ordered_factors() + list(args[1:])
else:
args = list(args)
if isinstance(expr, MatMul) and _coeff_isneg(expr):
if args[0] == -1:
args = args[1:]
else:
args[0] = -args[0]
return '- ' + ' '.join(map(parens, args))
else:
return ' '.join(map(parens, args))
def _print_Mod(self, expr, exp=None):
if exp is not None:
return r'\left(%s\bmod{%s}\right)^{%s}' % \
(self.parenthesize(expr.args[0], PRECEDENCE['Mul'],
strict=True), self._print(expr.args[1]),
exp)
return r'%s\bmod{%s}' % (self.parenthesize(expr.args[0],
PRECEDENCE['Mul'], strict=True),
self._print(expr.args[1]))
def _print_HadamardProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \circ '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_HadamardPower(self, expr):
if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]:
template = r"%s^{\circ \left({%s}\right)}"
else:
template = r"%s^{\circ {%s}}"
return self._helper_print_standard_power(expr, template)
def _print_KroneckerProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \otimes '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_MatPow(self, expr):
base, exp = expr.base, expr.exp
from sympy.matrices import MatrixSymbol
if not isinstance(base, MatrixSymbol):
return "\\left(%s\\right)^{%s}" % (self._print(base),
self._print(exp))
else:
return "%s^{%s}" % (self._print(base), self._print(exp))
def _print_MatrixSymbol(self, expr):
return self._print_Symbol(expr, style=self._settings[
'mat_symbol_style'])
def _print_ZeroMatrix(self, Z):
return r"\mathbb{0}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{0}"
def _print_OneMatrix(self, O):
return r"\mathbb{1}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{1}"
def _print_Identity(self, I):
return r"\mathbb{I}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{I}"
def _print_PermutationMatrix(self, P):
perm_str = self._print(P.args[0])
return "P_{%s}" % perm_str
def _print_NDimArray(self, expr):
if expr.rank() == 0:
return self._print(expr[()])
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.rank() == 0) or (expr.shape[-1] <= 10):
mat_str = 'matrix'
else:
mat_str = 'array'
block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
block_str = block_str.replace('%MATSTR%', mat_str)
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
block_str = r'\left' + left_delim + block_str + \
r'\right' + right_delim
if expr.rank() == 0:
return block_str % ""
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(self._print(expr[outer_i]))
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(
r" & ".join(level_str[back_outer_i+1]))
else:
level_str[back_outer_i].append(
block_str % (r"\\".join(level_str[back_outer_i+1])))
if len(level_str[back_outer_i+1]) == 1:
level_str[back_outer_i][-1] = r"\left[" + \
level_str[back_outer_i][-1] + r"\right]"
even = not even
level_str[back_outer_i+1] = []
out_str = level_str[0][0]
if expr.rank() % 2 == 1:
out_str = block_str % out_str
return out_str
def _printer_tensor_indices(self, name, indices, index_map={}):
out_str = self._print(name)
last_valence = None
prev_map = None
for index in indices:
new_valence = index.is_up
if ((index in index_map) or prev_map) and \
last_valence == new_valence:
out_str += ","
if last_valence != new_valence:
if last_valence is not None:
out_str += "}"
if index.is_up:
out_str += "{}^{"
else:
out_str += "{}_{"
out_str += self._print(index.args[0])
if index in index_map:
out_str += "="
out_str += self._print(index_map[index])
prev_map = True
else:
prev_map = False
last_valence = new_valence
if last_valence is not None:
out_str += "}"
return out_str
def _print_Tensor(self, expr):
name = expr.args[0].args[0]
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].args[0]
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
sign, args = expr._get_args_for_traditional_printer()
return sign + "".join(
[self.parenthesize(arg, precedence(expr)) for arg in args]
)
def _print_TensAdd(self, expr):
a = []
args = expr.args
for x in args:
a.append(self.parenthesize(x, precedence(expr)))
a.sort()
s = ' + '.join(a)
s = s.replace('+ -', '- ')
return s
def _print_TensorIndex(self, expr):
return "{}%s{%s}" % (
"^" if expr.is_up else "_",
self._print(expr.args[0])
)
def _print_PartialDerivative(self, expr):
if len(expr.variables) == 1:
return r"\frac{\partial}{\partial {%s}}{%s}" % (
self._print(expr.variables[0]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
else:
return r"\frac{\partial^{%s}}{%s}{%s}" % (
len(expr.variables),
" ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
def _print_UniversalSet(self, expr):
return r"\mathbb{U}"
def _print_frac(self, expr, exp=None):
if exp is None:
return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])
else:
return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (
self._print(expr.args[0]), exp)
def _print_tuple(self, expr):
if self._settings['decimal_separator'] == 'comma':
sep = ";"
elif self._settings['decimal_separator'] == 'period':
sep = ","
else:
raise ValueError('Unknown Decimal Separator')
if len(expr) == 1:
# 1-tuple needs a trailing separator
return self._add_parens_lspace(self._print(expr[0]) + sep)
else:
return self._add_parens_lspace(
(sep + r" \ ").join([self._print(i) for i in expr]))
def _print_TensorProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \otimes '.join(elements)
def _print_WedgeProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \wedge '.join(elements)
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_list(self, expr):
if self._settings['decimal_separator'] == 'comma':
return r"\left[ %s\right]" % \
r"; \ ".join([self._print(i) for i in expr])
elif self._settings['decimal_separator'] == 'period':
return r"\left[ %s\right]" % \
r", \ ".join([self._print(i) for i in expr])
else:
raise ValueError('Unknown Decimal Separator')
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
val = d[key]
items.append("%s : %s" % (self._print(key), self._print(val)))
return r"\left\{ %s\right\}" % r", \ ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_DiracDelta(self, expr, exp=None):
if len(expr.args) == 1 or expr.args[1] == 0:
tex = r"\delta\left(%s\right)" % self._print(expr.args[0])
else:
tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (
self._print(expr.args[1]), self._print(expr.args[0]))
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_SingularityFunction(self, expr):
shift = self._print(expr.args[0] - expr.args[1])
power = self._print(expr.args[2])
tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)
return tex
def _print_Heaviside(self, expr, exp=None):
tex = r"\theta\left(%s\right)" % self._print(expr.args[0])
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_KroneckerDelta(self, expr, exp=None):
i = self._print(expr.args[0])
j = self._print(expr.args[1])
if expr.args[0].is_Atom and expr.args[1].is_Atom:
tex = r'\delta_{%s %s}' % (i, j)
else:
tex = r'\delta_{%s, %s}' % (i, j)
if exp is not None:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
if all(x.is_Atom for x in expr.args):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return '\\text{Domain: }' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('\\text{Domain: }' + self._print(d.symbols) + '\\text{ in }' +
self._print(d.set))
elif hasattr(d, 'symbols'):
return '\\text{Domain on }' + self._print(d.symbols)
else:
return self._print(None)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_set(items)
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
if self._settings['decimal_separator'] == 'comma':
items = "; ".join(map(self._print, items))
elif self._settings['decimal_separator'] == 'period':
items = ", ".join(map(self._print, items))
else:
raise ValueError('Unknown Decimal Separator')
return r"\left\{%s\right\}" % items
_print_frozenset = _print_set
def _print_Range(self, s):
dots = object()
if s.has(Symbol):
return self._print_Basic(s)
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif len(s) > 4:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
printset = tuple(s)
return (r"\left\{" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right\}")
def __print_number_polynomial(self, expr, letter, exp=None):
if len(expr.args) == 2:
if exp is not None:
return r"%s_{%s}^{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), exp,
self._print(expr.args[1]))
return r"%s_{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), self._print(expr.args[1]))
tex = r"%s_{%s}" % (letter, self._print(expr.args[0]))
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_bernoulli(self, expr, exp=None):
return self.__print_number_polynomial(expr, "B", exp)
def _print_bell(self, expr, exp=None):
if len(expr.args) == 3:
tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for
el in expr.args[2])
if exp is not None:
tex = r"%s^{%s}%s" % (tex1, exp, tex2)
else:
tex = tex1 + tex2
return tex
return self.__print_number_polynomial(expr, "B", exp)
def _print_fibonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "F", exp)
def _print_lucas(self, expr, exp=None):
tex = r"L_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_tribonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "T", exp)
def _print_SeqFormula(self, s):
dots = object()
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
return r"\left\{%s\right\}_{%s=%s}^{%s}" % (
self._print(s.formula),
self._print(s.variables[0]),
self._print(s.start),
self._print(s.stop)
)
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
else:
printset = tuple(s)
return (r"\left[" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right]")
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_Interval(self, i):
if i.start == i.end:
return r"\left\{%s\right\}" % self._print(i.start)
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return r"\left%s%s, %s\right%s" % \
(left, self._print(i.start), self._print(i.end), right)
def _print_AccumulationBounds(self, i):
return r"\left\langle %s, %s\right\rangle" % \
(self._print(i.min), self._print(i.max))
def _print_Union(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cup ".join(args_str)
def _print_Complement(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \setminus ".join(args_str)
def _print_Intersection(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cap ".join(args_str)
def _print_SymmetricDifference(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \triangle ".join(args_str)
def _print_ProductSet(self, p):
prec = precedence_traditional(p)
if len(p.sets) >= 1 and not has_variety(p.sets):
return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets)
return r" \times ".join(
self.parenthesize(set, prec) for set in p.sets)
def _print_EmptySet(self, e):
return r"\emptyset"
def _print_Naturals(self, n):
return r"\mathbb{N}"
def _print_Naturals0(self, n):
return r"\mathbb{N}_0"
def _print_Integers(self, i):
return r"\mathbb{Z}"
def _print_Rationals(self, i):
return r"\mathbb{Q}"
def _print_Reals(self, i):
return r"\mathbb{R}"
def _print_Complexes(self, i):
return r"\mathbb{C}"
def _print_ImageSet(self, s):
expr = s.lamda.expr
sig = s.lamda.signature
xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets))
xinys = r" , ".join(r"%s \in %s" % xy for xy in xys)
return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys)
def _print_ConditionSet(self, s):
vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
if s.base_set is S.UniversalSet:
return r"\left\{%s\; \middle|\; %s \right\}" % \
(vars_print, self._print(s.condition))
return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % (
vars_print,
vars_print,
self._print(s.base_set),
self._print(s.condition))
def _print_ComplexRegion(self, s):
vars_print = ', '.join([self._print(var) for var in s.variables])
return r"\left\{%s\; \middle|\; %s \in %s \right\}" % (
self._print(s.expr),
vars_print,
self._print(s.sets))
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
def _print_FourierSeries(self, s):
return self._print_Add(s.truncate()) + r' + \ldots'
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_FiniteField(self, expr):
return r"\mathbb{F}_{%s}" % expr.mod
def _print_IntegerRing(self, expr):
return r"\mathbb{Z}"
def _print_RationalField(self, expr):
return r"\mathbb{Q}"
def _print_RealField(self, expr):
return r"\mathbb{R}"
def _print_ComplexField(self, expr):
return r"\mathbb{C}"
def _print_PolynomialRing(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left[%s\right]" % (domain, symbols)
def _print_FractionField(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left(%s\right)" % (domain, symbols)
def _print_PolynomialRingBase(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
inv = ""
if not expr.is_Poly:
inv = r"S_<^{-1}"
return r"%s%s\left[%s\right]" % (inv, domain, symbols)
def _print_Poly(self, poly):
cls = poly.__class__.__name__
terms = []
for monom, coeff in poly.terms():
s_monom = ''
for i, exp in enumerate(monom):
if exp > 0:
if exp == 1:
s_monom += self._print(poly.gens[i])
else:
s_monom += self._print(pow(poly.gens[i], exp))
if coeff.is_Add:
if s_monom:
s_coeff = r"\left(%s\right)" % self._print(coeff)
else:
s_coeff = self._print(coeff)
else:
if s_monom:
if coeff is S.One:
terms.extend(['+', s_monom])
continue
if coeff is S.NegativeOne:
terms.extend(['-', s_monom])
continue
s_coeff = self._print(coeff)
if not s_monom:
s_term = s_coeff
else:
s_term = s_coeff + " " + s_monom
if s_term.startswith('-'):
terms.extend(['-', s_term[1:]])
else:
terms.extend(['+', s_term])
if terms[0] in ['-', '+']:
modifier = terms.pop(0)
if modifier == '-':
terms[0] = '-' + terms[0]
expr = ' '.join(terms)
gens = list(map(self._print, poly.gens))
domain = "domain=%s" % self._print(poly.get_domain())
args = ", ".join([expr] + gens + [domain])
if cls in accepted_latex_functions:
tex = r"\%s {\left(%s \right)}" % (cls, args)
else:
tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)
return tex
def _print_ComplexRootOf(self, root):
cls = root.__class__.__name__
if cls == "ComplexRootOf":
cls = "CRootOf"
expr = self._print(root.expr)
index = root.index
if cls in accepted_latex_functions:
return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)
else:
return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr,
index)
def _print_RootSum(self, expr):
cls = expr.__class__.__name__
args = [self._print(expr.expr)]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
if cls in accepted_latex_functions:
return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))
else:
return r"\operatorname{%s} {\left(%s\right)}" % (cls,
", ".join(args))
def _print_PolyElement(self, poly):
mul_symbol = self._settings['mul_symbol_latex']
return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self._print(frac.numer)
denom = self._print(frac.denom)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_euler(self, expr, exp=None):
m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args
tex = r"E_{%s}" % self._print(m)
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
if x is not None:
tex = r"%s\left(%s\right)" % (tex, self._print(x))
return tex
def _print_catalan(self, expr, exp=None):
tex = r"C_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_UnifiedTransform(self, expr, s, inverse=False):
return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))
def _print_MellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M')
def _print_InverseMellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M', True)
def _print_LaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L')
def _print_InverseLaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L', True)
def _print_FourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F')
def _print_InverseFourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F', True)
def _print_SineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN')
def _print_InverseSineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN', True)
def _print_CosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS')
def _print_InverseCosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS', True)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(Symbol(object.name))
def _print_LambertW(self, expr):
if len(expr.args) == 1:
return r"W\left(%s\right)" % self._print(expr.args[0])
return r"W_{%s}\left(%s\right)" % \
(self._print(expr.args[1]), self._print(expr.args[0]))
def _print_Morphism(self, morphism):
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
return "%s\\rightarrow %s" % (domain, codomain)
def _print_TransferFunction(self, expr):
from sympy.core import Mul, Pow
num, den = expr.num, expr.den
res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False)
return self._print_Mul(res)
def _print_Series(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_Parallel(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Parallel, Series
num, tf = expr.num, TransferFunction(1, 1, expr.num.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.den.args) if isinstance(expr.den, Series) else [expr.den]
if isinstance(num, Series) and isinstance(expr.den, Series):
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
elif isinstance(num, Series) and isinstance(expr.den, TransferFunction):
if expr.den == tf:
den = Parallel(tf, Series(*num_arg_list))
else:
den = Parallel(tf, Series(*num_arg_list, expr.den))
elif isinstance(num, TransferFunction) and isinstance(expr.den, Series):
if num == tf:
den = Parallel(tf, Series(*den_arg_list))
else:
den = Parallel(tf, Series(num, *den_arg_list))
else:
if num == tf:
den = Parallel(tf, *den_arg_list)
elif expr.den == tf:
den = Parallel(tf, *num_arg_list)
else:
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
numer = self._print(num)
denom = self._print(den)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(Symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return "%s:%s" % (pretty_name, pretty_morphism)
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(NamedMorphism(
morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [self._print(Symbol(component.name)) for
component in morphism.components]
component_names_list.reverse()
component_names = "\\circ ".join(component_names_list) + ":"
pretty_morphism = self._print_Morphism(morphism)
return component_names + pretty_morphism
def _print_Category(self, morphism):
return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name)))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
latex_result = self._print(diagram.premises)
if diagram.conclusions:
latex_result += "\\Longrightarrow %s" % \
self._print(diagram.conclusions)
return latex_result
def _print_DiagramGrid(self, grid):
latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)
for i in range(grid.height):
for j in range(grid.width):
if grid[i, j]:
latex_result += latex(grid[i, j])
latex_result += " "
if j != grid.width - 1:
latex_result += "& "
if i != grid.height - 1:
latex_result += "\\\\"
latex_result += "\n"
latex_result += "\\end{array}\n"
return latex_result
def _print_FreeModule(self, M):
return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank))
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return r"\left[ {} \right]".format(",".join(
'{' + self._print(x) + '}' for x in m))
def _print_SubModule(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for x in m.gens))
def _print_ModuleImplementedIdeal(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for [x] in m._module.gens))
def _print_Quaternion(self, expr):
# TODO: This expression is potentially confusing,
# shall we print it as `Quaternion( ... )`?
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True)
for i in expr.args]
a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")]
return " + ".join(a)
def _print_QuotientRing(self, R):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(R.ring),
self._print(R.base_ideal))
def _print_QuotientRingElement(self, x):
return r"{{{}}} + {{{}}}".format(self._print(x.data),
self._print(x.ring.base_ideal))
def _print_QuotientModuleElement(self, m):
return r"{{{}}} + {{{}}}".format(self._print(m.data),
self._print(m.module.killed_module))
def _print_QuotientModule(self, M):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(M.base),
self._print(M.killed_module))
def _print_MatrixHomomorphism(self, h):
return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()),
self._print(h.domain), self._print(h.codomain))
def _print_Manifold(self, manifold):
string = manifold.name.name
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
name = r'\text{%s}' % name
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Patch(self, patch):
return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold))
def _print_CoordSystem(self, coordsys):
return r'\text{%s}^{\text{%s}}_{%s}' % (
self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold)
)
def _print_CovarDerivativeOp(self, cvd):
return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\mathbf{{{}}}'.format(self._print(Symbol(string)))
def _print_BaseVectorField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\partial_{{{}}}'.format(self._print(Symbol(string)))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return r'\operatorname{{d}}{}'.format(self._print(Symbol(string)))
else:
string = self._print(field)
return r'\operatorname{{d}}\left({}\right)'.format(string)
def _print_Tr(self, p):
# TODO: Handle indices
contents = self._print(p.args[0])
return r'\operatorname{{tr}}\left({}\right)'.format(contents)
def _print_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\phi\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\phi\left(%s\right)' % self._print(expr.args[0])
def _print_reduced_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\lambda\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\lambda\left(%s\right)' % self._print(expr.args[0])
def _print_divisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^{%s}%s" % (exp, tex)
return r"\sigma%s" % tex
def _print_udivisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^*^{%s}%s" % (exp, tex)
return r"\sigma^*%s" % tex
def _print_primenu(self, expr, exp=None):
if exp is not None:
return r'\left(\nu\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\nu\left(%s\right)' % self._print(expr.args[0])
def _print_primeomega(self, expr, exp=None):
if exp is not None:
return r'\left(\Omega\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\Omega\left(%s\right)' % self._print(expr.args[0])
def _print_Str(self, s):
return str(s.name)
def _print_float(self, expr):
return self._print(Float(expr))
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_mpq(self, expr):
return str(expr)
def emptyPrinter(self, expr):
# default to just printing as monospace, like would normally be shown
s = super().emptyPrinter(expr)
return r"\mathtt{\text{%s}}" % latex_escape(s)
def translate(s):
r'''
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"
'''
# Process the rest
tex = tex_greek_dictionary.get(s)
if tex:
return tex
elif s.lower() in greek_letters_set:
return "\\" + s.lower()
elif s in other_symbols:
return "\\" + s
else:
# Process modifiers, if any, and recurse
for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True):
if s.lower().endswith(key) and len(s) > len(key):
return modifier_dict[key](translate(s[:-len(key)]))
return s
@print_function(LatexPrinter)
def latex(expr, **settings):
r"""Convert the given expression to LaTeX string representation.
Parameters
==========
full_prec: boolean, optional
If set to True, a floating point number is printed with full precision.
fold_frac_powers : boolean, optional
Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers.
fold_func_brackets : boolean, optional
Fold function brackets where applicable.
fold_short_frac : boolean, optional
Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is
simple enough (at most two terms and no powers). The default value is
``True`` for inline mode, ``False`` otherwise.
inv_trig_style : string, optional
How inverse trig functions should be displayed. Can be one of
``abbreviated``, ``full``, or ``power``. Defaults to ``abbreviated``.
itex : boolean, optional
Specifies if itex-specific syntax is used, including emitting
``$$...$$``.
ln_notation : boolean, optional
If set to ``True``, ``\ln`` is used instead of default ``\log``.
long_frac_ratio : float or None, optional
The allowed ratio of the width of the numerator to the width of the
denominator before the printer breaks off long fractions. If ``None``
(the default value), long fractions are not broken up.
mat_delim : string, optional
The delimiter to wrap around matrices. Can be one of ``[``, ``(``, or
the empty string. Defaults to ``[``.
mat_str : string, optional
Which matrix environment string to emit. ``smallmatrix``, ``matrix``,
``array``, etc. Defaults to ``smallmatrix`` for inline mode, ``matrix``
for matrices of no more than 10 columns, and ``array`` otherwise.
mode: string, optional
Specifies how the generated code will be delimited. ``mode`` can be one
of ``plain``, ``inline``, ``equation`` or ``equation*``. If ``mode``
is set to ``plain``, then the resulting code will not be delimited at
all (this is the default). If ``mode`` is set to ``inline`` then inline
LaTeX ``$...$`` will be used. If ``mode`` is set to ``equation`` or
``equation*``, the resulting code will be enclosed in the ``equation``
or ``equation*`` environment (remember to import ``amsmath`` for
``equation*``), unless the ``itex`` option is set. In the latter case,
the ``$$...$$`` syntax is used.
mul_symbol : string or None, optional
The symbol to use for multiplication. Can be one of ``None``, ``ldot``,
``dot``, or ``times``.
order: string, optional
Any of the supported monomial orderings (currently ``lex``, ``grlex``,
or ``grevlex``), ``old``, and ``none``. This parameter does nothing for
Mul objects. Setting order to ``old`` uses the compatibility ordering
for Add defined in Printer. For very large expressions, set the
``order`` keyword to ``none`` if speed is a concern.
symbol_names : dictionary of strings mapped to symbols, optional
Dictionary of symbols and the custom strings they should be emitted as.
root_notation : boolean, optional
If set to ``False``, exponents of the form 1/n are printed in fractonal
form. Default is ``True``, to print exponent in root form.
mat_symbol_style : string, optional
Can be either ``plain`` (default) or ``bold``. If set to ``bold``,
a MatrixSymbol A will be printed as ``\mathbf{A}``, otherwise as ``A``.
imaginary_unit : string, optional
String to use for the imaginary unit. Defined options are "i" (default)
and "j". Adding "r" or "t" in front gives ``\mathrm`` or ``\text``, so
"ri" leads to ``\mathrm{i}`` which gives `\mathrm{i}`.
gothic_re_im : boolean, optional
If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively.
The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`.
decimal_separator : string, optional
Specifies what separator to use to separate the whole and fractional parts of a
floating point number as in `2.5` for the default, ``period`` or `2{,}5`
when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon
separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when
``comma`` is chosen and [1,2,3] for when ``period`` is chosen.
parenthesize_super : boolean, optional
If set to ``False``, superscripted expressions will not be parenthesized when
powered. Default is ``True``, which parenthesizes the expression when powered.
min: Integer or None, optional
Sets the lower bound for the exponent to print floating point numbers in
fixed-point format.
max: Integer or None, optional
Sets the upper bound for the exponent to print floating point numbers in
fixed-point format.
Notes
=====
Not using a print statement for printing, results in double backslashes for
latex commands since that's the way Python escapes backslashes in strings.
>>> from sympy import latex, Rational
>>> from sympy.abc import tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
Examples
========
>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
>>> from sympy.abc import x, y, mu, r, tau
Basic usage:
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
``mode`` and ``itex`` options:
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
Fraction options:
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
8 \sqrt{2} \tau^{7/2}
>>> print(latex((2*tau)**sin(Rational(7,2))))
\left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
>>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
\left(2 \tau\right)^{\sin {\frac{7}{2}}}
>>> print(latex(3*x**2/y))
\frac{3 x^{2}}{y}
>>> print(latex(3*x**2/y, fold_short_frac=True))
3 x^{2} / y
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
\frac{\int r\, dr}{2 \pi}
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
\frac{1}{2 \pi} \int r\, dr
Multiplication options:
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
\left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
Trig options:
>>> print(latex(asin(Rational(7,2))))
\operatorname{asin}{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
\arcsin{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
\sin^{-1}{\left(\frac{7}{2} \right)}
Matrix options:
>>> print(latex(Matrix(2, 1, [x, y])))
\left[\begin{matrix}x\\y\end{matrix}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
\left[\begin{array}{c}x\\y\end{array}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
\left(\begin{matrix}x\\y\end{matrix}\right)
Custom printing of symbols:
>>> print(latex(x**2, symbol_names={x: 'x_i'}))
x_i^{2}
Logarithms:
>>> print(latex(log(10)))
\log{\left(10 \right)}
>>> print(latex(log(10), ln_notation=True))
\ln{\left(10 \right)}
``latex()`` also supports the builtin container types :class:`list`,
:class:`tuple`, and :class:`dict`:
>>> print(latex([2/x, y], mode='inline'))
$\left[ 2 / x, \ y\right]$
Unsupported types are rendered as monospaced plaintext:
>>> print(latex(int))
\mathtt{\text{<class 'int'>}}
>>> print(latex("plain % text"))
\mathtt{\text{plain \% text}}
See :ref:`printer_method_example` for an example of how to override
this behavior for your own types by implementing ``_latex``.
.. versionchanged:: 1.7.0
Unsupported types no longer have their ``str`` representation treated as valid latex.
"""
return LatexPrinter(settings).doprint(expr)
def print_latex(expr, **settings):
"""Prints LaTeX representation of the given expression. Takes the same
settings as ``latex()``."""
print(latex(expr, **settings))
def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
r"""
This function generates a LaTeX equation with a multiline right-hand side
in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
Parameters
==========
lhs : Expr
Left-hand side of equation
rhs : Expr
Right-hand side of equation
terms_per_line : integer, optional
Number of terms per line to print. Default is 1.
environment : "string", optional
Which LaTeX wnvironment to use for the output. Options are "align*"
(default), "eqnarray", and "IEEEeqnarray".
use_dots : boolean, optional
If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
Examples
========
>>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
>>> x, y, alpha = symbols('x y alpha')
>>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
>>> print(multiline_latex(x, expr))
\begin{align*}
x = & e^{i \alpha} \\
& + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using at most two terms per line:
>>> print(multiline_latex(x, expr, 2))
\begin{align*}
x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using ``eqnarray`` and dots:
>>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
\begin{eqnarray}
x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{eqnarray}
Using ``IEEEeqnarray``:
>>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
\begin{IEEEeqnarray}{rCl}
x & = & e^{i \alpha} \nonumber\\
& & + \sin{\left(\alpha y \right)} \nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{IEEEeqnarray}
Notes
=====
All optional parameters from ``latex`` can also be used.
"""
# Based on code from https://github.com/sympy/sympy/issues/3001
l = LatexPrinter(**settings)
if environment == "eqnarray":
result = r'\begin{eqnarray}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{eqnarray}'
doubleet = True
elif environment == "IEEEeqnarray":
result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{IEEEeqnarray}'
doubleet = True
elif environment == "align*":
result = r'\begin{align*}' + '\n'
first_term = '= &'
nonumber = ''
end_term = '\n\\end{align*}'
doubleet = False
else:
raise ValueError("Unknown environment: {}".format(environment))
dots = ''
if use_dots:
dots=r'\dots'
terms = rhs.as_ordered_terms()
n_terms = len(terms)
term_count = 1
for i in range(n_terms):
term = terms[i]
term_start = ''
term_end = ''
sign = '+'
if term_count > terms_per_line:
if doubleet:
term_start = '& & '
else:
term_start = '& '
term_count = 1
if term_count == terms_per_line:
# End of line
if i < n_terms-1:
# There are terms remaining
term_end = dots + nonumber + r'\\' + '\n'
else:
term_end = ''
if term.as_ordered_factors()[0] == -1:
term = -1*term
sign = r'-'
if i == 0: # beginning
if sign == '+':
sign = ''
result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
first_term, sign, l.doprint(term), term_end)
else:
result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
l.doprint(term), term_end)
term_count += 1
result += end_term
return result
|
f5c9956ed260557a4fcd14caca31b3d8e79fd1456732d5f33725df81a50b054d | from sympy.concrete.expr_with_limits import AddWithLimits
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.compatibility import is_sequence
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import diff
from sympy.core.logic import fuzzy_bool
from sympy.core.mul import Mul
from sympy.core.numbers import oo, pi
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild)
from sympy.core.sympify import sympify
from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.complexes import Abs, sign
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.integrals.manualintegrate import manualintegrate
from sympy.integrals.trigonometry import trigintegrate
from sympy.integrals.meijerint import meijerint_definite, meijerint_indefinite
from sympy.matrices import MatrixBase
from sympy.polys import Poly, PolynomialError
from sympy.series import limit
from sympy.series.order import Order
from sympy.series.formal import FormalPowerSeries
from sympy.simplify.fu import sincos_to_sum
from sympy.tensor.functions import shape
from sympy.utilities.misc import filldedent
from sympy.utilities.exceptions import SymPyDeprecationWarning
class Integral(AddWithLimits):
"""Represents unevaluated integral."""
__slots__ = ('is_commutative',)
def __new__(cls, function, *symbols, **assumptions):
"""Create an unevaluated integral.
Explanation
===========
Arguments are an integrand followed by one or more limits.
If no limits are given and there is only one free symbol in the
expression, that symbol will be used, otherwise an error will be
raised.
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x)
Integral(x, x)
>>> Integral(y)
Integral(y, y)
When limits are provided, they are interpreted as follows (using
``x`` as though it were the variable of integration):
(x,) or x - indefinite integral
(x, a) - "evaluate at" integral is an abstract antiderivative
(x, a, b) - definite integral
The ``as_dummy`` method can be used to see which symbols cannot be
targeted by subs: those with a prepended underscore cannot be
changed with ``subs``. (Also, the integration variables themselves --
the first element of a limit -- can never be changed by subs.)
>>> i = Integral(x, x)
>>> at = Integral(x, (x, x))
>>> i.as_dummy()
Integral(x, x)
>>> at.as_dummy()
Integral(_0, (_0, x))
"""
#This will help other classes define their own definitions
#of behaviour with Integral.
if hasattr(function, '_eval_Integral'):
return function._eval_Integral(*symbols, **assumptions)
if isinstance(function, Poly):
SymPyDeprecationWarning(
feature="Using integrate/Integral with Poly",
issue=18613,
deprecated_since_version="1.6",
useinstead="the as_expr or integrate methods of Poly").warn()
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
return obj
def __getnewargs__(self):
return (self.function,) + tuple([tuple(xab) for xab in self.limits])
@property
def free_symbols(self):
"""
This method returns the symbols that will exist when the
integral is evaluated. This is useful if one is trying to
determine whether an integral depends on a certain
symbol or not.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x, (x, y, 1)).free_symbols
{y}
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.function
sympy.concrete.expr_with_limits.ExprWithLimits.limits
sympy.concrete.expr_with_limits.ExprWithLimits.variables
"""
return AddWithLimits.free_symbols.fget(self)
def _eval_is_zero(self):
# This is a very naive and quick test, not intended to do the integral to
# answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
# is zero but this routine should return None for that case. But, like
# Mul, there are trivial situations for which the integral will be
# zero so we check for those.
if self.function.is_zero:
return True
got_none = False
for l in self.limits:
if len(l) == 3:
z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
if z:
return True
elif z is None:
got_none = True
free = self.function.free_symbols
for xab in self.limits:
if len(xab) == 1:
free.add(xab[0])
continue
if len(xab) == 2 and xab[0] not in free:
if xab[1].is_zero:
return True
elif xab[1].is_zero is None:
got_none = True
# take integration symbol out of free since it will be replaced
# with the free symbols in the limits
free.discard(xab[0])
# add in the new symbols
for i in xab[1:]:
free.update(i.free_symbols)
if self.function.is_zero is False and got_none is False:
return False
def transform(self, x, u):
r"""
Performs a change of variables from `x` to `u` using the relationship
given by `x` and `u` which will define the transformations `f` and `F`
(which are inverses of each other) as follows:
1) If `x` is a Symbol (which is a variable of integration) then `u`
will be interpreted as some function, f(u), with inverse F(u).
This, in effect, just makes the substitution of x with f(x).
2) If `u` is a Symbol then `x` will be interpreted as some function,
F(x), with inverse f(u). This is commonly referred to as
u-substitution.
Once f and F have been identified, the transformation is made as
follows:
.. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
\frac{\mathrm{d}}{\mathrm{d}x}
where `F(x)` is the inverse of `f(x)` and the limits and integrand have
been corrected so as to retain the same value after integration.
Notes
=====
The mappings, F(x) or f(u), must lead to a unique integral. Linear
or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
always work; quadratic expressions like ``x**2 - 1`` are acceptable
as long as the resulting integrand does not depend on the sign of
the solutions (see examples).
The integral will be returned unchanged if ``x`` is not a variable of
integration.
``x`` must be (or contain) only one of of the integration variables. If
``u`` has more than one free symbol then it should be sent as a tuple
(``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
the integration variable.
XXX can it contain another integration variable?
Examples
========
>>> from sympy.abc import a, x, u
>>> from sympy import Integral, cos, sqrt
>>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
transform can change the variable of integration
>>> i.transform(x, u)
Integral(u*cos(u**2 - 1), (u, 0, 1))
transform can perform u-substitution as long as a unique
integrand is obtained:
>>> i.transform(x**2 - 1, u)
Integral(cos(u)/2, (u, -1, 0))
This attempt fails because x = +/-sqrt(u + 1) and the
sign does not cancel out of the integrand:
>>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
Traceback (most recent call last):
...
ValueError:
The mapping between F(x) and f(u) did not give a unique integrand.
transform can do a substitution. Here, the previous
result is transformed back into the original expression
using "u-substitution":
>>> ui = _
>>> _.transform(sqrt(u + 1), x) == i
True
We can accomplish the same with a regular substitution:
>>> ui.transform(u, x**2 - 1) == i
True
If the `x` does not contain a symbol of integration then
the integral will be returned unchanged. Integral `i` does
not have an integration variable `a` so no change is made:
>>> i.transform(a, x) == i
True
When `u` has more than one free symbol the symbol that is
replacing `x` must be identified by passing `u` as a tuple:
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
Integral(a + u, (u, -a, 1 - a))
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
Integral(a + u, (a, -u, 1 - u))
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
as_dummy : Replace integration variables with dummy ones
"""
from sympy.solvers.solvers import solve, posify
d = Dummy('d')
xfree = x.free_symbols.intersection(self.variables)
if len(xfree) > 1:
raise ValueError(
'F(x) can only contain one of: %s' % self.variables)
xvar = xfree.pop() if xfree else d
if xvar not in self.variables:
return self
u = sympify(u)
if isinstance(u, Expr):
ufree = u.free_symbols
if len(ufree) == 0:
raise ValueError(filldedent('''
f(u) cannot be a constant'''))
if len(ufree) > 1:
raise ValueError(filldedent('''
When f(u) has more than one free symbol, the one replacing x
must be identified: pass f(u) as (f(u), u)'''))
uvar = ufree.pop()
else:
u, uvar = u
if uvar not in u.free_symbols:
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) where symbol identified
a free symbol in expr, but symbol is not in expr's free
symbols.'''))
if not isinstance(uvar, Symbol):
# This probably never evaluates to True
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) but didn't get
a symbol; got %s''' % uvar))
if x.is_Symbol and u.is_Symbol:
return self.xreplace({x: u})
if not x.is_Symbol and not u.is_Symbol:
raise ValueError('either x or u must be a symbol')
if uvar == xvar:
return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
if uvar in self.limits:
raise ValueError(filldedent('''
u must contain the same variable as in x
or a variable that is not already an integration variable'''))
if not x.is_Symbol:
F = [x.subs(xvar, d)]
soln = solve(u - x, xvar, check=False)
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), x)')
f = [fi.subs(uvar, d) for fi in soln]
else:
f = [u.subs(uvar, d)]
pdiff, reps = posify(u - x)
puvar = uvar.subs([(v, k) for k, v in reps.items()])
soln = [s.subs(reps) for s in solve(pdiff, puvar)]
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), u)')
F = [fi.subs(xvar, d) for fi in soln]
newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
).subs(d, uvar) for fi in f}
if len(newfuncs) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not give
a unique integrand.'''))
newfunc = newfuncs.pop()
def _calc_limit_1(F, a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
wok = F.subs(d, a)
if wok is S.NaN or wok.is_finite is False and a.is_finite:
return limit(sign(b)*F, d, a)
return wok
def _calc_limit(a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
if len(avals) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not
give a unique limit.'''))
return avals[0]
newlimits = []
for xab in self.limits:
sym = xab[0]
if sym == xvar:
if len(xab) == 3:
a, b = xab[1:]
a, b = _calc_limit(a, b), _calc_limit(b, a)
if fuzzy_bool(a - b > 0):
a, b = b, a
newfunc = -newfunc
newlimits.append((uvar, a, b))
elif len(xab) == 2:
a = _calc_limit(xab[1], 1)
newlimits.append((uvar, a))
else:
newlimits.append(uvar)
else:
newlimits.append(xab)
return self.func(newfunc, *newlimits)
def doit(self, **hints):
"""
Perform the integration using any hints given.
Examples
========
>>> from sympy import Piecewise, S
>>> from sympy.abc import x, t
>>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
>>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
1/3
See Also
========
sympy.integrals.trigonometry.trigintegrate
sympy.integrals.heurisch.heurisch
sympy.integrals.rationaltools.ratint
as_sum : Approximate the integral using a sum
"""
from sympy.concrete.summations import Sum
if not hints.get('integrals', True):
return self
deep = hints.get('deep', True)
meijerg = hints.get('meijerg', None)
conds = hints.get('conds', 'piecewise')
risch = hints.get('risch', None)
heurisch = hints.get('heurisch', None)
manual = hints.get('manual', None)
if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
elif manual:
meijerg = risch = heurisch = False
elif meijerg:
manual = risch = heurisch = False
elif risch:
manual = meijerg = heurisch = False
elif heurisch:
manual = meijerg = risch = False
eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual, heurisch=heurisch,
conds=conds)
if conds not in ['separate', 'piecewise', 'none']:
raise ValueError('conds must be one of "separate", "piecewise", '
'"none", got: %s' % conds)
if risch and any(len(xab) > 1 for xab in self.limits):
raise ValueError('risch=True is only allowed for indefinite integrals.')
# check for the trivial zero
if self.is_zero:
return S.Zero
# hacks to handle integrals of
# nested summations
if isinstance(self.function, Sum):
if any(v in self.function.limits[0] for v in self.variables):
raise ValueError('Limit of the sum cannot be an integration variable.')
if any(l.is_infinite for l in self.function.limits[0][1:]):
return self
_i = self
_sum = self.function
return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
# now compute and check the function
function = self.function
if deep:
function = function.doit(**hints)
if function.is_zero:
return S.Zero
# hacks to handle special cases
if isinstance(function, MatrixBase):
return function.applyfunc(
lambda f: self.func(f, self.limits).doit(**hints))
if isinstance(function, FormalPowerSeries):
if len(self.limits) > 1:
raise NotImplementedError
xab = self.limits[0]
if len(xab) > 1:
return function.integrate(xab, **eval_kwargs)
else:
return function.integrate(xab[0], **eval_kwargs)
# There is no trivial answer and special handling
# is done so continue
# first make sure any definite limits have integration
# variables with matching assumptions
reps = {}
for xab in self.limits:
if len(xab) != 3:
continue
x, a, b = xab
l = (a, b)
if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
d = Dummy(positive=True)
elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
d = Dummy(negative=True)
elif all(i.is_real for i in l) and not x.is_real:
d = Dummy(real=True)
else:
d = None
if d:
reps[x] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if type(did) is tuple: # when separate=True
did = tuple([i.xreplace(undo) for i in did])
else:
did = did.xreplace(undo)
return did
# continue with existing assumptions
undone_limits = []
# ulj = free symbols of any undone limits' upper and lower limits
ulj = set()
for xab in self.limits:
# compute uli, the free symbols in the
# Upper and Lower limits of limit I
if len(xab) == 1:
uli = set(xab[:1])
elif len(xab) == 2:
uli = xab[1].free_symbols
elif len(xab) == 3:
uli = xab[1].free_symbols.union(xab[2].free_symbols)
# this integral can be done as long as there is no blocking
# limit that has been undone. An undone limit is blocking if
# it contains an integration variable that is in this limit's
# upper or lower free symbols or vice versa
if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
undone_limits.append(xab)
ulj.update(uli)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
if function.has(Abs, sign) and (
(len(xab) < 3 and all(x.is_extended_real for x in xab)) or
(len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
x in xab[1:]))):
# some improper integrals are better off with Abs
xr = Dummy("xr", real=True)
function = (function.xreplace({xab[0]: xr})
.rewrite(Piecewise).xreplace({xr: xab[0]}))
elif function.has(Min, Max):
function = function.rewrite(Piecewise)
if (function.has(Piecewise) and
not isinstance(function, Piecewise)):
function = piecewise_fold(function)
if isinstance(function, Piecewise):
if len(xab) == 1:
antideriv = function._eval_integral(xab[0],
**eval_kwargs)
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
else:
# There are a number of tradeoffs in using the
# Meijer G method. It can sometimes be a lot faster
# than other methods, and sometimes slower. And
# there are certain types of integrals for which it
# is more likely to work than others. These
# heuristics are incorporated in deciding what
# integration methods to try, in what order. See the
# integrate() docstring for details.
def try_meijerg(function, xab):
ret = None
if len(xab) == 3 and meijerg is not False:
x, a, b = xab
try:
res = meijerint_definite(function, x, a, b)
except NotImplementedError:
from sympy.integrals.meijerint import _debug
_debug('NotImplementedError '
'from meijerint_definite')
res = None
if res is not None:
f, cond = res
if conds == 'piecewise':
ret = Piecewise(
(f, cond),
(self.func(
function, (x, a, b)), True))
elif conds == 'separate':
if len(self.limits) != 1:
raise ValueError(filldedent('''
conds=separate not supported in
multiple integrals'''))
ret = f, cond
else:
ret = f
return ret
meijerg1 = meijerg
if (meijerg is not False and
len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
and not function.is_Poly and
(xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
meijerg1 = False
# If the special meijerg code did not succeed in
# finding a definite integral, then the code using
# meijerint_indefinite will not either (it might
# find an antiderivative, but the answer is likely
# to be nonsensical). Thus if we are requested to
# only use Meijer G-function methods, we give up at
# this stage. Otherwise we just disable G-function
# methods.
if meijerg1 is False and meijerg is True:
antideriv = None
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
if antideriv is None and meijerg is True:
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
if not isinstance(antideriv, Integral) and antideriv is not None:
for atan_term in antideriv.atoms(atan):
atan_arg = atan_term.args[0]
# Checking `atan_arg` to be linear combination of `tan` or `cot`
for tan_part in atan_arg.atoms(tan):
x1 = Dummy('x1')
tan_exp1 = atan_arg.subs(tan_part, x1)
# The coefficient of `tan` should be constant
coeff = tan_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = tan_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a-pi/2)/pi)))
for cot_part in atan_arg.atoms(cot):
x1 = Dummy('x1')
cot_exp1 = atan_arg.subs(cot_part, x1)
# The coefficient of `cot` should be constant
coeff = cot_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = cot_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a)/pi)))
if antideriv is None:
undone_limits.append(xab)
function = self.func(*([function] + [xab])).factor()
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
else:
if len(xab) == 1:
function = antideriv
else:
if len(xab) == 3:
x, a, b = xab
elif len(xab) == 2:
x, b = xab
a = None
else:
raise NotImplementedError
if deep:
if isinstance(a, Basic):
a = a.doit(**hints)
if isinstance(b, Basic):
b = b.doit(**hints)
if antideriv.is_Poly:
gens = list(antideriv.gens)
gens.remove(x)
antideriv = antideriv.as_expr()
function = antideriv._eval_interval(x, a, b)
function = Poly(function, *gens)
else:
def is_indef_int(g, x):
return (isinstance(g, Integral) and
any(i == (x,) for i in g.limits))
def eval_factored(f, x, a, b):
# _eval_interval for integrals with
# (constant) factors
# a single indefinite integral is assumed
args = []
for g in Mul.make_args(f):
if is_indef_int(g, x):
args.append(g._eval_interval(x, a, b))
else:
args.append(g)
return Mul(*args)
integrals, others, piecewises = [], [], []
for f in Add.make_args(antideriv):
if any(is_indef_int(g, x)
for g in Mul.make_args(f)):
integrals.append(f)
elif any(isinstance(g, Piecewise)
for g in Mul.make_args(f)):
piecewises.append(piecewise_fold(f))
else:
others.append(f)
uneval = Add(*[eval_factored(f, x, a, b)
for f in integrals])
try:
evalued = Add(*others)._eval_interval(x, a, b)
evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
function = uneval + evalued + evalued_pw
except NotImplementedError:
# This can happen if _eval_interval depends in a
# complicated way on limits that cannot be computed
undone_limits.append(xab)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
return function
def _eval_derivative(self, sym):
"""Evaluate the derivative of the current Integral object by
differentiating under the integral sign [1], using the Fundamental
Theorem of Calculus [2] when possible.
Explanation
===========
Whenever an Integral is encountered that is equivalent to zero or
has an integrand that is independent of the variable of integration
those integrals are performed. All others are returned as Integral
instances which can be resolved with doit() (provided they are integrable).
References
==========
.. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
.. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> i = Integral(x + y, y, (y, 1, x))
>>> i.diff(x)
Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
>>> i.doit().diff(x) == i.diff(x).doit()
True
>>> i.diff(y)
0
The previous must be true since there is no y in the evaluated integral:
>>> i.free_symbols
{x}
>>> i.doit()
2*x**3/3 - x/2 - 1/6
"""
# differentiate under the integral sign; we do not
# check for regularity conditions (TODO), see issue 4215
# get limits and the function
f, limits = self.function, list(self.limits)
# the order matters if variables of integration appear in the limits
# so work our way in from the outside to the inside.
limit = limits.pop(-1)
if len(limit) == 3:
x, a, b = limit
elif len(limit) == 2:
x, b = limit
a = None
else:
a = b = None
x = limit[0]
if limits: # f is the argument to an integral
f = self.func(f, *tuple(limits))
# assemble the pieces
def _do(f, ab):
dab_dsym = diff(ab, sym)
if not dab_dsym:
return S.Zero
if isinstance(f, Integral):
limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
for l in f.limits]
f = self.func(f.function, *limits)
return f.subs(x, ab)*dab_dsym
rv = S.Zero
if b is not None:
rv += _do(f, b)
if a is not None:
rv -= _do(f, a)
if len(limit) == 1 and sym == x:
# the dummy variable *is* also the real-world variable
arg = f
rv += arg
else:
# the dummy variable might match sym but it's
# only a dummy and the actual variable is determined
# by the limits, so mask off the variable of integration
# while differentiating
u = Dummy('u')
arg = f.subs(x, u).diff(sym).subs(u, x)
if arg:
rv += self.func(arg, Tuple(x, a, b))
return rv
def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
heurisch=None, conds='piecewise'):
"""
Calculate the anti-derivative to the function f(x).
Explanation
===========
The following algorithms are applied (roughly in this order):
1. Simple heuristics (based on pattern matching and integral table):
- most frequently used functions (e.g. polynomials, products of
trig functions)
2. Integration of rational functions:
- A complete algorithm for integrating rational functions is
implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
also uses the partial fraction decomposition algorithm
implemented in apart() as a preprocessor to make this process
faster. Note that the integral of a rational function is always
elementary, but in general, it may include a RootSum.
3. Full Risch algorithm:
- The Risch algorithm is a complete decision
procedure for integrating elementary functions, which means that
given any elementary function, it will either compute an
elementary antiderivative, or else prove that none exists.
Currently, part of transcendental case is implemented, meaning
elementary integrals containing exponentials, logarithms, and
(soon!) trigonometric functions can be computed. The algebraic
case, e.g., functions containing roots, is much more difficult
and is not implemented yet.
- If the routine fails (because the integrand is not elementary, or
because a case is not implemented yet), it continues on to the
next algorithms below. If the routine proves that the integrals
is nonelementary, it still moves on to the algorithms below,
because we might be able to find a closed-form solution in terms
of special functions. If risch=True, however, it will stop here.
4. The Meijer G-Function algorithm:
- This algorithm works by first rewriting the integrand in terms of
very general Meijer G-Function (meijerg in SymPy), integrating
it, and then rewriting the result back, if possible. This
algorithm is particularly powerful for definite integrals (which
is actually part of a different method of Integral), since it can
compute closed-form solutions of definite integrals even when no
closed-form indefinite integral exists. But it also is capable
of computing many indefinite integrals as well.
- Another advantage of this method is that it can use some results
about the Meijer G-Function to give a result in terms of a
Piecewise expression, which allows to express conditionally
convergent integrals.
- Setting meijerg=True will cause integrate() to use only this
method.
5. The "manual integration" algorithm:
- This algorithm tries to mimic how a person would find an
antiderivative by hand, for example by looking for a
substitution or applying integration by parts. This algorithm
does not handle as many integrands but can return results in a
more familiar form.
- Sometimes this algorithm can evaluate parts of an integral; in
this case integrate() will try to evaluate the rest of the
integrand using the other methods here.
- Setting manual=True will cause integrate() to use only this
method.
6. The Heuristic Risch algorithm:
- This is a heuristic version of the Risch algorithm, meaning that
it is not deterministic. This is tried as a last resort because
it can be very slow. It is still used because not enough of the
full Risch algorithm is implemented, so that there are still some
integrals that can only be computed using this method. The goal
is to implement enough of the Risch and Meijer G-function methods
so that this can be deleted.
Setting heurisch=True will cause integrate() to use only this
method. Set heurisch=False to not use it.
"""
from sympy.integrals.deltafunctions import deltaintegrate
from sympy.integrals.singularityfunctions import singularityintegrate
from sympy.integrals.heurisch import heurisch as heurisch_, heurisch_wrapper
from sympy.integrals.rationaltools import ratint
from sympy.integrals.risch import risch_integrate
if risch:
try:
return risch_integrate(f, x, conds=conds)
except NotImplementedError:
return None
if manual:
try:
result = manualintegrate(f, x)
if result is not None and result.func != Integral:
return result
except (ValueError, PolynomialError):
pass
eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual,
heurisch=heurisch, conds=conds)
# if it is a poly(x) then let the polynomial integrate itself (fast)
#
# It is important to make this check first, otherwise the other code
# will return a sympy expression instead of a Polynomial.
#
# see Polynomial for details.
if isinstance(f, Poly) and not (manual or meijerg or risch):
SymPyDeprecationWarning(
feature="Using integrate/Integral with Poly",
issue=18613,
deprecated_since_version="1.6",
useinstead="the as_expr or integrate methods of Poly").warn()
return f.integrate(x)
# Piecewise antiderivatives need to call special integrate.
if isinstance(f, Piecewise):
return f.piecewise_integrate(x, **eval_kwargs)
# let's cut it short if `f` does not depend on `x`; if
# x is only a dummy, that will be handled below
if not f.has(x):
return f*x
# try to convert to poly(x) and then integrate if successful (fast)
poly = f.as_poly(x)
if poly is not None and not (manual or meijerg or risch):
return poly.integrate().as_expr()
if risch is not False:
try:
result, i = risch_integrate(f, x, separate_integral=True,
conds=conds)
except NotImplementedError:
pass
else:
if i:
# There was a nonelementary integral. Try integrating it.
# if no part of the NonElementaryIntegral is integrated by
# the Risch algorithm, then use the original function to
# integrate, instead of re-written one
if result == 0:
from sympy.integrals.risch import NonElementaryIntegral
return NonElementaryIntegral(f, x).doit(risch=False)
else:
return result + i.doit(risch=False)
else:
return result
# since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
# we are going to handle Add terms separately,
# if `f` is not Add -- we only have one term
# Note that in general, this is a bad idea, because Integral(g1) +
# Integral(g2) might not be computable, even if Integral(g1 + g2) is.
# For example, Integral(x**x + x**x*log(x)). But many heuristics only
# work term-wise. So we compute this step last, after trying
# risch_integrate. We also try risch_integrate again in this loop,
# because maybe the integral is a sum of an elementary part and a
# nonelementary part (like erf(x) + exp(x)). risch_integrate() is
# quite fast, so this is acceptable.
parts = []
args = Add.make_args(f)
for g in args:
coeff, g = g.as_independent(x)
# g(x) = const
if g is S.One and not meijerg:
parts.append(coeff*x)
continue
# g(x) = expr + O(x**n)
order_term = g.getO()
if order_term is not None:
h = self._eval_integral(g.removeO(), x, **eval_kwargs)
if h is not None:
h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
if h_order_expr is not None:
h_order_term = order_term.func(
h_order_expr, *order_term.variables)
parts.append(coeff*(h + h_order_term))
continue
# NOTE: if there is O(x**n) and we fail to integrate then
# there is no point in trying other methods because they
# will fail, too.
return None
# c
# g(x) = (a*x+b)
if g.is_Pow and not g.exp.has(x) and not meijerg:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
M = g.base.match(a*x + b)
if M is not None:
if g.exp == -1:
h = log(g.base)
elif conds != 'piecewise':
h = g.base**(g.exp + 1) / (g.exp + 1)
else:
h1 = log(g.base)
h2 = g.base**(g.exp + 1) / (g.exp + 1)
h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
parts.append(coeff * h / M[a])
continue
# poly(x)
# g(x) = -------
# poly(x)
if g.is_rational_function(x) and not (manual or meijerg or risch):
parts.append(coeff * ratint(g, x))
continue
if not (manual or meijerg or risch):
# g(x) = Mul(trig)
h = trigintegrate(g, x, conds=conds)
if h is not None:
parts.append(coeff * h)
continue
# g(x) has at least a DiracDelta term
h = deltaintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
# g(x) has at least a Singularity Function term
h = singularityintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
# Try risch again.
if risch is not False:
try:
h, i = risch_integrate(g, x,
separate_integral=True, conds=conds)
except NotImplementedError:
h = None
else:
if i:
h = h + i.doit(risch=False)
parts.append(coeff*h)
continue
# fall back to heurisch
if heurisch is not False:
try:
if conds == 'piecewise':
h = heurisch_wrapper(g, x, hints=[])
else:
h = heurisch_(g, x, hints=[])
except PolynomialError:
# XXX: this exception means there is a bug in the
# implementation of heuristic Risch integration
# algorithm.
h = None
else:
h = None
if meijerg is not False and h is None:
# rewrite using G functions
try:
h = meijerint_indefinite(g, x)
except NotImplementedError:
from sympy.integrals.meijerint import _debug
_debug('NotImplementedError from meijerint_definite')
if h is not None:
parts.append(coeff * h)
continue
if h is None and manual is not False:
try:
result = manualintegrate(g, x)
if result is not None and not isinstance(result, Integral):
if result.has(Integral) and not manual:
# Try to have other algorithms do the integrals
# manualintegrate can't handle,
# unless we were asked to use manual only.
# Keep the rest of eval_kwargs in case another
# method was set to False already
new_eval_kwargs = eval_kwargs
new_eval_kwargs["manual"] = False
result = result.func(*[
arg.doit(**new_eval_kwargs) if
arg.has(Integral) else arg
for arg in result.args
]).expand(multinomial=False,
log=False,
power_exp=False,
power_base=False)
if not result.has(Integral):
parts.append(coeff * result)
continue
except (ValueError, PolynomialError):
# can't handle some SymPy expressions
pass
# if we failed maybe it was because we had
# a product that could have been expanded,
# so let's try an expansion of the whole
# thing before giving up; we don't try this
# at the outset because there are things
# that cannot be solved unless they are
# NOT expanded e.g., x**x*(1+log(x)). There
# should probably be a checker somewhere in this
# routine to look for such cases and try to do
# collection on the expressions if they are already
# in an expanded form
if not h and len(args) == 1:
f = sincos_to_sum(f).expand(mul=True, deep=False)
if f.is_Add:
# Note: risch will be identical on the expanded
# expression, but maybe it will be able to pick out parts,
# like x*(exp(x) + erf(x)).
return self._eval_integral(f, x, **eval_kwargs)
if h is not None:
parts.append(coeff * h)
else:
return None
return Add(*parts)
def _eval_lseries(self, x, logx, cdir=0):
expr = self.as_dummy()
symb = x
for l in expr.limits:
if x in l[1:]:
symb = l[0]
break
for term in expr.function.lseries(symb, logx):
yield integrate(term, *expr.limits)
def _eval_nseries(self, x, n, logx, cdir=0):
expr = self.as_dummy()
symb = x
for l in expr.limits:
if x in l[1:]:
symb = l[0]
break
terms, order = expr.function.nseries(
x=symb, n=n, logx=logx).as_coeff_add(Order)
order = [o.subs(symb, x) for o in order]
return integrate(terms, *expr.limits) + Add(*order)*x
def _eval_as_leading_term(self, x, cdir=0):
series_gen = self.args[0].lseries(x)
for leading_term in series_gen:
if leading_term != 0:
break
return integrate(leading_term, *self.args[1:])
def _eval_simplify(self, **kwargs):
from sympy.core.exprtools import factor_terms
from sympy.simplify.simplify import simplify
expr = factor_terms(self)
if isinstance(expr, Integral):
return expr.func(*[simplify(i, **kwargs) for i in expr.args])
return expr.simplify(**kwargs)
def as_sum(self, n=None, method="midpoint", evaluate=True):
"""
Approximates a definite integral by a sum.
Parameters
==========
n :
The number of subintervals to use, optional.
method :
One of: 'left', 'right', 'midpoint', 'trapezoid'.
evaluate : bool
If False, returns an unevaluated Sum expression. The default
is True, evaluate the sum.
Notes
=====
These methods of approximate integration are described in [1].
Examples
========
>>> from sympy import sin, sqrt
>>> from sympy.abc import x, n
>>> from sympy.integrals import Integral
>>> e = Integral(sin(x), (x, 3, 7))
>>> e
Integral(sin(x), (x, 3, 7))
For demonstration purposes, this interval will only be split into 2
regions, bounded by [3, 5] and [5, 7].
The left-hand rule uses function evaluations at the left of each
interval:
>>> e.as_sum(2, 'left')
2*sin(5) + 2*sin(3)
The midpoint rule uses evaluations at the center of each interval:
>>> e.as_sum(2, 'midpoint')
2*sin(4) + 2*sin(6)
The right-hand rule uses function evaluations at the right of each
interval:
>>> e.as_sum(2, 'right')
2*sin(5) + 2*sin(7)
The trapezoid rule uses function evaluations on both sides of the
intervals. This is equivalent to taking the average of the left and
right hand rule results:
>>> e.as_sum(2, 'trapezoid')
2*sin(5) + sin(3) + sin(7)
>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _
True
Here, the discontinuity at x = 0 can be avoided by using the
midpoint or right-hand method:
>>> e = Integral(1/sqrt(x), (x, 0, 1))
>>> e.as_sum(5).n(4)
1.730
>>> e.as_sum(10).n(4)
1.809
>>> e.doit().n(4) # the actual value is 2
2.000
The left- or trapezoid method will encounter the discontinuity and
return infinity:
>>> e.as_sum(5, 'left')
zoo
The number of intervals can be symbolic. If omitted, a dummy symbol
will be used for it.
>>> e = Integral(x**2, (x, 0, 2))
>>> e.as_sum(n, 'right').expand()
8/3 + 4/n + 4/(3*n**2)
This shows that the midpoint rule is more accurate, as its error
term decays as the square of n:
>>> e.as_sum(method='midpoint').expand()
8/3 - 2/(3*_n**2)
A symbolic sum is returned with evaluate=False:
>>> e.as_sum(n, 'midpoint', evaluate=False)
2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
See Also
========
Integral.doit : Perform the integration using any hints
References
==========
.. [1] https://en.wikipedia.org/wiki/Riemann_sum#Methods
"""
from sympy.concrete.summations import Sum
limits = self.limits
if len(limits) > 1:
raise NotImplementedError(
"Multidimensional midpoint rule not implemented yet")
else:
limit = limits[0]
if (len(limit) != 3 or limit[1].is_finite is False or
limit[2].is_finite is False):
raise ValueError("Expecting a definite integral over "
"a finite interval.")
if n is None:
n = Dummy('n', integer=True, positive=True)
else:
n = sympify(n)
if (n.is_positive is False or n.is_integer is False or
n.is_finite is False):
raise ValueError("n must be a positive integer, got %s" % n)
x, a, b = limit
dx = (b - a)/n
k = Dummy('k', integer=True, positive=True)
f = self.function
if method == "left":
result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
elif method == "right":
result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
elif method == "midpoint":
result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
elif method == "trapezoid":
result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
else:
raise ValueError("Unknown method %s" % method)
return result.doit() if evaluate else result
def _sage_(self):
import sage.all as sage
f, limits = self.function._sage_(), list(self.limits)
for limit_ in limits:
if len(limit_) == 1:
x = limit_[0]
f = sage.integral(f,
x._sage_(),
hold=True)
elif len(limit_) == 2:
x, b = limit_
f = sage.integral(f,
x._sage_(),
b._sage_(),
hold=True)
else:
x, a, b = limit_
f = sage.integral(f,
(x._sage_(),
a._sage_(),
b._sage_()),
hold=True)
return f
def principal_value(self, **kwargs):
"""
Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
on the real axis.
Explanation
===========
In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
integrals which would otherwise be undefined.
Examples
========
>>> from sympy import oo
>>> from sympy.integrals.integrals import Integral
>>> from sympy.abc import x
>>> Integral(x+1, (x, -oo, oo)).principal_value()
oo
>>> f = 1 / (x**3)
>>> Integral(f, (x, -oo, oo)).principal_value()
0
>>> Integral(f, (x, -10, 10)).principal_value()
0
>>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
0
References
==========
.. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
.. [2] http://mathworld.wolfram.com/CauchyPrincipalValue.html
"""
from sympy.calculus import singularities
if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
"cauchy's principal value")
x, a, b = self.limits[0]
if not (a.is_comparable and b.is_comparable and a <= b):
raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
"cauchy's principal value. Also, a and b need to be comparable.")
if a == b:
return 0
r = Dummy('r')
f = self.function
singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
for i in singularities_list:
if (i == b) or (i == a):
raise ValueError(
'The principal value is not defined in the given interval due to singularity at %d.' % (i))
F = integrate(f, x, **kwargs)
if F.has(Integral):
return self
if a is -oo and b is oo:
I = limit(F - F.subs(x, -x), x, oo)
else:
I = limit(F, x, b, '-') - limit(F, x, a, '+')
for s in singularities_list:
I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
return I
def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
"""integrate(f, var, ...)
Explanation
===========
Compute definite or indefinite integral of one or more variables
using Risch-Norman algorithm and table lookup. This procedure is
able to handle elementary algebraic and transcendental functions
and also a huge class of special functions, including Airy,
Bessel, Whittaker and Lambert.
var can be:
- a symbol -- indefinite integration
- a tuple (symbol, a) -- indefinite integration with result
given with `a` replacing `symbol`
- a tuple (symbol, a, b) -- definite integration
Several variables can be specified, in which case the result is
multiple integration. (If var is omitted and the integrand is
univariate, the indefinite integral in that variable will be performed.)
Indefinite integrals are returned without terms that are independent
of the integration variables. (see examples)
Definite improper integrals often entail delicate convergence
conditions. Pass conds='piecewise', 'separate' or 'none' to have
these returned, respectively, as a Piecewise function, as a separate
result (i.e. result will be a tuple), or not at all (default is
'piecewise').
**Strategy**
SymPy uses various approaches to definite integration. One method is to
find an antiderivative for the integrand, and then use the fundamental
theorem of calculus. Various functions are implemented to integrate
polynomial, rational and trigonometric functions, and integrands
containing DiracDelta terms.
SymPy also implements the part of the Risch algorithm, which is a decision
procedure for integrating elementary functions, i.e., the algorithm can
either find an elementary antiderivative, or prove that one does not
exist. There is also a (very successful, albeit somewhat slow) general
implementation of the heuristic Risch algorithm. This algorithm will
eventually be phased out as more of the full Risch algorithm is
implemented. See the docstring of Integral._eval_integral() for more
details on computing the antiderivative using algebraic methods.
The option risch=True can be used to use only the (full) Risch algorithm.
This is useful if you want to know if an elementary function has an
elementary antiderivative. If the indefinite Integral returned by this
function is an instance of NonElementaryIntegral, that means that the
Risch algorithm has proven that integral to be non-elementary. Note that
by default, additional methods (such as the Meijer G method outlined
below) are tried on these integrals, as they may be expressible in terms
of special functions, so if you only care about elementary answers, use
risch=True. Also note that an unevaluated Integral returned by this
function is not necessarily a NonElementaryIntegral, even with risch=True,
as it may just be an indication that the particular part of the Risch
algorithm needed to integrate that function is not yet implemented.
Another family of strategies comes from re-writing the integrand in
terms of so-called Meijer G-functions. Indefinite integrals of a
single G-function can always be computed, and the definite integral
of a product of two G-functions can be computed from zero to
infinity. Various strategies are implemented to rewrite integrands
as G-functions, and use this information to compute integrals (see
the ``meijerint`` module).
The option manual=True can be used to use only an algorithm that tries
to mimic integration by hand. This algorithm does not handle as many
integrands as the other algorithms implemented but may return results in
a more familiar form. The ``manualintegrate`` module has functions that
return the steps used (see the module docstring for more information).
In general, the algebraic methods work best for computing
antiderivatives of (possibly complicated) combinations of elementary
functions. The G-function methods work best for computing definite
integrals from zero to infinity of moderately complicated
combinations of special functions, or indefinite integrals of very
simple combinations of special functions.
The strategy employed by the integration code is as follows:
- If computing a definite integral, and both limits are real,
and at least one limit is +- oo, try the G-function method of
definite integration first.
- Try to find an antiderivative, using all available methods, ordered
by performance (that is try fastest method first, slowest last; in
particular polynomial integration is tried first, Meijer
G-functions second to last, and heuristic Risch last).
- If still not successful, try G-functions irrespective of the
limits.
The option meijerg=True, False, None can be used to, respectively:
always use G-function methods and no others, never use G-function
methods, or use all available methods (in order as described above).
It defaults to None.
Examples
========
>>> from sympy import integrate, log, exp, oo
>>> from sympy.abc import a, x, y
>>> integrate(x*y, x)
x**2*y/2
>>> integrate(log(x), x)
x*log(x) - x
>>> integrate(log(x), (x, 1, a))
a*log(a) - a + 1
>>> integrate(x)
x**2/2
Terms that are independent of x are dropped by indefinite integration:
>>> from sympy import sqrt
>>> integrate(sqrt(1 + x), (x, 0, x))
2*(x + 1)**(3/2)/3 - 2/3
>>> integrate(sqrt(1 + x), x)
2*(x + 1)**(3/2)/3
>>> integrate(x*y)
Traceback (most recent call last):
...
ValueError: specify integration variables to integrate x*y
Note that ``integrate(x)`` syntax is meant only for convenience
in interactive sessions and should be avoided in library code.
>>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
Piecewise((gamma(a + 1), re(a) > -1),
(Integral(x**a*exp(-x), (x, 0, oo)), True))
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
gamma(a + 1)
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
(gamma(a + 1), -re(a) < 1)
See Also
========
Integral, Integral.doit
"""
doit_flags = {
'deep': False,
'meijerg': meijerg,
'conds': conds,
'risch': risch,
'heurisch': heurisch,
'manual': manual
}
integral = Integral(*args, **kwargs)
if isinstance(integral, Integral):
return integral.doit(**doit_flags)
else:
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
for a in integral.args]
return integral.func(*new_args)
def line_integrate(field, curve, vars):
"""line_integrate(field, Curve, variables)
Compute the line integral.
Examples
========
>>> from sympy import Curve, line_integrate, E, ln
>>> from sympy.abc import x, y, t
>>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
>>> line_integrate(x + y, C, [x, y])
3*sqrt(2)
See Also
========
sympy.integrals.integrals.integrate, Integral
"""
from sympy.geometry import Curve
F = sympify(field)
if not F:
raise ValueError(
"Expecting function specifying field as first argument.")
if not isinstance(curve, Curve):
raise ValueError("Expecting Curve entity as second argument.")
if not is_sequence(vars):
raise ValueError("Expecting ordered iterable for variables.")
if len(curve.functions) != len(vars):
raise ValueError("Field variable size does not match curve dimension.")
if curve.parameter in vars:
raise ValueError("Curve parameter clashes with field parameters.")
# Calculate derivatives for line parameter functions
# F(r) -> F(r(t)) and finally F(r(t)*r'(t))
Ft = F
dldt = 0
for i, var in enumerate(vars):
_f = curve.functions[i]
_dn = diff(_f, curve.parameter)
# ...arc length
dldt = dldt + (_dn * _dn)
Ft = Ft.subs(var, _f)
Ft = Ft * sqrt(dldt)
integral = Integral(Ft, curve.limits).doit(deep=False)
return integral
### Property function dispatching ###
@shape.register(Integral)
def _(expr):
return shape(expr.function)
|
866153a25bc3e2a2bd7eb56cc8684a3a6111b74fe26fe0c0f9b0198c82d74d02 | """Base class for all the objects in SymPy"""
from collections import defaultdict
from collections.abc import Mapping
from itertools import chain, zip_longest
from .assumptions import BasicMeta, ManagedProperties
from .cache import cacheit
from .sympify import _sympify, sympify, SympifyError
from .compatibility import iterable, ordered
from .singleton import S
from .kind import UndefinedKind
from ._print_helpers import Printable
from inspect import getmro
def as_Basic(expr):
"""Return expr as a Basic instance using strict sympify
or raise a TypeError; this is just a wrapper to _sympify,
raising a TypeError instead of a SympifyError."""
from sympy.utilities.misc import func_name
try:
return _sympify(expr)
except SympifyError:
raise TypeError(
'Argument must be a Basic object, not `%s`' % func_name(
expr))
class Basic(Printable, metaclass=ManagedProperties):
"""
Base class for all SymPy objects.
Notes and conventions
=====================
1) Always use ``.args``, when accessing parameters of some instance:
>>> from sympy import cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
2) Never use internal methods or variables (the ones prefixed with ``_``):
>>> cot(x)._args # do not use this, use cot(x).args instead
(x,)
3) By "SymPy object" we mean something that can be returned by
``sympify``. But not all objects one encounters using SymPy are
subclasses of Basic. For example, mutable objects are not:
>>> from sympy import Basic, Matrix, sympify
>>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
>>> isinstance(A, Basic)
False
>>> B = sympify(A)
>>> isinstance(B, Basic)
True
"""
__slots__ = ('_mhash', # hash value
'_args', # arguments
'_assumptions'
)
# To be overridden with True in the appropriate subclasses
is_number = False
is_Atom = False
is_Symbol = False
is_symbol = False
is_Indexed = False
is_Dummy = False
is_Wild = False
is_Function = False
is_Add = False
is_Mul = False
is_Pow = False
is_Number = False
is_Float = False
is_Rational = False
is_Integer = False
is_NumberSymbol = False
is_Order = False
is_Derivative = False
is_Piecewise = False
is_Poly = False
is_AlgebraicNumber = False
is_Relational = False
is_Equality = False
is_Boolean = False
is_Not = False
is_Matrix = False
is_Vector = False
is_Point = False
is_MatAdd = False
is_MatMul = False
kind = UndefinedKind
def __new__(cls, *args):
obj = object.__new__(cls)
obj._assumptions = cls.default_assumptions
obj._mhash = None # will be set by __hash__ method.
obj._args = args # all items in args must be Basic objects
return obj
def copy(self):
return self.func(*self.args)
def __reduce_ex__(self, proto):
""" Pickling support."""
return type(self), self.__getnewargs__(), self.__getstate__()
def __getnewargs__(self):
return self.args
def __getstate__(self):
return {}
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
def __hash__(self):
# hash cannot be cached using cache_it because infinite recurrence
# occurs as hash is needed for setting cache dictionary keys
h = self._mhash
if h is None:
h = hash((type(self).__name__,) + self._hashable_content())
self._mhash = h
return h
def _hashable_content(self):
"""Return a tuple of information about self that can be used to
compute the hash. If a class defines additional attributes,
like ``name`` in Symbol, then this method should be updated
accordingly to return such relevant attributes.
Defining more than _hashable_content is necessary if __eq__ has
been defined by a class. See note about this in Basic.__eq__."""
return self._args
@property
def assumptions0(self):
"""
Return object `type` assumptions.
For example:
Symbol('x', real=True)
Symbol('x', integer=True)
are different objects. In other words, besides Python type (Symbol in
this case), the initial assumptions are also forming their typeinfo.
Examples
========
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'extended_negative': False,
'extended_nonnegative': True, 'extended_nonpositive': False,
'extended_nonzero': True, 'extended_positive': True, 'extended_real':
True, 'finite': True, 'hermitian': True, 'imaginary': False,
'infinite': False, 'negative': False, 'nonnegative': True,
'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
True, 'zero': False}
"""
return {}
def compare(self, other):
"""
Return -1, 0, 1 if the object is smaller, equal, or greater than other.
Not in the mathematical sense. If the object is of a different type
from the "other" then their classes are ordered according to
the sorted_classes list.
Examples
========
>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
"""
# all redefinitions of __cmp__ method should start with the
# following lines:
if self is other:
return 0
n1 = self.__class__
n2 = other.__class__
c = (n1 > n2) - (n1 < n2)
if c:
return c
#
st = self._hashable_content()
ot = other._hashable_content()
c = (len(st) > len(ot)) - (len(st) < len(ot))
if c:
return c
for l, r in zip(st, ot):
l = Basic(*l) if isinstance(l, frozenset) else l
r = Basic(*r) if isinstance(r, frozenset) else r
if isinstance(l, Basic):
c = l.compare(r)
else:
c = (l > r) - (l < r)
if c:
return c
return 0
@staticmethod
def _compare_pretty(a, b):
from sympy.series.order import Order
if isinstance(a, Order) and not isinstance(b, Order):
return 1
if not isinstance(a, Order) and isinstance(b, Order):
return -1
if a.is_Rational and b.is_Rational:
l = a.p * b.q
r = b.p * a.q
return (l > r) - (l < r)
else:
from sympy.core.symbol import Wild
p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
r_a = a.match(p1 * p2**p3)
if r_a and p3 in r_a:
a3 = r_a[p3]
r_b = b.match(p1 * p2**p3)
if r_b and p3 in r_b:
b3 = r_b[p3]
c = Basic.compare(a3, b3)
if c != 0:
return c
return Basic.compare(a, b)
@classmethod
def fromiter(cls, args, **assumptions):
"""
Create a new object from an iterable.
This is a convenience function that allows one to create objects from
any iterable, without having to convert to a list or tuple first.
Examples
========
>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in range(5))
(0, 1, 2, 3, 4)
"""
return cls(*tuple(args), **assumptions)
@classmethod
def class_key(cls):
"""Nice order of classes. """
return 5, 0, cls.__name__
@cacheit
def sort_key(self, order=None):
"""
Return a sort key.
Examples
========
>>> from sympy.core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
"""
# XXX: remove this when issue 5169 is fixed
def inner_key(arg):
if isinstance(arg, Basic):
return arg.sort_key(order)
else:
return arg
args = self._sorted_args
args = len(args), tuple([inner_key(arg) for arg in args])
return self.class_key(), args, S.One.sort_key(), S.One
def __eq__(self, other):
"""Return a boolean indicating whether a == b on the basis of
their symbolic trees.
This is the same as a.compare(b) == 0 but faster.
Notes
=====
If a class that overrides __eq__() needs to retain the
implementation of __hash__() from a parent class, the
interpreter must be told this explicitly by setting __hash__ =
<ParentClass>.__hash__. Otherwise the inheritance of __hash__()
will be blocked, just as if __hash__ had been explicitly set to
None.
References
==========
from http://docs.python.org/dev/reference/datamodel.html#object.__hash__
"""
if self is other:
return True
tself = type(self)
tother = type(other)
if tself is not tother:
try:
other = _sympify(other)
tother = type(other)
except SympifyError:
return NotImplemented
# As long as we have the ordering of classes (sympy.core),
# comparing types will be slow in Python 2, because it uses
# __cmp__. Until we can remove it
# (https://github.com/sympy/sympy/issues/4269), we only compare
# types in Python 2 directly if they actually have __ne__.
if type(tself).__ne__ is not type.__ne__:
if tself != tother:
return False
elif tself is not tother:
return False
return self._hashable_content() == other._hashable_content()
def __ne__(self, other):
"""``a != b`` -> Compare two symbolic trees and see whether they are different
this is the same as:
``a.compare(b) != 0``
but faster
"""
return not self == other
def dummy_eq(self, other, symbol=None):
"""
Compare two expressions and handle dummy symbols.
Examples
========
>>> from sympy import Dummy
>>> from sympy.abc import x, y
>>> u = Dummy('u')
>>> (u**2 + 1).dummy_eq(x**2 + 1)
True
>>> (u**2 + 1) == (x**2 + 1)
False
>>> (u**2 + y).dummy_eq(x**2 + y, x)
True
>>> (u**2 + y).dummy_eq(x**2 + y, y)
False
"""
s = self.as_dummy()
o = _sympify(other)
o = o.as_dummy()
dummy_symbols = [i for i in s.free_symbols if i.is_Dummy]
if len(dummy_symbols) == 1:
dummy = dummy_symbols.pop()
else:
return s == o
if symbol is None:
symbols = o.free_symbols
if len(symbols) == 1:
symbol = symbols.pop()
else:
return s == o
tmp = dummy.__class__()
return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp})
def atoms(self, *types):
"""Returns the atoms that form the current object.
By default, only objects that are truly atomic and can't
be divided into smaller pieces are returned: symbols, numbers,
and number symbols like I and pi. It is possible to request
atoms of any type, however, as demonstrated below.
Examples
========
>>> from sympy import I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
{1, 2, I, pi, x, y}
If one or more types are given, the results will contain only
those types of atoms.
>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
{x, y}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
{1, 2}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
{1, 2, pi}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
{1, 2, I, pi}
Note that I (imaginary unit) and zoo (complex infinity) are special
types of number symbols and are not part of the NumberSymbol class.
The type can be given implicitly, too:
>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
{x, y}
Be careful to check your assumptions when using the implicit option
since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
of sympy atom, while ``type(S(2))`` is type ``Integer`` and will find all
integers in an expression:
>>> from sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
{1}
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
{1, 2}
Finally, arguments to atoms() can select more than atomic atoms: any
sympy type (loaded in core/__init__.py) can be listed as an argument
and those types of "atoms" as found in scanning the arguments of the
expression recursively:
>>> from sympy import Function, Mul
>>> from sympy.core.function import AppliedUndef
>>> f = Function('f')
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
{f(x), sin(y + I*pi)}
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
{f(x)}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
{I*pi, 2*sin(y + I*pi)}
"""
if types:
types = tuple(
[t if isinstance(t, type) else type(t) for t in types])
nodes = preorder_traversal(self)
if types:
result = {node for node in nodes if isinstance(node, types)}
else:
result = {node for node in nodes if not node.args}
return result
@property
def free_symbols(self):
"""Return from the atoms of self those which are free symbols.
For most expressions, all symbols are free symbols. For some classes
this is not true. e.g. Integrals use Symbols for the dummy variables
which are bound variables, so Integral has a method to return all
symbols except those. Derivative keeps track of symbols with respect
to which it will perform a derivative; those are
bound variables, too, so it has its own free_symbols method.
Any other method that uses bound variables should implement a
free_symbols method."""
return set().union(*[a.free_symbols for a in self.args])
@property
def expr_free_symbols(self):
return set()
def as_dummy(self):
"""Return the expression with any objects having structurally
bound symbols replaced with unique, canonical symbols within
the object in which they appear and having only the default
assumption for commutativity being True. When applied to a
symbol a new symbol having only the same commutativity will be
returned.
Examples
========
>>> from sympy import Integral, Symbol
>>> from sympy.abc import x
>>> r = Symbol('r', real=True)
>>> Integral(r, (r, x)).as_dummy()
Integral(_0, (_0, x))
>>> _.variables[0].is_real is None
True
>>> r.as_dummy()
_r
Notes
=====
Any object that has structurally bound variables should have
a property, `bound_symbols` that returns those symbols
appearing in the object.
"""
from sympy.core.symbol import Dummy, Symbol
def can(x):
# mask free that shadow bound
free = x.free_symbols
bound = set(x.bound_symbols)
d = {i: Dummy() for i in bound & free}
x = x.subs(d)
# replace bound with canonical names
x = x.xreplace(x.canonical_variables)
# return after undoing masking
return x.xreplace({v: k for k, v in d.items()})
if not self.has(Symbol):
return self
return self.replace(
lambda x: hasattr(x, 'bound_symbols'),
lambda x: can(x),
simultaneous=False)
@property
def canonical_variables(self):
"""Return a dictionary mapping any variable defined in
``self.bound_symbols`` to Symbols that do not clash
with any free symbols in the expression.
Examples
========
>>> from sympy import Lambda
>>> from sympy.abc import x
>>> Lambda(x, 2*x).canonical_variables
{x: _0}
"""
from sympy.utilities.iterables import numbered_symbols
if not hasattr(self, 'bound_symbols'):
return {}
dums = numbered_symbols('_')
reps = {}
# watch out for free symbol that are not in bound symbols;
# those that are in bound symbols are about to get changed
bound = self.bound_symbols
names = {i.name for i in self.free_symbols - set(bound)}
for b in bound:
d = next(dums)
if b.is_Symbol:
while d.name in names:
d = next(dums)
reps[b] = d
return reps
def rcall(self, *args):
"""Apply on the argument recursively through the expression tree.
This method is used to simulate a common abuse of notation for
operators. For instance in SymPy the the following will not work:
``(x+Lambda(y, 2*y))(z) == x+2*z``,
however you can use
>>> from sympy import Lambda
>>> from sympy.abc import x, y, z
>>> (x + Lambda(y, 2*y)).rcall(z)
x + 2*z
"""
return Basic._recursive_call(self, args)
@staticmethod
def _recursive_call(expr_to_call, on_args):
"""Helper for rcall method."""
from sympy import Symbol
def the_call_method_is_overridden(expr):
for cls in getmro(type(expr)):
if '__call__' in cls.__dict__:
return cls != Basic
if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call):
if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is
return expr_to_call # transformed into an UndefFunction
else:
return expr_to_call(*on_args)
elif expr_to_call.args:
args = [Basic._recursive_call(
sub, on_args) for sub in expr_to_call.args]
return type(expr_to_call)(*args)
else:
return expr_to_call
def is_hypergeometric(self, k):
from sympy.simplify import hypersimp
from sympy.functions import Piecewise
if self.has(Piecewise):
return None
return hypersimp(self, k) is not None
@property
def is_comparable(self):
"""Return True if self can be computed to a real number
(or already is a real number) with precision, else False.
Examples
========
>>> from sympy import exp_polar, pi, I
>>> (I*exp_polar(I*pi/2)).is_comparable
True
>>> (I*exp_polar(I*pi*2)).is_comparable
False
A False result does not mean that `self` cannot be rewritten
into a form that would be comparable. For example, the
difference computed below is zero but without simplification
it does not evaluate to a zero with precision:
>>> e = 2**pi*(1 + 2**pi)
>>> dif = e - e.expand()
>>> dif.is_comparable
False
>>> dif.n(2)._prec
1
"""
is_extended_real = self.is_extended_real
if is_extended_real is False:
return False
if not self.is_number:
return False
# don't re-eval numbers that are already evaluated since
# this will create spurious precision
n, i = [p.evalf(2) if not p.is_Number else p
for p in self.as_real_imag()]
if not (i.is_Number and n.is_Number):
return False
if i:
# if _prec = 1 we can't decide and if not,
# the answer is False because numbers with
# imaginary parts can't be compared
# so return False
return False
else:
return n._prec != 1
@property
def func(self):
"""
The top-level function in an expression.
The following should hold for all objects::
>> x == x.func(*x.args)
Examples
========
>>> from sympy.abc import x
>>> a = 2*x
>>> a.func
<class 'sympy.core.mul.Mul'>
>>> a.args
(2, x)
>>> a.func(*a.args)
2*x
>>> a == a.func(*a.args)
True
"""
return self.__class__
@property
def args(self):
"""Returns a tuple of arguments of 'self'.
Examples
========
>>> from sympy import cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Notes
=====
Never use self._args, always use self.args.
Only use _args in __new__ when creating a new function.
Don't override .args() from Basic (so that it's easy to
change the interface in the future if needed).
"""
return self._args
@property
def _sorted_args(self):
"""
The same as ``args``. Derived classes which don't fix an
order on their arguments should override this method to
produce the sorted representation.
"""
return self.args
def as_content_primitive(self, radical=False, clear=True):
"""A stub to allow Basic args (like Tuple) to be skipped when computing
the content and primitive components of an expression.
See Also
========
sympy.core.expr.Expr.as_content_primitive
"""
return S.One, self
def subs(self, *args, **kwargs):
"""
Substitutes old for new in an expression after sympifying args.
`args` is either:
- two arguments, e.g. foo.subs(old, new)
- one iterable argument, e.g. foo.subs(iterable). The iterable may be
o an iterable container with (old, new) pairs. In this case the
replacements are processed in the order given with successive
patterns possibly affecting replacements already made.
o a dict or set whose key/value items correspond to old/new pairs.
In this case the old/new pairs will be sorted by op count and in
case of a tie, by number of args and the default_sort_key. The
resulting sorted list is then processed as an iterable container
(see previous).
If the keyword ``simultaneous`` is True, the subexpressions will not be
evaluated until all the substitutions have been made.
Examples
========
>>> from sympy import pi, exp, limit, oo
>>> from sympy.abc import x, y
>>> (1 + x*y).subs(x, pi)
pi*y + 1
>>> (1 + x*y).subs({x:pi, y:2})
1 + 2*pi
>>> (1 + x*y).subs([(x, pi), (y, 2)])
1 + 2*pi
>>> reps = [(y, x**2), (x, 2)]
>>> (x + y).subs(reps)
6
>>> (x + y).subs(reversed(reps))
x**2 + 2
>>> (x**2 + x**4).subs(x**2, y)
y**2 + y
To replace only the x**2 but not the x**4, use xreplace:
>>> (x**2 + x**4).xreplace({x**2: y})
x**4 + y
To delay evaluation until all substitutions have been made,
set the keyword ``simultaneous`` to True:
>>> (x/y).subs([(x, 0), (y, 0)])
0
>>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
nan
This has the added feature of not allowing subsequent substitutions
to affect those already made:
>>> ((x + y)/y).subs({x + y: y, y: x + y})
1
>>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
y/(x + y)
In order to obtain a canonical result, unordered iterables are
sorted by count_op length, number of arguments and by the
default_sort_key to break any ties. All other iterables are left
unsorted.
>>> from sympy import sqrt, sin, cos
>>> from sympy.abc import a, b, c, d, e
>>> A = (sqrt(sin(2*x)), a)
>>> B = (sin(2*x), b)
>>> C = (cos(2*x), c)
>>> D = (x, d)
>>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs(dict([A, B, C, D, E]))
a*c*sin(d*e) + b
The resulting expression represents a literal replacement of the
old arguments with the new arguments. This may not reflect the
limiting behavior of the expression:
>>> (x**3 - 3*x).subs({x: oo})
nan
>>> limit(x**3 - 3*x, x, oo)
oo
If the substitution will be followed by numerical
evaluation, it is better to pass the substitution to
evalf as
>>> (1/x).evalf(subs={x: 3.0}, n=21)
0.333333333333333333333
rather than
>>> (1/x).subs({x: 3.0}).evalf(21)
0.333333333333333314830
as the former will ensure that the desired level of precision is
obtained.
See Also
========
replace: replacement capable of doing wildcard-like matching,
parsing of match, and conditional replacements
xreplace: exact node replacement in expr tree; also capable of
using matching rules
sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision
"""
from sympy.core.compatibility import _nodes, default_sort_key
from sympy.core.containers import Dict
from sympy.core.symbol import Dummy, Symbol
from sympy.utilities.misc import filldedent
unordered = False
if len(args) == 1:
sequence = args[0]
if isinstance(sequence, set):
unordered = True
elif isinstance(sequence, (Dict, Mapping)):
unordered = True
sequence = sequence.items()
elif not iterable(sequence):
raise ValueError(filldedent("""
When a single argument is passed to subs
it should be a dictionary of old: new pairs or an iterable
of (old, new) tuples."""))
elif len(args) == 2:
sequence = [args]
else:
raise ValueError("subs accepts either 1 or 2 arguments")
sequence = list(sequence)
for i, s in enumerate(sequence):
if isinstance(s[0], str):
# when old is a string we prefer Symbol
s = Symbol(s[0]), s[1]
try:
s = [sympify(_, strict=not isinstance(_, (str, type)))
for _ in s]
except SympifyError:
# if it can't be sympified, skip it
sequence[i] = None
continue
# skip if there is no change
sequence[i] = None if _aresame(*s) else tuple(s)
sequence = list(filter(None, sequence))
if unordered:
sequence = dict(sequence)
# order so more complex items are first and items
# of identical complexity are ordered so
# f(x) < f(y) < x < y
# \___ 2 __/ \_1_/ <- number of nodes
#
# For more complex ordering use an unordered sequence.
k = list(ordered(sequence, default=False, keys=(
lambda x: -_nodes(x),
lambda x: default_sort_key(x),
)))
sequence = [(k, sequence[k]) for k in k]
if kwargs.pop('simultaneous', False): # XXX should this be the default for dict subs?
reps = {}
rv = self
kwargs['hack2'] = True
m = Dummy('subs_m')
for old, new in sequence:
com = new.is_commutative
if com is None:
com = True
d = Dummy('subs_d', commutative=com)
# using d*m so Subs will be used on dummy variables
# in things like Derivative(f(x, y), x) in which x
# is both free and bound
rv = rv._subs(old, d*m, **kwargs)
if not isinstance(rv, Basic):
break
reps[d] = new
reps[m] = S.One # get rid of m
return rv.xreplace(reps)
else:
rv = self
for old, new in sequence:
rv = rv._subs(old, new, **kwargs)
if not isinstance(rv, Basic):
break
return rv
@cacheit
def _subs(self, old, new, **hints):
"""Substitutes an expression old -> new.
If self is not equal to old then _eval_subs is called.
If _eval_subs doesn't want to make any special replacement
then a None is received which indicates that the fallback
should be applied wherein a search for replacements is made
amongst the arguments of self.
>>> from sympy import Add
>>> from sympy.abc import x, y, z
Examples
========
Add's _eval_subs knows how to target x + y in the following
so it makes the change:
>>> (x + y + z).subs(x + y, 1)
z + 1
Add's _eval_subs doesn't need to know how to find x + y in
the following:
>>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
True
The returned None will cause the fallback routine to traverse the args and
pass the z*(x + y) arg to Mul where the change will take place and the
substitution will succeed:
>>> (z*(x + y) + 3).subs(x + y, 1)
z + 3
** Developers Notes **
An _eval_subs routine for a class should be written if:
1) any arguments are not instances of Basic (e.g. bool, tuple);
2) some arguments should not be targeted (as in integration
variables);
3) if there is something other than a literal replacement
that should be attempted (as in Piecewise where the condition
may be updated without doing a replacement).
If it is overridden, here are some special cases that might arise:
1) If it turns out that no special change was made and all
the original sub-arguments should be checked for
replacements then None should be returned.
2) If it is necessary to do substitutions on a portion of
the expression then _subs should be called. _subs will
handle the case of any sub-expression being equal to old
(which usually would not be the case) while its fallback
will handle the recursion into the sub-arguments. For
example, after Add's _eval_subs removes some matching terms
it must process the remaining terms so it calls _subs
on each of the un-matched terms and then adds them
onto the terms previously obtained.
3) If the initial expression should remain unchanged then
the original expression should be returned. (Whenever an
expression is returned, modified or not, no further
substitution of old -> new is attempted.) Sum's _eval_subs
routine uses this strategy when a substitution is attempted
on any of its summation variables.
"""
def fallback(self, old, new):
"""
Try to replace old with new in any of self's arguments.
"""
hit = False
args = list(self.args)
for i, arg in enumerate(args):
if not hasattr(arg, '_eval_subs'):
continue
arg = arg._subs(old, new, **hints)
if not _aresame(arg, args[i]):
hit = True
args[i] = arg
if hit:
rv = self.func(*args)
hack2 = hints.get('hack2', False)
if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
coeff = S.One
nonnumber = []
for i in args:
if i.is_Number:
coeff *= i
else:
nonnumber.append(i)
nonnumber = self.func(*nonnumber)
if coeff is S.One:
return nonnumber
else:
return self.func(coeff, nonnumber, evaluate=False)
return rv
return self
if _aresame(self, old):
return new
rv = self._eval_subs(old, new)
if rv is None:
rv = fallback(self, old, new)
return rv
def _eval_subs(self, old, new):
"""Override this stub if you want to do anything more than
attempt a replacement of old with new in the arguments of self.
See also
========
_subs
"""
return None
def xreplace(self, rule):
"""
Replace occurrences of objects within the expression.
Parameters
==========
rule : dict-like
Expresses a replacement rule
Returns
=======
xreplace : the result of the replacement
Examples
========
>>> from sympy import symbols, pi, exp
>>> x, y, z = symbols('x y z')
>>> (1 + x*y).xreplace({x: pi})
pi*y + 1
>>> (1 + x*y).xreplace({x: pi, y: 2})
1 + 2*pi
Replacements occur only if an entire node in the expression tree is
matched:
>>> (x*y + z).xreplace({x*y: pi})
z + pi
>>> (x*y*z).xreplace({x*y: pi})
x*y*z
>>> (2*x).xreplace({2*x: y, x: z})
y
>>> (2*2*x).xreplace({2*x: y, x: z})
4*z
>>> (x + y + 2).xreplace({x + y: 2})
x + y + 2
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
x + exp(y) + 2
xreplace doesn't differentiate between free and bound symbols. In the
following, subs(x, y) would not change x since it is a bound symbol,
but xreplace does:
>>> from sympy import Integral
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
Integral(y, (y, 1, 2*y))
Trying to replace x with an expression raises an error:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
ValueError: Invalid limits given: ((2*y, 1, 4*y),)
See Also
========
replace: replacement capable of doing wildcard-like matching,
parsing of match, and conditional replacements
subs: substitution of subexpressions as defined by the objects
themselves.
"""
value, _ = self._xreplace(rule)
return value
def _xreplace(self, rule):
"""
Helper for xreplace. Tracks whether a replacement actually occurred.
"""
if self in rule:
return rule[self], True
elif rule:
args = []
changed = False
for a in self.args:
_xreplace = getattr(a, '_xreplace', None)
if _xreplace is not None:
a_xr = _xreplace(rule)
args.append(a_xr[0])
changed |= a_xr[1]
else:
args.append(a)
args = tuple(args)
if changed:
return self.func(*args), True
return self, False
@cacheit
def has(self, *patterns):
"""
Test whether any subexpression matches any of the patterns.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x, y, z
>>> (x**2 + sin(x*y)).has(z)
False
>>> (x**2 + sin(x*y)).has(x, y, z)
True
>>> x.has(x)
True
Note ``has`` is a structural algorithm with no knowledge of
mathematics. Consider the following half-open interval:
>>> from sympy.sets import Interval
>>> i = Interval.Lopen(0, 5); i
Interval.Lopen(0, 5)
>>> i.args
(0, 5, True, False)
>>> i.has(4) # there is no "4" in the arguments
False
>>> i.has(0) # there *is* a "0" in the arguments
True
Instead, use ``contains`` to determine whether a number is in the
interval or not:
>>> i.contains(4)
True
>>> i.contains(0)
False
Note that ``expr.has(*patterns)`` is exactly equivalent to
``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
returned when the list of patterns is empty.
>>> x.has()
False
"""
return any(self._has(pattern) for pattern in patterns)
def _has(self, pattern):
"""Helper for .has()"""
from sympy.core.function import UndefinedFunction, Function
if isinstance(pattern, UndefinedFunction):
return any(f.func == pattern or f == pattern
for f in self.atoms(Function, UndefinedFunction))
if isinstance(pattern, BasicMeta):
subtrees = preorder_traversal(self)
return any(isinstance(arg, pattern) for arg in subtrees)
pattern = _sympify(pattern)
_has_matcher = getattr(pattern, '_has_matcher', None)
if _has_matcher is not None:
match = _has_matcher()
return any(match(arg) for arg in preorder_traversal(self))
else:
return any(arg == pattern for arg in preorder_traversal(self))
def _has_matcher(self):
"""Helper for .has()"""
return lambda other: self == other
def replace(self, query, value, map=False, simultaneous=True, exact=None):
"""
Replace matching subexpressions of ``self`` with ``value``.
If ``map = True`` then also return the mapping {old: new} where ``old``
was a sub-expression found with query and ``new`` is the replacement
value for it. If the expression itself doesn't match the query, then
the returned value will be ``self.xreplace(map)`` otherwise it should
be ``self.subs(ordered(map.items()))``.
Traverses an expression tree and performs replacement of matching
subexpressions from the bottom to the top of the tree. The default
approach is to do the replacement in a simultaneous fashion so
changes made are targeted only once. If this is not desired or causes
problems, ``simultaneous`` can be set to False.
In addition, if an expression containing more than one Wild symbol
is being used to match subexpressions and the ``exact`` flag is None
it will be set to True so the match will only succeed if all non-zero
values are received for each Wild that appears in the match pattern.
Setting this to False accepts a match of 0; while setting it True
accepts all matches that have a 0 in them. See example below for
cautions.
The list of possible combinations of queries and replacement values
is listed below:
Examples
========
Initial setup
>>> from sympy import log, sin, cos, tan, Wild, Mul, Add
>>> from sympy.abc import x, y
>>> f = log(sin(x)) + tan(sin(x**2))
1.1. type -> type
obj.replace(type, newtype)
When object of type ``type`` is found, replace it with the
result of passing its argument(s) to ``newtype``.
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> (x*y).replace(Mul, Add)
x + y
1.2. type -> func
obj.replace(type, func)
When object of type ``type`` is found, apply ``func`` to its
argument(s). ``func`` must be written to handle the number
of arguments of ``type``.
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
sin(2*x*y)
2.1. pattern -> expr
obj.replace(pattern(wild), expr(wild))
Replace subexpressions matching ``pattern`` with the expression
written in terms of the Wild symbols in ``pattern``.
>>> a, b = map(Wild, 'ab')
>>> f.replace(sin(a), tan(a))
log(tan(x)) + tan(tan(x**2))
>>> f.replace(sin(a), tan(a/2))
log(tan(x/2)) + tan(tan(x**2/2))
>>> f.replace(sin(a), a)
log(x) + tan(x**2)
>>> (x*y).replace(a*x, a)
y
Matching is exact by default when more than one Wild symbol
is used: matching fails unless the match gives non-zero
values for all Wild symbols:
>>> (2*x + y).replace(a*x + b, b - a)
y - 2
>>> (2*x).replace(a*x + b, b - a)
2*x
When set to False, the results may be non-intuitive:
>>> (2*x).replace(a*x + b, b - a, exact=False)
2/x
2.2. pattern -> func
obj.replace(pattern(wild), lambda wild: expr(wild))
All behavior is the same as in 2.1 but now a function in terms of
pattern variables is used rather than an expression:
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
3.1. func -> func
obj.replace(filter, func)
Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
is True.
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
The expression itself is also targeted by the query but is done in
such a fashion that changes are not made twice.
>>> e = x*(x*y + 1)
>>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
2*x*(2*x*y + 1)
When matching a single symbol, `exact` will default to True, but
this may or may not be the behavior that is desired:
Here, we want `exact=False`:
>>> from sympy import Function
>>> f = Function('f')
>>> e = f(1) + f(0)
>>> q = f(a), lambda a: f(a + 1)
>>> e.replace(*q, exact=False)
f(1) + f(2)
>>> e.replace(*q, exact=True)
f(0) + f(2)
But here, the nature of matching makes selecting
the right setting tricky:
>>> e = x**(1 + y)
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
x
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
x**(-x - y + 1)
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
x
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
x**(1 - y)
It is probably better to use a different form of the query
that describes the target expression more precisely:
>>> (1 + x**(1 + y)).replace(
... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
... lambda x: x.base**(1 - (x.exp - 1)))
...
x**(1 - y) + 1
See Also
========
subs: substitution of subexpressions as defined by the objects
themselves.
xreplace: exact node replacement in expr tree; also capable of
using matching rules
"""
from sympy.core.symbol import Wild
try:
query = _sympify(query)
except SympifyError:
pass
try:
value = _sympify(value)
except SympifyError:
pass
if isinstance(query, type):
_query = lambda expr: isinstance(expr, query)
if isinstance(value, type):
_value = lambda expr, result: value(*expr.args)
elif callable(value):
_value = lambda expr, result: value(*expr.args)
else:
raise TypeError(
"given a type, replace() expects another "
"type or a callable")
elif isinstance(query, Basic):
_query = lambda expr: expr.match(query)
if exact is None:
exact = (len(query.atoms(Wild)) > 1)
if isinstance(value, Basic):
if exact:
_value = lambda expr, result: (value.subs(result)
if all(result.values()) else expr)
else:
_value = lambda expr, result: value.subs(result)
elif callable(value):
# match dictionary keys get the trailing underscore stripped
# from them and are then passed as keywords to the callable;
# if ``exact`` is True, only accept match if there are no null
# values amongst those matched.
if exact:
_value = lambda expr, result: (value(**
{str(k)[:-1]: v for k, v in result.items()})
if all(val for val in result.values()) else expr)
else:
_value = lambda expr, result: value(**
{str(k)[:-1]: v for k, v in result.items()})
else:
raise TypeError(
"given an expression, replace() expects "
"another expression or a callable")
elif callable(query):
_query = query
if callable(value):
_value = lambda expr, result: value(expr)
else:
raise TypeError(
"given a callable, replace() expects "
"another callable")
else:
raise TypeError(
"first argument to replace() must be a "
"type, an expression or a callable")
def walk(rv, F):
"""Apply ``F`` to args and then to result.
"""
args = getattr(rv, 'args', None)
if args is not None:
if args:
newargs = tuple([walk(a, F) for a in args])
if args != newargs:
rv = rv.func(*newargs)
if simultaneous:
# if rv is something that was already
# matched (that was changed) then skip
# applying F again
for i, e in enumerate(args):
if rv == e and e != newargs[i]:
return rv
rv = F(rv)
return rv
mapping = {} # changes that took place
def rec_replace(expr):
result = _query(expr)
if result or result == {}:
v = _value(expr, result)
if v is not None and v != expr:
if map:
mapping[expr] = v
expr = v
return expr
rv = walk(self, rec_replace)
return (rv, mapping) if map else rv
def find(self, query, group=False):
"""Find all subexpressions matching a query. """
query = _make_find_query(query)
results = list(filter(query, preorder_traversal(self)))
if not group:
return set(results)
else:
groups = {}
for result in results:
if result in groups:
groups[result] += 1
else:
groups[result] = 1
return groups
def count(self, query):
"""Count the number of matching subexpressions. """
query = _make_find_query(query)
return sum(bool(query(sub)) for sub in preorder_traversal(self))
def matches(self, expr, repl_dict={}, old=False):
"""
Helper method for match() that looks for a match between Wild symbols
in self and expressions in expr.
Examples
========
>>> from sympy import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
"""
repl_dict = repl_dict.copy()
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if self == expr:
return repl_dict
if len(self.args) != len(expr.args):
return None
d = repl_dict.copy()
for arg, other_arg in zip(self.args, expr.args):
if arg == other_arg:
continue
d = arg.xreplace(d).matches(other_arg, d, old=old)
if d is None:
return None
return d
def match(self, pattern, old=False):
"""
Pattern matching.
Wild symbols match all.
Return ``None`` when expression (self) does not match
with pattern. Otherwise return a dictionary such that::
pattern.xreplace(self.match(pattern)) == self
Examples
========
>>> from sympy import Wild, Sum
>>> from sympy.abc import x, y
>>> p = Wild("p")
>>> q = Wild("q")
>>> r = Wild("r")
>>> e = (x+y)**(x+y)
>>> e.match(p**p)
{p_: x + y}
>>> e.match(p**q)
{p_: x + y, q_: x + y}
>>> e = (2*x)**2
>>> e.match(p*q**r)
{p_: 4, q_: x, r_: 2}
>>> (p*q**r).xreplace(e.match(p*q**r))
4*x**2
Structurally bound symbols are ignored during matching:
>>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
{p_: 2}
But they can be identified if desired:
>>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
{p_: 2, q_: x}
The ``old`` flag will give the old-style pattern matching where
expressions and patterns are essentially solved to give the
match. Both of the following give None unless ``old=True``:
>>> (x - 2).match(p - x, old=True)
{p_: 2*x - 2}
>>> (2/x).match(p*x, old=True)
{p_: 2/x**2}
"""
from sympy.core.symbol import Wild
from sympy.core.function import WildFunction
from sympy.utilities.misc import filldedent
pattern = sympify(pattern)
# match non-bound symbols
canonical = lambda x: x if x.is_Symbol else x.as_dummy()
m = canonical(pattern).matches(canonical(self), old=old)
if m is None:
return m
wild = pattern.atoms(Wild, WildFunction)
# sanity check
if set(m) - wild:
raise ValueError(filldedent('''
Some `matches` routine did not use a copy of repl_dict
and injected unexpected symbols. Report this as an
error at https://github.com/sympy/sympy/issues'''))
# now see if bound symbols were requested
bwild = wild - set(m)
if not bwild:
return m
# replace free-Wild symbols in pattern with match result
# so they will match but not be in the next match
wpat = pattern.xreplace(m)
# identify remaining bound wild
w = wpat.matches(self, old=old)
# add them to m
if w:
m.update(w)
# done
return m
def count_ops(self, visual=None):
"""wrapper for count_ops that returns the operation count."""
from sympy import count_ops
return count_ops(self, visual)
def doit(self, **hints):
"""Evaluate objects that are not evaluated by default like limits,
integrals, sums and products. All objects of this kind will be
evaluated recursively, unless some species were excluded via 'hints'
or unless the 'deep' hint was set to 'False'.
>>> from sympy import Integral
>>> from sympy.abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
"""
if hints.get('deep', True):
terms = [term.doit(**hints) if isinstance(term, Basic) else term
for term in self.args]
return self.func(*terms)
else:
return self
def simplify(self, **kwargs):
"""See the simplify function in sympy.simplify"""
from sympy.simplify import simplify
return simplify(self, **kwargs)
def refine(self, assumption=True):
"""See the refine function in sympy.assumptions"""
from sympy.assumptions import refine
return refine(self, assumption)
def _eval_rewrite(self, pattern, rule, **hints):
if self.is_Atom:
if hasattr(self, rule):
return getattr(self, rule)()
return self
if hints.get('deep', True):
args = [a._eval_rewrite(pattern, rule, **hints)
if isinstance(a, Basic) else a
for a in self.args]
else:
args = self.args
if pattern is None or isinstance(self, pattern):
if hasattr(self, rule):
rewritten = getattr(self, rule)(*args, **hints)
if rewritten is not None:
return rewritten
return self.func(*args) if hints.get('evaluate', True) else self
def _eval_derivative_n_times(self, s, n):
# This is the default evaluator for derivatives (as called by `diff`
# and `Derivative`), it will attempt a loop to derive the expression
# `n` times by calling the corresponding `_eval_derivative` method,
# while leaving the derivative unevaluated if `n` is symbolic. This
# method should be overridden if the object has a closed form for its
# symbolic n-th derivative.
from sympy import Integer
if isinstance(n, (int, Integer)):
obj = self
for i in range(n):
obj2 = obj._eval_derivative(s)
if obj == obj2 or obj2 is None:
break
obj = obj2
return obj2
else:
return None
def rewrite(self, *args, **hints):
""" Rewrite functions in terms of other functions.
Rewrites expression containing applications of functions
of one kind in terms of functions of different kind. For
example you can rewrite trigonometric functions as complex
exponentials or combinatorial functions as gamma function.
As a pattern this function accepts a list of functions to
to rewrite (instances of DefinedFunction class). As rule
you can use string or a destination function instance (in
this case rewrite() will use the str() function).
There is also the possibility to pass hints on how to rewrite
the given expressions. For now there is only one such hint
defined called 'deep'. When 'deep' is set to False it will
forbid functions to rewrite their contents.
Examples
========
>>> from sympy import sin, exp
>>> from sympy.abc import x
Unspecified pattern:
>>> sin(x).rewrite(exp)
-I*(exp(I*x) - exp(-I*x))/2
Pattern as a single function:
>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2
Pattern as a list of functions:
>>> sin(x).rewrite([sin, ], exp)
-I*(exp(I*x) - exp(-I*x))/2
"""
if not args:
return self
else:
pattern = args[:-1]
if isinstance(args[-1], str):
rule = '_eval_rewrite_as_' + args[-1]
else:
# rewrite arg is usually a class but can also be a
# singleton (e.g. GoldenRatio) so we check
# __name__ or __class__.__name__
clsname = getattr(args[-1], "__name__", None)
if clsname is None:
clsname = args[-1].__class__.__name__
rule = '_eval_rewrite_as_' + clsname
if not pattern:
return self._eval_rewrite(None, rule, **hints)
else:
if iterable(pattern[0]):
pattern = pattern[0]
pattern = [p for p in pattern if self.has(p)]
if pattern:
return self._eval_rewrite(tuple(pattern), rule, **hints)
else:
return self
_constructor_postprocessor_mapping = {} # type: ignore
@classmethod
def _exec_constructor_postprocessors(cls, obj):
# WARNING: This API is experimental.
# This is an experimental API that introduces constructor
# postprosessors for SymPy Core elements. If an argument of a SymPy
# expression has a `_constructor_postprocessor_mapping` attribute, it will
# be interpreted as a dictionary containing lists of postprocessing
# functions for matching expression node names.
clsname = obj.__class__.__name__
postprocessors = defaultdict(list)
for i in obj.args:
try:
postprocessor_mappings = (
Basic._constructor_postprocessor_mapping[cls].items()
for cls in type(i).mro()
if cls in Basic._constructor_postprocessor_mapping
)
for k, v in chain.from_iterable(postprocessor_mappings):
postprocessors[k].extend([j for j in v if j not in postprocessors[k]])
except TypeError:
pass
for f in postprocessors.get(clsname, []):
obj = f(obj)
return obj
class Atom(Basic):
"""
A parent class for atomic things. An atom is an expression with no subexpressions.
Examples
========
Symbol, Number, Rational, Integer, ...
But not: Add, Mul, Pow, ...
"""
is_Atom = True
__slots__ = ()
def matches(self, expr, repl_dict={}, old=False):
if self == expr:
return repl_dict.copy()
def xreplace(self, rule, hack2=False):
return rule.get(self, self)
def doit(self, **hints):
return self
@classmethod
def class_key(cls):
return 2, 0, cls.__name__
@cacheit
def sort_key(self, order=None):
return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One
def _eval_simplify(self, **kwargs):
return self
@property
def _sorted_args(self):
# this is here as a safeguard against accidentally using _sorted_args
# on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args)
# since there are no args. So the calling routine should be checking
# to see that this property is not called for Atoms.
raise AttributeError('Atoms have no args. It might be necessary'
' to make a check for Atoms in the calling code.')
def _aresame(a, b):
"""Return True if a and b are structurally the same, else False.
Examples
========
In SymPy (as in Python) two numbers compare the same if they
have the same underlying base-2 representation even though
they may not be the same type:
>>> from sympy import S
>>> 2.0 == S(2)
True
>>> 0.5 == S.Half
True
This routine was written to provide a query for such cases that
would give false when the types do not match:
>>> from sympy.core.basic import _aresame
>>> _aresame(S(2.0), S(2))
False
"""
from .numbers import Number
from .function import AppliedUndef, UndefinedFunction as UndefFunc
if isinstance(a, Number) and isinstance(b, Number):
return a == b and a.__class__ == b.__class__
for i, j in zip_longest(preorder_traversal(a), preorder_traversal(b)):
if i != j or type(i) != type(j):
if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or
(isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))):
if i.class_key() != j.class_key():
return False
else:
return False
return True
def _atomic(e, recursive=False):
"""Return atom-like quantities as far as substitution is
concerned: Derivatives, Functions and Symbols. Don't
return any 'atoms' that are inside such quantities unless
they also appear outside, too, unless `recursive` is True.
Examples
========
>>> from sympy import Derivative, Function, cos
>>> from sympy.abc import x, y
>>> from sympy.core.basic import _atomic
>>> f = Function('f')
>>> _atomic(x + y)
{x, y}
>>> _atomic(x + f(y))
{x, f(y)}
>>> _atomic(Derivative(f(x), x) + cos(x) + y)
{y, cos(x), Derivative(f(x), x)}
"""
from sympy import Derivative, Function, Symbol
pot = preorder_traversal(e)
seen = set()
if isinstance(e, Basic):
free = getattr(e, "free_symbols", None)
if free is None:
return {e}
else:
return set()
atoms = set()
for p in pot:
if p in seen:
pot.skip()
continue
seen.add(p)
if isinstance(p, Symbol) and p in free:
atoms.add(p)
elif isinstance(p, (Derivative, Function)):
if not recursive:
pot.skip()
atoms.add(p)
return atoms
class preorder_traversal:
"""
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a pre-order
fashion. That is, it yields the current node then descends through the
tree breadth-first to yield all of a node's children's pre-order
traversal.
For an expression, the order of the traversal depends on the order of
.args, which in many cases can be arbitrary.
Parameters
==========
node : sympy expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic
objects are processed in arbitrary order. If key is defined, it will
be passed along to ordered() as the only key(s) to use to sort the
arguments; if ``key`` is simply True then the default keys of ordered
will be used.
Yields
======
subtree : sympy expression
All of the subtrees in the tree.
Examples
========
>>> from sympy import symbols
>>> from sympy.core.basic import preorder_traversal
>>> x, y, z = symbols('x y z')
The nodes are returned in the order that they are encountered unless key
is given; simply passing key=True will guarantee that the traversal is
unique.
>>> list(preorder_traversal((x + y)*z, keys=None)) # doctest: +SKIP
[z*(x + y), z, x + y, y, x]
>>> list(preorder_traversal((x + y)*z, keys=True))
[z*(x + y), z, x + y, x, y]
"""
def __init__(self, node, keys=None):
self._skip_flag = False
self._pt = self._preorder_traversal(node, keys)
def _preorder_traversal(self, node, keys):
yield node
if self._skip_flag:
self._skip_flag = False
return
if isinstance(node, Basic):
if not keys and hasattr(node, '_argset'):
# LatticeOp keeps args as a set. We should use this if we
# don't care about the order, to prevent unnecessary sorting.
args = node._argset
else:
args = node.args
if keys:
if keys != True:
args = ordered(args, keys, default=False)
else:
args = ordered(args)
for arg in args:
yield from self._preorder_traversal(arg, keys)
elif iterable(node):
for item in node:
yield from self._preorder_traversal(item, keys)
def skip(self):
"""
Skip yielding current node's (last yielded node's) subtrees.
Examples
========
>>> from sympy.core import symbols
>>> from sympy.core.basic import preorder_traversal
>>> x, y, z = symbols('x y z')
>>> pt = preorder_traversal((x+y*z)*z)
>>> for i in pt:
... print(i)
... if i == x+y*z:
... pt.skip()
z*(x + y*z)
z
x + y*z
"""
self._skip_flag = True
def __next__(self):
return next(self._pt)
def __iter__(self):
return self
def _make_find_query(query):
"""Convert the argument of Basic.find() into a callable"""
try:
query = _sympify(query)
except SympifyError:
pass
if isinstance(query, type):
return lambda expr: isinstance(expr, query)
elif isinstance(query, Basic):
return lambda expr: expr.match(query) is not None
return query
|
84a0a40f245e5e359092663d2e43e932085ba595a561f18f91e38041ed6824de | from math import log as _log
from .sympify import _sympify
from .cache import cacheit
from .singleton import S
from .expr import Expr
from .evalf import PrecisionExhausted
from .function import (_coeff_isneg, expand_complex, expand_multinomial,
expand_mul)
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and
from .compatibility import as_int, HAS_GMPY, gmpy
from .parameters import global_parameters
from sympy.utilities.iterables import sift
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.multipledispatch import Dispatcher
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
from math import sqrt as _sqrt
def isqrt(n):
"""Return the largest integer less than or equal to sqrt(n)."""
if n < 0:
raise ValueError("n must be nonnegative")
n = int(n)
# Fast path: with IEEE 754 binary64 floats and a correctly-rounded
# math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
# 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
# IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
# answer and fall back to the slow method if necessary.
if n < 4503599761588224:
s = int(_sqrt(n))
if 0 <= n - s*s <= 2*s:
return s
return integer_nthroot(n, 2)[0]
def integer_nthroot(y, n):
"""
Return a tuple containing x = floor(y**(1/n))
and a boolean indicating whether the result is exact (that is,
whether x**n == y).
Examples
========
>>> from sympy import integer_nthroot
>>> integer_nthroot(16, 2)
(4, True)
>>> integer_nthroot(26, 2)
(5, False)
To simply determine if a number is a perfect square, the is_square
function should be used:
>>> from sympy.ntheory.primetest import is_square
>>> is_square(26)
False
See Also
========
sympy.ntheory.primetest.is_square
integer_log
"""
y, n = as_int(y), as_int(n)
if y < 0:
raise ValueError("y must be nonnegative")
if n < 1:
raise ValueError("n must be positive")
if HAS_GMPY and n < 2**63:
# Currently it works only for n < 2**63, else it produces TypeError
# sympy issue: https://github.com/sympy/sympy/issues/18374
# gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
if HAS_GMPY >= 2:
x, t = gmpy.iroot(y, n)
else:
x, t = gmpy.root(y, n)
return as_int(x), bool(t)
return _integer_nthroot_python(y, n)
def _integer_nthroot_python(y, n):
if y in (0, 1):
return y, True
if n == 1:
return y, True
if n == 2:
x, rem = mpmath_sqrtrem(y)
return int(x), not rem
if n > y:
return 1, False
# Get initial estimate for Newton's method. Care must be taken to
# avoid overflow
try:
guess = int(y**(1./n) + 0.5)
except OverflowError:
exp = _log(y, 2)/n
if exp > 53:
shift = int(exp - 53)
guess = int(2.0**(exp - shift) + 1) << shift
else:
guess = int(2.0**exp)
if guess > 2**50:
# Newton iteration
xprev, x = -1, guess
while 1:
t = x**(n - 1)
xprev, x = x, ((n - 1)*x + y//t)//n
if abs(x - xprev) < 2:
break
else:
x = guess
# Compensate
t = x**n
while t < y:
x += 1
t = x**n
while t > y:
x -= 1
t = x**n
return int(x), t == y # int converts long to int if possible
def integer_log(y, x):
r"""
Returns ``(e, bool)`` where e is the largest nonnegative integer
such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
Examples
========
>>> from sympy import integer_log
>>> integer_log(125, 5)
(3, True)
>>> integer_log(17, 9)
(1, False)
>>> integer_log(4, -2)
(2, True)
>>> integer_log(-125,-5)
(3, True)
See Also
========
integer_nthroot
sympy.ntheory.primetest.is_square
sympy.ntheory.factor_.multiplicity
sympy.ntheory.factor_.perfect_power
"""
if x == 1:
raise ValueError('x cannot take value as 1')
if y == 0:
raise ValueError('y cannot take value as 0')
if x in (-2, 2):
x = int(x)
y = as_int(y)
e = y.bit_length() - 1
return e, x**e == y
if x < 0:
n, b = integer_log(y if y > 0 else -y, -x)
return n, b and bool(n % 2 if y < 0 else not n % 2)
x = as_int(x)
y = as_int(y)
r = e = 0
while y >= x:
d = x
m = 1
while y >= d:
y, rem = divmod(y, d)
r = r or rem
e += m
if y > d:
d *= d
m *= 2
return e, r == 0 and y == 1
class Pow(Expr):
"""
Defines the expression x**y as "x raised to a power y"
Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
+--------------+---------+-----------------------------------------------+
| expr | value | reason |
+==============+=========+===============================================+
| z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
+--------------+---------+-----------------------------------------------+
| z**1 | z | |
+--------------+---------+-----------------------------------------------+
| (-oo)**(-1) | 0 | |
+--------------+---------+-----------------------------------------------+
| (-1)**-1 | -1 | |
+--------------+---------+-----------------------------------------------+
| S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
| | | undefined, but is convenient in some contexts |
| | | where the base is assumed to be positive. |
+--------------+---------+-----------------------------------------------+
| 1**-1 | 1 | |
+--------------+---------+-----------------------------------------------+
| oo**-1 | 0 | |
+--------------+---------+-----------------------------------------------+
| 0**oo | 0 | Because for all complex numbers z near |
| | | 0, z**oo -> 0. |
+--------------+---------+-----------------------------------------------+
| 0**-oo | zoo | This is not strictly true, as 0**oo may be |
| | | oscillating between positive and negative |
| | | values or rotating in the complex plane. |
| | | It is convenient, however, when the base |
| | | is positive. |
+--------------+---------+-----------------------------------------------+
| 1**oo | nan | Because there are various cases where |
| 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
| | | but lim( x(t)**y(t), t) != 1. See [3]. |
+--------------+---------+-----------------------------------------------+
| b**zoo | nan | Because b**z has no limit as z -> zoo |
+--------------+---------+-----------------------------------------------+
| (-1)**oo | nan | Because of oscillations in the limit. |
| (-1)**(-oo) | | |
+--------------+---------+-----------------------------------------------+
| oo**oo | oo | |
+--------------+---------+-----------------------------------------------+
| oo**-oo | 0 | |
+--------------+---------+-----------------------------------------------+
| (-oo)**oo | nan | |
| (-oo)**-oo | | |
+--------------+---------+-----------------------------------------------+
| oo**I | nan | oo**e could probably be best thought of as |
| (-oo)**I | | the limit of x**e for real x as x tends to |
| | | oo. If e is I, then the limit does not exist |
| | | and nan is used to indicate that. |
+--------------+---------+-----------------------------------------------+
| oo**(1+I) | zoo | If the real part of e is positive, then the |
| (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
| | | is zoo. |
+--------------+---------+-----------------------------------------------+
| oo**(-1+I) | 0 | If the real part of e is negative, then the |
| -oo**(-1+I) | | limit is 0. |
+--------------+---------+-----------------------------------------------+
Because symbolic computations are more flexible that floating point
calculations and we prefer to never return an incorrect answer,
we choose not to conform to all IEEE 754 conventions. This helps
us avoid extra test-case code in the calculation of limits.
See Also
========
sympy.core.numbers.Infinity
sympy.core.numbers.NegativeInfinity
sympy.core.numbers.NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Exponentiation
.. [2] https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero
.. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
"""
is_Pow = True
__slots__ = ('is_commutative',)
@cacheit
def __new__(cls, b, e, evaluate=None):
if evaluate is None:
evaluate = global_parameters.evaluate
from sympy.functions.elementary.exponential import exp_polar
b = _sympify(b)
e = _sympify(e)
# XXX: This can be removed when non-Expr args are disallowed rather
# than deprecated.
from sympy.core.relational import Relational
if isinstance(b, Relational) or isinstance(e, Relational):
raise TypeError('Relational can not be used in Pow')
# XXX: This should raise TypeError once deprecation period is over:
if not (isinstance(b, Expr) and isinstance(e, Expr)):
SymPyDeprecationWarning(
feature="Pow with non-Expr args",
useinstead="Expr args",
issue=19445,
deprecated_since_version="1.7"
).warn()
if evaluate:
if b is S.Zero and e is S.NegativeInfinity:
return S.ComplexInfinity
if e is S.ComplexInfinity:
return S.NaN
if e is S.Zero:
return S.One
elif e is S.One:
return b
elif e == -1 and not b:
return S.ComplexInfinity
# Only perform autosimplification if exponent or base is a Symbol or number
elif (b.is_Symbol or b.is_number) and (e.is_Symbol or e.is_number) and\
e.is_integer and _coeff_isneg(b):
if e.is_even:
b = -b
elif e.is_odd:
return -Pow(-b, e)
if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
return S.NaN
elif b is S.One:
if abs(e).is_infinite:
return S.NaN
return S.One
else:
# recognize base as E
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
from sympy import numer, denom, log, sign, im, factor_terms
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
den = denom(ex)
if isinstance(den, log) and den.args[0] == b:
return S.Exp1**(c*numer(ex))
elif den.is_Add:
s = sign(im(b))
if s.is_Number and s and den == \
log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
return S.Exp1**(c*numer(ex))
obj = b._eval_power(e)
if obj is not None:
return obj
obj = Expr.__new__(cls, b, e)
obj = cls._exec_constructor_postprocessors(obj)
if not isinstance(obj, Pow):
return obj
obj.is_commutative = (b.is_commutative and e.is_commutative)
return obj
@property
def base(self):
return self._args[0]
@property
def exp(self):
return self._args[1]
@classmethod
def class_key(cls):
return 3, 2, cls.__name__
def _eval_refine(self, assumptions):
from sympy.assumptions.ask import ask, Q
b, e = self.as_base_exp()
if ask(Q.integer(e), assumptions) and _coeff_isneg(b):
if ask(Q.even(e), assumptions):
return Pow(-b, e)
elif ask(Q.odd(e), assumptions):
return -Pow(-b, e)
def _eval_power(self, other):
from sympy import arg, exp, floor, im, log, re, sign
b, e = self.as_base_exp()
if b is S.NaN:
return (b**e)**other # let __new__ handle it
s = None
if other.is_integer:
s = 1
elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
s = 1
elif e.is_extended_real is not None:
# helper functions ===========================
def _half(e):
"""Return True if the exponent has a literal 2 as the
denominator, else None."""
if getattr(e, 'q', None) == 2:
return True
n, d = e.as_numer_denom()
if n.is_integer and d == 2:
return True
def _n2(e):
"""Return ``e`` evaluated to a Number with 2 significant
digits, else None."""
try:
rv = e.evalf(2, strict=True)
if rv.is_Number:
return rv
except PrecisionExhausted:
pass
# ===================================================
if e.is_extended_real:
# we need _half(other) with constant floor or
# floor(S.Half - e*arg(b)/2/pi) == 0
# handle -1 as special case
if e == -1:
# floor arg. is 1/2 + arg(b)/2/pi
if _half(other):
if b.is_negative is True:
return S.NegativeOne**other*Pow(-b, e*other)
elif b.is_negative is False:
return Pow(b, -other)
elif e.is_even:
if b.is_extended_real:
b = abs(b)
if b.is_imaginary:
b = abs(im(b))*S.ImaginaryUnit
if (abs(e) < 1) == True or e == 1:
s = 1 # floor = 0
elif b.is_extended_nonnegative:
s = 1 # floor = 0
elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
s = 1 # floor = 0
elif fuzzy_not(im(b).is_zero) and abs(e) == 2:
s = 1 # floor = 0
elif _half(other):
s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
S.Half - e*arg(b)/(2*S.Pi)))
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
else:
# e.is_extended_real is False requires:
# _half(other) with constant floor or
# floor(S.Half - im(e*log(b))/2/pi) == 0
try:
s = exp(2*S.ImaginaryUnit*S.Pi*other*
floor(S.Half - im(e*log(b))/2/S.Pi))
# be careful to test that s is -1 or 1 b/c sign(I) == I:
# so check that s is real
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
except PrecisionExhausted:
s = None
if s is not None:
return s*Pow(b, e*other)
def _eval_Mod(self, q):
r"""A dispatched function to compute `b^e \bmod q`, dispatched
by ``Mod``.
Notes
=====
Algorithms:
1. For unevaluated integer power, use built-in ``pow`` function
with 3 arguments, if powers are not too large wrt base.
2. For very large powers, use totient reduction if e >= lg(m).
Bound on m, is for safe factorization memory wise ie m^(1/4).
For pollard-rho to be faster than built-in pow lg(e) > m^(1/4)
check is added.
3. For any unevaluated power found in `b` or `e`, the step 2
will be recursed down to the base and the exponent
such that the `b \bmod q` becomes the new base and
``\phi(q) + e \bmod \phi(q)`` becomes the new exponent, and then
the computation for the reduced expression can be done.
"""
from sympy.ntheory import totient
from .mod import Mod
base, exp = self.base, self.exp
if exp.is_integer and exp.is_positive:
if q.is_integer and base % q == 0:
return S.Zero
if base.is_Integer and exp.is_Integer and q.is_Integer:
b, e, m = int(base), int(exp), int(q)
mb = m.bit_length()
if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
phi = totient(m)
return Integer(pow(b, phi + e%phi, m))
return Integer(pow(b, e, m))
if isinstance(base, Pow) and base.is_integer and base.is_number:
base = Mod(base, q)
return Mod(Pow(base, exp, evaluate=False), q)
if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
bit_length = int(q).bit_length()
# XXX Mod-Pow actually attempts to do a hanging evaluation
# if this dispatched function returns None.
# May need some fixes in the dispatcher itself.
if bit_length <= 80:
phi = totient(q)
exp = phi + Mod(exp, phi)
return Mod(Pow(base, exp, evaluate=False), q)
def _eval_is_even(self):
if self.exp.is_integer and self.exp.is_positive:
return self.base.is_even
def _eval_is_negative(self):
ext_neg = Pow._eval_is_extended_negative(self)
if ext_neg is True:
return self.is_finite
return ext_neg
def _eval_is_positive(self):
ext_pos = Pow._eval_is_extended_positive(self)
if ext_pos is True:
return self.is_finite
return ext_pos
def _eval_is_extended_positive(self):
from sympy import log
if self.base == self.exp:
if self.base.is_extended_nonnegative:
return True
elif self.base.is_positive:
if self.exp.is_real:
return True
elif self.base.is_extended_negative:
if self.exp.is_even:
return True
if self.exp.is_odd:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return self.exp.is_zero
elif self.base.is_extended_nonpositive:
if self.exp.is_odd:
return False
elif self.base.is_imaginary:
if self.exp.is_integer:
m = self.exp % 4
if m.is_zero:
return True
if m.is_integer and m.is_zero is False:
return False
if self.exp.is_imaginary:
return log(self.base).is_imaginary
def _eval_is_extended_negative(self):
if self.exp is S(1)/2:
if self.base.is_complex or self.base.is_extended_real:
return False
if self.base.is_extended_negative:
if self.exp.is_odd and self.base.is_finite:
return True
if self.exp.is_even:
return False
elif self.base.is_extended_positive:
if self.exp.is_extended_real:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return False
elif self.base.is_extended_nonnegative:
if self.exp.is_extended_nonnegative:
return False
elif self.base.is_extended_nonpositive:
if self.exp.is_even:
return False
elif self.base.is_extended_real:
if self.exp.is_even:
return False
def _eval_is_zero(self):
if self.base.is_zero:
if self.exp.is_extended_positive:
return True
elif self.exp.is_extended_nonpositive:
return False
elif self.base.is_zero is False:
if self.base.is_finite and self.exp.is_finite:
return False
elif self.exp.is_negative:
return self.base.is_infinite
elif self.exp.is_nonnegative:
return False
elif self.exp.is_infinite and self.exp.is_extended_real:
if (1 - abs(self.base)).is_extended_positive:
return self.exp.is_extended_positive
elif (1 - abs(self.base)).is_extended_negative:
return self.exp.is_extended_negative
else: # when self.base.is_zero is None
if self.base.is_finite and self.exp.is_negative:
return False
def _eval_is_integer(self):
b, e = self.args
if b.is_rational:
if b.is_integer is False and e.is_positive:
return False # rat**nonneg
if b.is_integer and e.is_integer:
if b is S.NegativeOne:
return True
if e.is_nonnegative or e.is_positive:
return True
if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
return False
if b.is_Number and e.is_Number:
check = self.func(*self.args)
return check.is_Integer
if e.is_negative and b.is_positive and (b - 1).is_positive:
return False
if e.is_negative and b.is_negative and (b + 1).is_negative:
return False
def _eval_is_extended_real(self):
from ..functions import arg, log, exp
from .mul import Mul
if self.base is S.Exp1:
if self.exp.is_extended_real:
return True
elif self.exp.is_imaginary:
return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
real_b = self.base.is_extended_real
if real_b is None:
if self.base.func == exp and self.base.args[0].is_imaginary:
return self.exp.is_imaginary
if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
return self.exp.is_imaginary
return
real_e = self.exp.is_extended_real
if real_e is None:
return
if real_b and real_e:
if self.base.is_extended_positive:
return True
elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
return True
elif self.exp.is_integer and self.base.is_extended_nonzero:
return True
elif self.exp.is_integer and self.exp.is_nonnegative:
return True
elif self.base.is_extended_negative:
if self.exp.is_Rational:
return False
if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
return Pow(self.base, -self.exp).is_extended_real
im_b = self.base.is_imaginary
im_e = self.exp.is_imaginary
if im_b:
if self.exp.is_integer:
if self.exp.is_even:
return True
elif self.exp.is_odd:
return False
elif im_e and log(self.base).is_imaginary:
return True
elif self.exp.is_Add:
c, a = self.exp.as_coeff_Add()
if c and c.is_Integer:
return Mul(
self.base**c, self.base**a, evaluate=False).is_extended_real
elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
if (self.exp/2).is_integer is False:
return False
if real_b and im_e:
if self.base is S.NegativeOne:
return True
c = self.exp.coeff(S.ImaginaryUnit)
if c:
if self.base.is_rational and c.is_rational:
if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
return False
ok = (c*log(self.base)/S.Pi).is_integer
if ok is not None:
return ok
if real_b is False: # we already know it's not imag
i = arg(self.base)*self.exp/S.Pi
if i.is_complex: # finite
return i.is_integer
def _eval_is_complex(self):
if all(a.is_complex for a in self.args) and self._eval_is_finite():
return True
def _eval_is_imaginary(self):
from sympy import arg, log
if self.base.is_imaginary:
if self.exp.is_integer:
odd = self.exp.is_odd
if odd is not None:
return odd
return
if self.exp.is_imaginary:
imlog = log(self.base).is_imaginary
if imlog is not None:
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
if self.base.is_extended_real and self.exp.is_extended_real:
if self.base.is_positive:
return False
else:
rat = self.exp.is_rational
if not rat:
return rat
if self.exp.is_integer:
return False
else:
half = (2*self.exp).is_integer
if half:
return self.base.is_negative
return half
if self.base.is_extended_real is False: # we already know it's not imag
i = arg(self.base)*self.exp/S.Pi
isodd = (2*i).is_odd
if isodd is not None:
return isodd
def _eval_is_odd(self):
if self.exp.is_integer:
if self.exp.is_positive:
return self.base.is_odd
elif self.exp.is_nonnegative and self.base.is_odd:
return True
elif self.base is S.NegativeOne:
return True
def _eval_is_finite(self):
if self.exp.is_negative:
if self.base.is_zero:
return False
if self.base.is_infinite or self.base.is_nonzero:
return True
c1 = self.base.is_finite
if c1 is None:
return
c2 = self.exp.is_finite
if c2 is None:
return
if c1 and c2:
if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
return True
def _eval_is_prime(self):
'''
An integer raised to the n(>=2)-th power cannot be a prime.
'''
if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
return False
def _eval_is_composite(self):
"""
A power is composite if both base and exponent are greater than 1
"""
if (self.base.is_integer and self.exp.is_integer and
((self.base - 1).is_positive and (self.exp - 1).is_positive or
(self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
return True
def _eval_is_polar(self):
return self.base.is_polar
def _eval_subs(self, old, new):
from sympy import exp, log, Symbol
def _check(ct1, ct2, old):
"""Return (bool, pow, remainder_pow) where, if bool is True, then the
exponent of Pow `old` will combine with `pow` so the substitution
is valid, otherwise bool will be False.
For noncommutative objects, `pow` will be an integer, and a factor
`Pow(old.base, remainder_pow)` needs to be included. If there is
no such factor, None is returned. For commutative objects,
remainder_pow is always None.
cti are the coefficient and terms of an exponent of self or old
In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
will give y**2 since (b**x)**2 == b**(2*x); if that equality does
not hold then the substitution should not occur so `bool` will be
False.
"""
coeff1, terms1 = ct1
coeff2, terms2 = ct2
if terms1 == terms2:
if old.is_commutative:
# Allow fractional powers for commutative objects
pow = coeff1/coeff2
try:
as_int(pow, strict=False)
combines = True
except ValueError:
combines = isinstance(Pow._eval_power(
Pow(*old.as_base_exp(), evaluate=False),
pow), (Pow, exp, Symbol))
return combines, pow, None
else:
# With noncommutative symbols, substitute only integer powers
if not isinstance(terms1, tuple):
terms1 = (terms1,)
if not all(term.is_integer for term in terms1):
return False, None, None
try:
# Round pow toward zero
pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
if pow < 0 and remainder != 0:
pow += 1
remainder -= as_int(coeff2)
if remainder == 0:
remainder_pow = None
else:
remainder_pow = Mul(remainder, *terms1)
return True, pow, remainder_pow
except ValueError:
# Can't substitute
pass
return False, None, None
if old == self.base:
return new**self.exp._subs(old, new)
# issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
if isinstance(old, self.func) and self.exp == old.exp:
l = log(self.base, old.base)
if l.is_Number:
return Pow(new, l)
if isinstance(old, self.func) and self.base == old.base:
if self.exp.is_Add is False:
ct1 = self.exp.as_independent(Symbol, as_Add=False)
ct2 = old.exp.as_independent(Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
# issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
result = self.func(new, pow)
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
# exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
oarg = old.exp
new_l = []
o_al = []
ct2 = oarg.as_coeff_mul()
for a in self.exp.args:
newa = a._subs(old, new)
ct1 = newa.as_coeff_mul()
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
new_l.append(new**pow)
if remainder_pow is not None:
o_al.append(remainder_pow)
continue
elif not old.is_commutative and not newa.is_integer:
# If any term in the exponent is non-integer,
# we do not do any substitutions in the noncommutative case
return
o_al.append(newa)
if new_l:
expo = Add(*o_al)
new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
return Mul(*new_l)
if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
ct1 = old.args[0].as_independent(Symbol, as_Add=False)
ct2 = (self.exp*log(self.base)).as_independent(
Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
def as_base_exp(self):
"""Return base and exp of self.
Explnation
==========
If base is 1/Integer, then return Integer, -exp. If this extra
processing is not needed, the base and exp properties will
give the raw arguments
Examples
========
>>> from sympy import Pow, S
>>> p = Pow(S.Half, 2, evaluate=False)
>>> p.as_base_exp()
(2, -2)
>>> p.args
(1/2, 2)
"""
b, e = self.args
if b.is_Rational and b.p == 1 and b.q != 1:
return Integer(b.q), -e
return b, e
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import adjoint
i, p = self.exp.is_integer, self.base.is_positive
if i:
return adjoint(self.base)**self.exp
if p:
return self.base**adjoint(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return adjoint(expanded)
def _eval_conjugate(self):
from sympy.functions.elementary.complexes import conjugate as c
i, p = self.exp.is_integer, self.base.is_positive
if i:
return c(self.base)**self.exp
if p:
return self.base**c(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return c(expanded)
if self.is_extended_real:
return self
def _eval_transpose(self):
from sympy.functions.elementary.complexes import transpose
i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
if p:
return self.base**self.exp
if i:
return transpose(self.base)**self.exp
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return transpose(expanded)
def _eval_expand_power_exp(self, **hints):
"""a**(n + m) -> a**n*a**m"""
b = self.base
e = self.exp
if e.is_Add and e.is_commutative:
expr = []
for x in e.args:
expr.append(self.func(self.base, x))
return Mul(*expr)
return self.func(b, e)
def _eval_expand_power_base(self, **hints):
"""(a*b)**n -> a**n * b**n"""
force = hints.get('force', False)
b = self.base
e = self.exp
if not b.is_Mul:
return self
cargs, nc = b.args_cnc(split_1=False)
# expand each term - this is top-level-only
# expansion but we have to watch out for things
# that don't have an _eval_expand method
if nc:
nc = [i._eval_expand_power_base(**hints)
if hasattr(i, '_eval_expand_power_base') else i
for i in nc]
if e.is_Integer:
if e.is_positive:
rv = Mul(*nc*e)
else:
rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
if cargs:
rv *= Mul(*cargs)**e
return rv
if not cargs:
return self.func(Mul(*nc), e, evaluate=False)
nc = [Mul(*nc)]
# sift the commutative bases
other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
binary=True)
def pred(x):
if x is S.ImaginaryUnit:
return S.ImaginaryUnit
polar = x.is_polar
if polar:
return True
if polar is None:
return fuzzy_bool(x.is_extended_nonnegative)
sifted = sift(maybe_real, pred)
nonneg = sifted[True]
other += sifted[None]
neg = sifted[False]
imag = sifted[S.ImaginaryUnit]
if imag:
I = S.ImaginaryUnit
i = len(imag) % 4
if i == 0:
pass
elif i == 1:
other.append(I)
elif i == 2:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
else:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
other.append(I)
del imag
# bring out the bases that can be separated from the base
if force or e.is_integer:
# treat all commutatives the same and put nc in other
cargs = nonneg + neg + other
other = nc
else:
# this is just like what is happening automatically, except
# that now we are doing it for an arbitrary exponent for which
# no automatic expansion is done
assert not e.is_Integer
# handle negatives by making them all positive and putting
# the residual -1 in other
if len(neg) > 1:
o = S.One
if not other and neg[0].is_Number:
o *= neg.pop(0)
if len(neg) % 2:
o = -o
for n in neg:
nonneg.append(-n)
if o is not S.One:
other.append(o)
elif neg and other:
if neg[0].is_Number and neg[0] is not S.NegativeOne:
other.append(S.NegativeOne)
nonneg.append(-neg[0])
else:
other.extend(neg)
else:
other.extend(neg)
del neg
cargs = nonneg
other += nc
rv = S.One
if cargs:
if e.is_Rational:
npow, cargs = sift(cargs, lambda x: x.is_Pow and
x.exp.is_Rational and x.base.is_number,
binary=True)
rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
if other:
rv *= self.func(Mul(*other), e, evaluate=False)
return rv
def _eval_expand_multinomial(self, **hints):
"""(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
base, exp = self.args
result = self
if exp.is_Rational and exp.p > 0 and base.is_Add:
if not exp.is_Integer:
n = Integer(exp.p // exp.q)
if not n:
return result
else:
radical, result = self.func(base, exp - n), []
expanded_base_n = self.func(base, n)
if expanded_base_n.is_Pow:
expanded_base_n = \
expanded_base_n._eval_expand_multinomial()
for term in Add.make_args(expanded_base_n):
result.append(term*radical)
return Add(*result)
n = int(exp)
if base.is_commutative:
order_terms, other_terms = [], []
for b in base.args:
if b.is_Order:
order_terms.append(b)
else:
other_terms.append(b)
if order_terms:
# (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
f = Add(*other_terms)
o = Add(*order_terms)
if n == 2:
return expand_multinomial(f**n, deep=False) + n*f*o
else:
g = expand_multinomial(f**(n - 1), deep=False)
return expand_mul(f*g, deep=False) + n*g*o
if base.is_number:
# Efficiently expand expressions of the form (a + b*I)**n
# where 'a' and 'b' are real numbers and 'n' is integer.
a, b = base.as_real_imag()
if a.is_Rational and b.is_Rational:
if not a.is_Integer:
if not b.is_Integer:
k = self.func(a.q * b.q, n)
a, b = a.p*b.q, a.q*b.p
else:
k = self.func(a.q, n)
a, b = a.p, a.q*b
elif not b.is_Integer:
k = self.func(b.q, n)
a, b = a*b.q, b.p
else:
k = 1
a, b, c, d = int(a), int(b), 1, 0
while n:
if n & 1:
c, d = a*c - b*d, b*c + a*d
n -= 1
a, b = a*a - b*b, 2*a*b
n //= 2
I = S.ImaginaryUnit
if k == 1:
return c + I*d
else:
return Integer(c)/k + I*d/k
p = other_terms
# (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
# in this particular example:
# p = [x,y]; n = 3
# so now it's easy to get the correct result -- we get the
# coefficients first:
from sympy import multinomial_coefficients
from sympy.polys.polyutils import basic_from_dict
expansion_dict = multinomial_coefficients(len(p), n)
# in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
# and now construct the expression.
return basic_from_dict(expansion_dict, *p)
else:
if n == 2:
return Add(*[f*g for f in base.args for g in base.args])
else:
multi = (base**(n - 1))._eval_expand_multinomial()
if multi.is_Add:
return Add(*[f*g for f in base.args
for g in multi.args])
else:
# XXX can this ever happen if base was an Add?
return Add(*[f*multi for f in base.args])
elif (exp.is_Rational and exp.p < 0 and base.is_Add and
abs(exp.p) > exp.q):
return 1 / self.func(base, -exp)._eval_expand_multinomial()
elif exp.is_Add and base.is_Number:
# a + b a b
# n --> n n , where n, a, b are Numbers
coeff, tail = S.One, S.Zero
for term in exp.args:
if term.is_Number:
coeff *= self.func(base, term)
else:
tail += term
return coeff * self.func(base, tail)
else:
return result
def as_real_imag(self, deep=True, **hints):
from sympy import atan2, cos, im, re, sin
from sympy.polys.polytools import poly
if self.exp.is_Integer:
exp = self.exp
re_e, im_e = self.base.as_real_imag(deep=deep)
if not im_e:
return self, S.Zero
a, b = symbols('a b', cls=Dummy)
if exp >= 0:
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial(self.base**exp)
if expr != self:
return expr.as_real_imag()
expr = poly(
(a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
else:
mag = re_e**2 + im_e**2
re_e, im_e = re_e/mag, -im_e/mag
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
if expr != self:
return expr.as_real_imag()
expr = poly((a + b)**-exp)
# Terms with even b powers will be real
r = [i for i in expr.terms() if not i[0][1] % 2]
re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
# Terms with odd b powers will be imaginary
r = [i for i in expr.terms() if i[0][1] % 4 == 1]
im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
r = [i for i in expr.terms() if i[0][1] % 4 == 3]
im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
elif self.exp.is_Rational:
re_e, im_e = self.base.as_real_imag(deep=deep)
if im_e.is_zero and self.exp is S.Half:
if re_e.is_extended_nonnegative:
return self, S.Zero
if re_e.is_extended_nonpositive:
return S.Zero, (-self.base)**self.exp
# XXX: This is not totally correct since for x**(p/q) with
# x being imaginary there are actually q roots, but
# only a single one is returned from here.
r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
t = atan2(im_e, re_e)
rp, tp = self.func(r, self.exp), t*self.exp
return rp*cos(tp), rp*sin(tp)
elif self.base is S.Exp1:
from ..functions import exp
re_e, im_e = self.exp.as_real_imag()
if deep:
re_e = re_e.expand(deep, **hints)
im_e = im_e.expand(deep, **hints)
c, s = cos(im_e), sin(im_e)
return exp(re_e)*c, exp(re_e)*s
else:
if deep:
hints['complex'] = False
expanded = self.expand(deep, **hints)
if hints.get('ignore') == expanded:
return None
else:
return (re(expanded), im(expanded))
else:
return re(self), im(self)
def _eval_derivative(self, s):
from sympy import log
dbase = self.base.diff(s)
dexp = self.exp.diff(s)
return self * (dexp * log(self.base) + dbase * self.exp/self.base)
def _eval_evalf(self, prec):
base, exp = self.as_base_exp()
base = base._evalf(prec)
if not exp.is_Integer:
exp = exp._evalf(prec)
if exp.is_negative and base.is_number and base.is_extended_real is False:
base = base.conjugate() / (base * base.conjugate())._evalf(prec)
exp = -exp
return self.func(base, exp).expand()
return self.func(base, exp)
def _eval_is_polynomial(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return bool(self.base._eval_is_polynomial(syms) and
self.exp.is_Integer and (self.exp >= 0))
else:
return True
def _eval_is_rational(self):
# The evaluation of self.func below can be very expensive in the case
# of integer**integer if the exponent is large. We should try to exit
# before that if possible:
if (self.exp.is_integer and self.base.is_rational
and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
return True
p = self.func(*self.as_base_exp()) # in case it's unevaluated
if not p.is_Pow:
return p.is_rational
b, e = p.as_base_exp()
if e.is_Rational and b.is_Rational:
# we didn't check that e is not an Integer
# because Rational**Integer autosimplifies
return False
if e.is_integer:
if b.is_rational:
if fuzzy_not(b.is_zero) or e.is_nonnegative:
return True
if b == e: # always rational, even for 0**0
return True
elif b.is_irrational:
return e.is_zero
if b is S.Exp1:
if e.is_rational and e.is_nonzero:
return False
def _eval_is_algebraic(self):
def _is_one(expr):
try:
return (expr - 1).is_zero
except ValueError:
# when the operation is not allowed
return False
if self.base.is_zero or _is_one(self.base):
return True
elif self.base is S.Exp1:
s = self.func(*self.args)
if s.func == self.func:
if self.exp.is_nonzero:
if self.exp.is_algebraic:
return False
elif (self.exp/S.Pi).is_rational:
return False
elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
return True
else:
return s.is_algebraic
elif self.exp.is_rational:
if self.base.is_algebraic is False:
return self.exp.is_zero
if self.base.is_zero is False:
if self.exp.is_nonzero:
return self.base.is_algebraic
elif self.base.is_algebraic:
return True
if self.exp.is_positive:
return self.base.is_algebraic
elif self.base.is_algebraic and self.exp.is_algebraic:
if ((fuzzy_not(self.base.is_zero)
and fuzzy_not(_is_one(self.base)))
or self.base.is_integer is False
or self.base.is_irrational):
return self.exp.is_rational
def _eval_is_rational_function(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_rational_function(syms) and \
self.exp.is_Integer
else:
return True
def _eval_is_meromorphic(self, x, a):
# f**g is meromorphic if g is an integer and f is meromorphic.
# E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
# and finite.
base_merom = self.base._eval_is_meromorphic(x, a)
exp_integer = self.exp.is_Integer
if exp_integer:
return base_merom
exp_merom = self.exp._eval_is_meromorphic(x, a)
if base_merom is False:
# f**g = E**(log(f)*g) may be meromorphic if the
# singularities of log(f) and g cancel each other,
# for example, if g = 1/log(f). Hence,
return False if exp_merom else None
elif base_merom is None:
return None
b = self.base.subs(x, a)
# b is extended complex as base is meromorphic.
# log(base) is finite and meromorphic when b != 0, zoo.
b_zero = b.is_zero
if b_zero:
log_defined = False
else:
log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
if log_defined is False: # zero or pole of base
return exp_integer # False or None
elif log_defined is None:
return None
if not exp_merom:
return exp_merom # False or None
return self.exp.subs(x, a).is_finite
def _eval_is_algebraic_expr(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_algebraic_expr(syms) and \
self.exp.is_Rational
else:
return True
def _eval_rewrite_as_exp(self, base, expo, **kwargs):
from sympy import exp, log, I, arg
if base.is_zero or base.has(exp) or expo.has(exp):
return base**expo
if base.has(Symbol):
# delay evaluation if expo is non symbolic
# (as exp(x*log(5)) automatically reduces to x**5)
return exp(log(base)*expo, evaluate=expo.has(Symbol))
else:
return exp((log(abs(base)) + I*arg(base))*expo)
def as_numer_denom(self):
if not self.is_commutative:
return self, S.One
base, exp = self.as_base_exp()
n, d = base.as_numer_denom()
# this should be the same as ExpBase.as_numer_denom wrt
# exponent handling
neg_exp = exp.is_negative
if not neg_exp and not (-exp).is_negative:
neg_exp = _coeff_isneg(exp)
int_exp = exp.is_integer
# the denominator cannot be separated from the numerator if
# its sign is unknown unless the exponent is an integer, e.g.
# sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
# denominator is negative the numerator and denominator can
# be negated and the denominator (now positive) separated.
if not (d.is_extended_real or int_exp):
n = base
d = S.One
dnonpos = d.is_nonpositive
if dnonpos:
n, d = -n, -d
elif dnonpos is None and not int_exp:
n = base
d = S.One
if neg_exp:
n, d = d, n
exp = -exp
if exp.is_infinite:
if n is S.One and d is not S.One:
return n, self.func(d, exp)
if n is not S.One and d is S.One:
return self.func(n, exp), d
return self.func(n, exp), self.func(d, exp)
def matches(self, expr, repl_dict={}, old=False):
expr = _sympify(expr)
repl_dict = repl_dict.copy()
# special case, pattern = 1 and expr.exp can match to 0
if expr is S.One:
d = self.exp.matches(S.Zero, repl_dict)
if d is not None:
return d
# make sure the expression to be matched is an Expr
if not isinstance(expr, Expr):
return None
b, e = expr.as_base_exp()
# special case number
sb, se = self.as_base_exp()
if sb.is_Symbol and se.is_Integer and expr:
if e.is_rational:
return sb.matches(b**(e/se), repl_dict)
return sb.matches(expr**(1/se), repl_dict)
d = repl_dict.copy()
d = self.base.matches(b, d)
if d is None:
return None
d = self.exp.xreplace(d).matches(e, d)
if d is None:
return Expr.matches(self, expr, repl_dict)
return d
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE! This function is an important part of the gruntz algorithm
# for computing limits. It has to return a generalized power
# series with coefficients in C(log, log(x)). In more detail:
# It has to return an expression
# c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
# where e_i are numbers (not necessarily integers) and c_i are
# expressions involving only numbers, the log function, and log(x).
# The series expansion of b**e is computed as follows:
# 1) We express b as f*(1 + g) where f is the leading term of b.
# g has order O(x**d) where d is strictly positive.
# 2) Then b**e = (f**e)*((1 + g)**e).
# (1 + g)**e is computed using binomial series.
from sympy import im, I, ceiling, polygamma, logcombine, EulerGamma, nan, zoo, factorial, ff, PoleError, O, powdenest, Wild
from itertools import product
from ..functions import exp, log
from ..series import Order, limit
from ..simplify import powsimp
if self.base is S.Exp1:
e_series = self.exp.nseries(x, n=n, logx=logx)
if e_series.is_Order:
return 1 + e_series
e0 = limit(e_series.removeO(), x, 0)
if e0 in (-S.NegativeInfinity, S.Infinity):
return self
t = e_series - e0
exp_series = term = exp(e0)
# series of exp(e0 + t) in t
for i in range(1, n):
term *= t/i
term = term.nseries(x, n=n, logx=logx)
exp_series += term
exp_series += Order(t**n, x)
return powsimp(exp_series, deep=True, combine='exp')
self = powdenest(self, force=True).trigsimp()
b, e = self.as_base_exp()
if e.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
raise PoleError()
if e.has(x):
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
if logx is not None and b.has(log):
c, ex = symbols('c, ex', cls=Wild, exclude=[x])
b = b.replace(log(c*x**ex), log(c) + ex*logx)
self = b**e
b = b.removeO()
try:
if b.has(polygamma, EulerGamma) and logx is not None:
raise ValueError()
_, m = b.leadterm(x)
except (ValueError, NotImplementedError):
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
if b.has(nan, zoo):
raise NotImplementedError()
_, m = b.leadterm(x)
if e.has(log):
e = logcombine(e).cancel()
if not (m.is_zero or e.is_number and e.is_real):
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
f = b.as_leading_term(x)
g = (b/f - S.One).cancel()
maxpow = n - m*e
if maxpow < S.Zero:
return O(x**(m*e), x)
if g.is_zero:
return f**e
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
def mul(d1, d2):
res = {}
for e1, e2 in product(d1, d2):
ex = e1 + e2
if ex < maxpow:
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
return res
try:
_, d = g.leadterm(x)
except (ValueError, NotImplementedError):
if limit(g/x**maxpow, x, 0) == 0:
# g has higher order zero
return f**e + e*f**e*g # first term of binomial series
else:
raise NotImplementedError()
if not d.is_positive:
g = (b - f).simplify()/f
_, d = g.leadterm(x)
if not d.is_positive:
raise NotImplementedError()
gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
gterms = {}
for term in Add.make_args(gpoly):
co1, e1 = coeff_exp(term, x)
gterms[e1] = gterms.get(e1, S.Zero) + co1
k = S.One
terms = {S.Zero: S.One}
tk = gterms
while k*d < maxpow:
coeff = ff(e, k)/factorial(k)
for ex in tk:
terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
tk = mul(tk, gterms)
k += S.One
if (not e.is_integer and m.is_zero and f.is_real
and f.is_negative and im((b - f).dir(x, cdir)) < 0):
inco, inex = coeff_exp(f**e*exp(-2*e*S.Pi*I), x)
else:
inco, inex = coeff_exp(f**e, x)
res = S.Zero
for e1 in terms:
ex = e1 + inex
res += terms[e1]*inco*x**(ex)
for i in (1, 2, 3):
if (res - self).subs(x, i) is not S.Zero:
res += O(x**n, x)
break
return res
def _eval_as_leading_term(self, x, cdir=0):
from ..series import Order
from sympy import exp, I, im, log
e = self.exp
b = self.base
if self.base is S.Exp1:
arg = self.exp
if arg.is_Add:
return Mul(*[(S.Exp1**f).as_leading_term(x) for f in arg.args])
arg_1 = arg.as_leading_term(x)
if Order(x, x).contains(arg_1):
return S.One
if Order(1, x).contains(arg_1):
return S.Exp1**arg_1
####################################################
# The correct result here should be 'None'. #
# Indeed arg in not bounded as x tends to 0. #
# Consequently the series expansion does not admit #
# the leading term. #
# For compatibility reasons, the return value here #
# is the original function, i.e. exp(arg), #
# instead of None. #
####################################################
return S.Exp1**arg
elif e.has(x):
return exp(e * log(b)).as_leading_term(x, cdir=cdir)
else:
f = b.as_leading_term(x, cdir=cdir)
if (not e.is_integer and f.is_constant() and f.is_real
and f.is_negative and im((b - f).dir(x, cdir)) < 0):
return self.func(f, e) * exp(-2 * e * S.Pi * I)
return self.func(f, e)
@cacheit
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
from sympy import binomial
return binomial(self.exp, n) * self.func(x, n)
def taylor_term(self, n, x, *previous_terms):
if self.base is not S.Exp1:
return super().taylor_term(n, x, *previous_terms)
from sympy import sympify, factorial
if n < 0:
return S.Zero
if n == 0:
return S.One
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
return x**n/factorial(n)
def _sage_(self):
return self.args[0]._sage_()**self.args[1]._sage_()
def _eval_rewrite_as_sin(self, base, exp):
from ..functions import sin
if self.base is S.Exp1:
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
def _eval_rewrite_as_cos(self, base, exp):
from ..functions import cos
if self.base is S.Exp1:
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
def _eval_rewrite_as_tanh(self, base, exp):
from ..functions import tanh
if self.base is S.Exp1:
return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
from sympy.functions.elementary.trigonometric import sin, cos
if base is not S.Exp1:
return None
if exp.is_Mul:
coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
if coeff and coeff.is_number:
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
if not isinstance(cosine, cos) and not isinstance (sine, sin):
return cosine + S.ImaginaryUnit*sine
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import sqrt
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
(2, sqrt(1 + sqrt(2)))
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
(1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from sympy import expand_power_base, powsimp, Mul
>>> from sympy.abc import x, y
>>> ((2*x + 2)**2).as_content_primitive()
(4, (x + 1)**2)
>>> (4**((1 + y)/2)).as_content_primitive()
(2, 4**(y/2))
>>> (3**((1 + y)/2)).as_content_primitive()
(1, 3**((y + 1)/2))
>>> (3**((5 + y)/2)).as_content_primitive()
(9, 3**((y + 1)/2))
>>> eq = 3**(2 + 2*x)
>>> powsimp(eq) == eq
True
>>> eq.as_content_primitive()
(9, 3**(2*x))
>>> powsimp(Mul(*_))
3**(2*x + 2)
>>> eq = (2 + 2*x)**y
>>> s = expand_power_base(eq); s.is_Mul, s
(False, (2*x + 2)**y)
>>> eq.as_content_primitive()
(1, (2*(x + 1))**y)
>>> s = expand_power_base(_[1]); s.is_Mul, s
(True, 2**y*(x + 1)**y)
See docstring of Expr.as_content_primitive for more examples.
"""
b, e = self.as_base_exp()
b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
ce, pe = e.as_content_primitive(radical=radical, clear=clear)
if b.is_Rational:
#e
#= ce*pe
#= ce*(h + t)
#= ce*h + ce*t
#=> self
#= b**(ce*h)*b**(ce*t)
#= b**(cehp/cehq)*b**(ce*t)
#= b**(iceh + r/cehq)*b**(ce*t)
#= b**(iceh)*b**(r/cehq)*b**(ce*t)
#= b**(iceh)*b**(ce*t + r/cehq)
h, t = pe.as_coeff_Add()
if h.is_Rational:
ceh = ce*h
c = self.func(b, ceh)
r = S.Zero
if not c.is_Rational:
iceh, r = divmod(ceh.p, ceh.q)
c = self.func(b, iceh)
return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
e = _keep_coeff(ce, pe)
# b**e = (h*t)**e = h**e*t**e = c*m*t**e
if e.is_Rational and b.is_Mul:
h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
c, m = self.func(h, e).as_coeff_Mul() # so c is positive
m, me = m.as_base_exp()
if m is S.One or me == e: # probably always true
# return the following, not return c, m*Pow(t, e)
# which would change Pow into Mul; we let sympy
# decide what to do by using the unevaluated Mul, e.g
# should it stay as sqrt(2 + 2*sqrt(5)) or become
# sqrt(2)*sqrt(1 + sqrt(5))
return c, self.func(_keep_coeff(m, t), e)
return S.One, self.func(b, e)
def is_constant(self, *wrt, **flags):
expr = self
if flags.get('simplify', True):
expr = expr.simplify()
b, e = expr.as_base_exp()
bz = b.equals(0)
if bz: # recalculate with assumptions in case it's unevaluated
new = b**e
if new != expr:
return new.is_constant()
econ = e.is_constant(*wrt)
bcon = b.is_constant(*wrt)
if bcon:
if econ:
return True
bz = b.equals(0)
if bz is False:
return False
elif bcon is None:
return None
return e.equals(0)
def _eval_difference_delta(self, n, step):
b, e = self.args
if e.has(n) and not b.has(n):
new_e = e.subs(n, n + step)
return (b**(new_e - e) - 1) * self
power = Dispatcher('power')
power.add((object, object), Pow)
from .add import Add
from .numbers import Integer
from .mul import Mul, _keep_coeff
from .symbol import Symbol, Dummy, symbols
|
774cc14802957d625a454b3b83edb8d35343a7ed6afb9546739040103c9092d0 | """Thread-safe global parameters"""
from .cache import clear_cache
from contextlib import contextmanager
from threading import local
class _global_parameters(local):
"""
Thread-local global parameters.
Explanation
===========
This class generates thread-local container for SymPy's global parameters.
Every global parameters must be passed as keyword argument when generating
its instance.
A variable, `global_parameters` is provided as default instance for this class.
WARNING! Although the global parameters are thread-local, SymPy's cache is not
by now.
This may lead to undesired result in multi-threading operations.
Examples
========
>>> from sympy.abc import x
>>> from sympy.core.cache import clear_cache
>>> from sympy.core.parameters import global_parameters as gp
>>> gp.evaluate
True
>>> x+x
2*x
>>> log = []
>>> def f():
... clear_cache()
... gp.evaluate = False
... log.append(x+x)
... clear_cache()
>>> import threading
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
>>> print(log)
[x + x]
>>> gp.evaluate
True
>>> x+x
2*x
References
==========
.. [1] https://docs.python.org/3/library/threading.html
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __setattr__(self, name, value):
if getattr(self, name) != value:
clear_cache()
return super().__setattr__(name, value)
global_parameters = _global_parameters(evaluate=True, distribute=True, exp_is_pow=False)
@contextmanager
def evaluate(x):
""" Control automatic evaluation
Explanation
===========
This context manager controls whether or not all SymPy functions evaluate
by default.
Note that much of SymPy expects evaluated expressions. This functionality
is experimental and is unlikely to function as intended on large
expressions.
Examples
========
>>> from sympy.abc import x
>>> from sympy.core.parameters import evaluate
>>> print(x + x)
2*x
>>> with evaluate(False):
... print(x + x)
x + x
"""
old = global_parameters.evaluate
try:
global_parameters.evaluate = x
yield
finally:
global_parameters.evaluate = old
@contextmanager
def distribute(x):
""" Control automatic distribution of Number over Add
Explanation
===========
This context manager controls whether or not Mul distribute Number over
Add. Plan is to avoid distributing Number over Add in all of sympy. Once
that is done, this contextmanager will be removed.
Examples
========
>>> from sympy.abc import x
>>> from sympy.core.parameters import distribute
>>> print(2*(x + 1))
2*x + 2
>>> with distribute(False):
... print(2*(x + 1))
2*(x + 1)
"""
old = global_parameters.distribute
try:
global_parameters.distribute = x
yield
finally:
global_parameters.distribute = old
@contextmanager
def _exp_is_pow(x):
"""
Control whether `e^x` should be represented as ``exp(x)`` or a ``Pow(E, x)``.
Examples
========
>>> from sympy import exp
>>> from sympy.abc import x
>>> from sympy.core.parameters import _exp_is_pow
>>> with _exp_is_pow(True): print(type(exp(x)))
<class 'sympy.core.power.Pow'>
>>> with _exp_is_pow(False): print(type(exp(x)))
exp
"""
old = global_parameters.exp_is_pow
clear_cache()
try:
global_parameters.exp_is_pow = x
yield
finally:
clear_cache()
global_parameters.exp_is_pow = old
|
42ccd65a8ddc259ea8e6f1d0ae1f5af9ab1caa6991b61200b82130e3098e0dcb | from typing import Tuple as tTuple
from collections.abc import Iterable
from functools import reduce
from .sympify import sympify, _sympify, SympifyError
from .basic import Basic, Atom
from .singleton import S
from .evalf import EvalfMixin, pure_complex
from .decorators import call_highest_priority, sympify_method_args, sympify_return
from .cache import cacheit
from .compatibility import as_int, default_sort_key
from sympy.utilities.misc import func_name
from mpmath.libmp import mpf_log, prec_to_dps
from collections import defaultdict
@sympify_method_args
class Expr(Basic, EvalfMixin):
"""
Base class for algebraic expressions.
Explanation
===========
Everything that requires arithmetic operations to be defined
should subclass this class, instead of Basic (which should be
used only for argument storage and expression manipulation, i.e.
pattern matching, substitutions, etc).
If you want to override the comparisons of expressions:
Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
_eval_is_ge return true if x >= y, false if x < y, and None if the two types
are not comparable or the comparison is indeterminate
See Also
========
sympy.core.basic.Basic
"""
__slots__ = () # type: tTuple[str, ...]
is_scalar = True # self derivative is 1
@property
def _diff_wrt(self):
"""Return True if one can differentiate with respect to this
object, else False.
Explanation
===========
Subclasses such as Symbol, Function and Derivative return True
to enable derivatives wrt them. The implementation in Derivative
separates the Symbol and non-Symbol (_diff_wrt=True) variables and
temporarily converts the non-Symbols into Symbols when performing
the differentiation. By default, any object deriving from Expr
will behave like a scalar with self.diff(self) == 1. If this is
not desired then the object must also set `is_scalar = False` or
else define an _eval_derivative routine.
Note, see the docstring of Derivative for how this should work
mathematically. In particular, note that expr.subs(yourclass, Symbol)
should be well-defined on a structural level, or this will lead to
inconsistent results.
Examples
========
>>> from sympy import Expr
>>> e = Expr()
>>> e._diff_wrt
False
>>> class MyScalar(Expr):
... _diff_wrt = True
...
>>> MyScalar().diff(MyScalar())
1
>>> class MySymbol(Expr):
... _diff_wrt = True
... is_scalar = False
...
>>> MySymbol().diff(MySymbol())
Derivative(MySymbol(), MySymbol())
"""
return False
@cacheit
def sort_key(self, order=None):
coeff, expr = self.as_coeff_Mul()
if expr.is_Pow:
expr, exp = expr.args
else:
expr, exp = expr, S.One
if expr.is_Dummy:
args = (expr.sort_key(),)
elif expr.is_Atom:
args = (str(expr),)
else:
if expr.is_Add:
args = expr.as_ordered_terms(order=order)
elif expr.is_Mul:
args = expr.as_ordered_factors(order=order)
else:
args = expr.args
args = tuple(
[ default_sort_key(arg, order=order) for arg in args ])
args = (len(args), tuple(args))
exp = exp.sort_key(order=order)
return expr.class_key(), args, exp, coeff
def __hash__(self) -> int:
# hash cannot be cached using cache_it because infinite recurrence
# occurs as hash is needed for setting cache dictionary keys
h = self._mhash
if h is None:
h = hash((type(self).__name__,) + self._hashable_content())
self._mhash = h
return h
def _hashable_content(self):
"""Return a tuple of information about self that can be used to
compute the hash. If a class defines additional attributes,
like ``name`` in Symbol, then this method should be updated
accordingly to return such relevant attributes.
Defining more than _hashable_content is necessary if __eq__ has
been defined by a class. See note about this in Basic.__eq__."""
return self._args
def __eq__(self, other):
try:
other = _sympify(other)
if not isinstance(other, Expr):
return False
except (SympifyError, SyntaxError):
return False
# check for pure number expr
if not (self.is_Number and other.is_Number) and (
type(self) != type(other)):
return False
a, b = self._hashable_content(), other._hashable_content()
if a != b:
return False
# check number *in* an expression
for a, b in zip(a, b):
if not isinstance(a, Expr):
continue
if a.is_Number and type(a) != type(b):
return False
return True
# ***************
# * Arithmetics *
# ***************
# Expr and its sublcasses use _op_priority to determine which object
# passed to a binary special method (__mul__, etc.) will handle the
# operation. In general, the 'call_highest_priority' decorator will choose
# the object with the highest _op_priority to handle the call.
# Custom subclasses that want to define their own binary special methods
# should set an _op_priority value that is higher than the default.
#
# **NOTE**:
# This is a temporary fix, and will eventually be replaced with
# something better and more powerful. See issue 5510.
_op_priority = 10.0
@property
def _add_handler(self):
return Add
@property
def _mul_handler(self):
return Mul
def __pos__(self):
return self
def __neg__(self):
# Mul has its own __neg__ routine, so we just
# create a 2-args Mul with the -1 in the canonical
# slot 0.
c = self.is_commutative
return Mul._from_args((S.NegativeOne, self), c)
def __abs__(self):
from sympy import Abs
return Abs(self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return Add(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return Add(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return Add(self, -other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return Add(other, -self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return Mul(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return Mul(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rpow__')
def _pow(self, other):
return Pow(self, other)
def __pow__(self, other, mod=None):
if mod is None:
return self._pow(other)
try:
_self, other, mod = as_int(self), as_int(other), as_int(mod)
if other >= 0:
return pow(_self, other, mod)
else:
from sympy.core.numbers import mod_inverse
return mod_inverse(pow(_self, -other, mod), mod)
except ValueError:
power = self._pow(other)
try:
return power%mod
except TypeError:
return NotImplemented
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
return Pow(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
denom = Pow(other, S.NegativeOne)
if self is S.One:
return denom
else:
return Mul(self, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
denom = Pow(self, S.NegativeOne)
if other is S.One:
return denom
else:
return Mul(other, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmod__')
def __mod__(self, other):
return Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mod__')
def __rmod__(self, other):
return Mod(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rfloordiv__')
def __floordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__floordiv__')
def __rfloordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rdivmod__')
def __divmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other), Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__divmod__')
def __rdivmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self), Mod(other, self)
def __int__(self):
# Although we only need to round to the units position, we'll
# get one more digit so the extra testing below can be avoided
# unless the rounded value rounded to an integer, e.g. if an
# expression were equal to 1.9 and we rounded to the unit position
# we would get a 2 and would not know if this rounded up or not
# without doing a test (as done below). But if we keep an extra
# digit we know that 1.9 is not the same as 1 and there is no
# need for further testing: our int value is correct. If the value
# were 1.99, however, this would round to 2.0 and our int value is
# off by one. So...if our round value is the same as the int value
# (regardless of how much extra work we do to calculate extra decimal
# places) we need to test whether we are off by one.
from sympy import Dummy
if not self.is_number:
raise TypeError("can't convert symbols to int")
r = self.round(2)
if not r.is_Number:
raise TypeError("can't convert complex to int")
if r in (S.NaN, S.Infinity, S.NegativeInfinity):
raise TypeError("can't convert %s to int" % r)
i = int(r)
if not i:
return 0
# off-by-one check
if i == r and not (self - i).equals(0):
isign = 1 if i > 0 else -1
x = Dummy()
# in the following (self - i).evalf(2) will not always work while
# (self - r).evalf(2) and the use of subs does; if the test that
# was added when this comment was added passes, it might be safe
# to simply use sign to compute this rather than doing this by hand:
diff_sign = 1 if (self - x).evalf(2, subs={x: i}) > 0 else -1
if diff_sign != isign:
i -= isign
return i
def __float__(self):
# Don't bother testing if it's a number; if it's not this is going
# to fail, and if it is we still need to check that it evalf'ed to
# a number.
result = self.evalf()
if result.is_Number:
return float(result)
if result.is_number and result.as_real_imag()[1]:
raise TypeError("can't convert complex to float")
raise TypeError("can't convert expression to float")
def __complex__(self):
result = self.evalf()
re, im = result.as_real_imag()
return complex(float(re), float(im))
@sympify_return([('other', 'Expr')], NotImplemented)
def __ge__(self, other):
from .relational import GreaterThan
return GreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __le__(self, other):
from .relational import LessThan
return LessThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __gt__(self, other):
from .relational import StrictGreaterThan
return StrictGreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __lt__(self, other):
from .relational import StrictLessThan
return StrictLessThan(self, other)
def __trunc__(self):
if not self.is_number:
raise TypeError("can't truncate symbols and expressions")
else:
return Integer(self)
@staticmethod
def _from_mpmath(x, prec):
from sympy import Float
if hasattr(x, "_mpf_"):
return Float._new(x._mpf_, prec)
elif hasattr(x, "_mpc_"):
re, im = x._mpc_
re = Float._new(re, prec)
im = Float._new(im, prec)*S.ImaginaryUnit
return re + im
else:
raise TypeError("expected mpmath number (mpf or mpc)")
@property
def is_number(self):
"""Returns True if ``self`` has no free symbols and no
undefined functions (AppliedUndef, to be precise). It will be
faster than ``if not self.free_symbols``, however, since
``is_number`` will fail as soon as it hits a free symbol
or undefined function.
Examples
========
>>> from sympy import Integral, cos, sin, pi
>>> from sympy.core.function import Function
>>> from sympy.abc import x
>>> f = Function('f')
>>> x.is_number
False
>>> f(1).is_number
False
>>> (2*x).is_number
False
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True
Not all numbers are Numbers in the SymPy sense:
>>> pi.is_number, pi.is_Number
(True, False)
If something is a number it should evaluate to a number with
real and imaginary parts that are Numbers; the result may not
be comparable, however, since the real and/or imaginary part
of the result may not have precision.
>>> cos(1).is_number and cos(1).is_comparable
True
>>> z = cos(1)**2 + sin(1)**2 - 1
>>> z.is_number
True
>>> z.is_comparable
False
See Also
========
sympy.core.basic.Basic.is_comparable
"""
return all(obj.is_number for obj in self.args)
def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
"""Return self evaluated, if possible, replacing free symbols with
random complex values, if necessary.
Explanation
===========
The random complex value for each free symbol is generated
by the random_complex_number routine giving real and imaginary
parts in the range given by the re_min, re_max, im_min, and im_max
values. The returned value is evaluated to a precision of n
(if given) else the maximum of 15 and the precision needed
to get more than 1 digit of precision. If the expression
could not be evaluated to a number, or could not be evaluated
to more than 1 digit of precision, then None is returned.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y
>>> x._random() # doctest: +SKIP
0.0392918155679172 + 0.916050214307199*I
>>> x._random(2) # doctest: +SKIP
-0.77 - 0.87*I
>>> (x + y/2)._random(2) # doctest: +SKIP
-0.57 + 0.16*I
>>> sqrt(2)._random(2)
1.4
See Also
========
sympy.testing.randtest.random_complex_number
"""
free = self.free_symbols
prec = 1
if free:
from sympy.testing.randtest import random_complex_number
a, c, b, d = re_min, re_max, im_min, im_max
reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True)
for zi in free])))
try:
nmag = abs(self.evalf(2, subs=reps))
except (ValueError, TypeError):
# if an out of range value resulted in evalf problems
# then return None -- XXX is there a way to know how to
# select a good random number for a given expression?
# e.g. when calculating n! negative values for n should not
# be used
return None
else:
reps = {}
nmag = abs(self.evalf(2))
if not hasattr(nmag, '_prec'):
# e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True
return None
if nmag._prec == 1:
# increase the precision up to the default maximum
# precision to see if we can get any significance
from mpmath.libmp.libintmath import giant_steps
from sympy.core.evalf import DEFAULT_MAXPREC as target
# evaluate
for prec in giant_steps(2, target):
nmag = abs(self.evalf(prec, subs=reps))
if nmag._prec != 1:
break
if nmag._prec != 1:
if n is None:
n = max(prec, 15)
return self.evalf(n, subs=reps)
# never got any significance
return None
def is_constant(self, *wrt, **flags):
"""Return True if self is constant, False if not, or None if
the constancy could not be determined conclusively.
Explanation
===========
If an expression has no free symbols then it is a constant. If
there are free symbols it is possible that the expression is a
constant, perhaps (but not necessarily) zero. To test such
expressions, a few strategies are tried:
1) numerical evaluation at two random points. If two such evaluations
give two different values and the values have a precision greater than
1 then self is not constant. If the evaluations agree or could not be
obtained with any precision, no decision is made. The numerical testing
is done only if ``wrt`` is different than the free symbols.
2) differentiation with respect to variables in 'wrt' (or all free
symbols if omitted) to see if the expression is constant or not. This
will not always lead to an expression that is zero even though an
expression is constant (see added test in test_expr.py). If
all derivatives are zero then self is constant with respect to the
given symbols.
3) finding out zeros of denominator expression with free_symbols.
It won't be constant if there are zeros. It gives more negative
answers for expression that are not constant.
If neither evaluation nor differentiation can prove the expression is
constant, None is returned unless two numerical values happened to be
the same and the flag ``failing_number`` is True -- in that case the
numerical value will be returned.
If flag simplify=False is passed, self will not be simplified;
the default is True since self should be simplified before testing.
Examples
========
>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
"""
def check_denominator_zeros(expression):
from sympy.solvers.solvers import denoms
retNone = False
for den in denoms(expression):
z = den.is_zero
if z is True:
return True
if z is None:
retNone = True
if retNone:
return None
return False
simplify = flags.get('simplify', True)
if self.is_number:
return True
free = self.free_symbols
if not free:
return True # assume f(1) is some constant
# if we are only interested in some symbols and they are not in the
# free symbols then this expression is constant wrt those symbols
wrt = set(wrt)
if wrt and not wrt & free:
return True
wrt = wrt or free
# simplify unless this has already been done
expr = self
if simplify:
expr = expr.simplify()
# is_zero should be a quick assumptions check; it can be wrong for
# numbers (see test_is_not_constant test), giving False when it
# shouldn't, but hopefully it will never give True unless it is sure.
if expr.is_zero:
return True
# try numerical evaluation to see if we get two different values
failing_number = None
if wrt == free:
# try 0 (for a) and 1 (for b)
try:
a = expr.subs(list(zip(free, [0]*len(free))),
simultaneous=True)
if a is S.NaN:
# evaluation may succeed when substitution fails
a = expr._random(None, 0, 0, 0, 0)
except ZeroDivisionError:
a = None
if a is not None and a is not S.NaN:
try:
b = expr.subs(list(zip(free, [1]*len(free))),
simultaneous=True)
if b is S.NaN:
# evaluation may succeed when substitution fails
b = expr._random(None, 1, 0, 1, 0)
except ZeroDivisionError:
b = None
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random real
b = expr._random(None, -1, 0, 1, 0)
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random complex
b = expr._random()
if b is not None and b is not S.NaN:
if b.equals(a) is False:
return False
failing_number = a if a.is_number else b
# now we will test each wrt symbol (or all free symbols) to see if the
# expression depends on them or not using differentiation. This is
# not sufficient for all expressions, however, so we don't return
# False if we get a derivative other than 0 with free symbols.
for w in wrt:
deriv = expr.diff(w)
if simplify:
deriv = deriv.simplify()
if deriv != 0:
if not (pure_complex(deriv, or_real=True)):
if flags.get('failing_number', False):
return failing_number
elif deriv.free_symbols:
# dead line provided _random returns None in such cases
return None
return False
cd = check_denominator_zeros(self)
if cd is True:
return False
elif cd is None:
return None
return True
def equals(self, other, failing_expression=False):
"""Return True if self == other, False if it doesn't, or None. If
failing_expression is True then the expression which did not simplify
to a 0 will be returned instead of None.
Explanation
===========
If ``self`` is a Number (or complex number) that is not zero, then
the result is False.
If ``self`` is a number and has not evaluated to zero, evalf will be
used to test whether the expression evaluates to zero. If it does so
and the result has significance (i.e. the precision is either -1, for
a Rational result, or is greater than 1) then the evalf value will be
used to return True or False.
"""
from sympy.simplify.simplify import nsimplify, simplify
from sympy.solvers.solvers import solve
from sympy.polys.polyerrors import NotAlgebraic
from sympy.polys.numberfields import minimal_polynomial
other = sympify(other)
if self == other:
return True
# they aren't the same so see if we can make the difference 0;
# don't worry about doing simplification steps one at a time
# because if the expression ever goes to 0 then the subsequent
# simplification steps that are done will be very fast.
diff = factor_terms(simplify(self - other), radical=True)
if not diff:
return True
if not diff.has(Add, Mod):
# if there is no expanding to be done after simplifying
# then this can't be a zero
return False
constant = diff.is_constant(simplify=False, failing_number=True)
if constant is False:
return False
if not diff.is_number:
if constant is None:
# e.g. unless the right simplification is done, a symbolic
# zero is possible (see expression of issue 6829: without
# simplification constant will be None).
return
if constant is True:
# this gives a number whether there are free symbols or not
ndiff = diff._random()
# is_comparable will work whether the result is real
# or complex; it could be None, however.
if ndiff and ndiff.is_comparable:
return False
# sometimes we can use a simplified result to give a clue as to
# what the expression should be; if the expression is *not* zero
# then we should have been able to compute that and so now
# we can just consider the cases where the approximation appears
# to be zero -- we try to prove it via minimal_polynomial.
#
# removed
# ns = nsimplify(diff)
# if diff.is_number and (not ns or ns == diff):
#
# The thought was that if it nsimplifies to 0 that's a sure sign
# to try the following to prove it; or if it changed but wasn't
# zero that might be a sign that it's not going to be easy to
# prove. But tests seem to be working without that logic.
#
if diff.is_number:
# try to prove via self-consistency
surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer]
# it seems to work better to try big ones first
surds.sort(key=lambda x: -x.args[0])
for s in surds:
try:
# simplify is False here -- this expression has already
# been identified as being hard to identify as zero;
# we will handle the checking ourselves using nsimplify
# to see if we are in the right ballpark or not and if so
# *then* the simplification will be attempted.
sol = solve(diff, s, simplify=False)
if sol:
if s in sol:
# the self-consistent result is present
return True
if all(si.is_Integer for si in sol):
# perfect powers are removed at instantiation
# so surd s cannot be an integer
return False
if all(i.is_algebraic is False for i in sol):
# a surd is algebraic
return False
if any(si in surds for si in sol):
# it wasn't equal to s but it is in surds
# and different surds are not equal
return False
if any(nsimplify(s - si) == 0 and
simplify(s - si) == 0 for si in sol):
return True
if s.is_real:
if any(nsimplify(si, [s]) == s and simplify(si) == s
for si in sol):
return True
except NotImplementedError:
pass
# try to prove with minimal_polynomial but know when
# *not* to use this or else it can take a long time. e.g. issue 8354
if True: # change True to condition that assures non-hang
try:
mp = minimal_polynomial(diff)
if mp.is_Symbol:
return True
return False
except (NotAlgebraic, NotImplementedError):
pass
# diff has not simplified to zero; constant is either None, True
# or the number with significance (is_comparable) that was randomly
# calculated twice as the same value.
if constant not in (True, None) and constant != 0:
return False
if failing_expression:
return diff
return None
def _eval_is_positive(self):
finite = self.is_finite
if finite is False:
return False
extended_positive = self.is_extended_positive
if finite is True:
return extended_positive
if extended_positive is False:
return False
def _eval_is_negative(self):
finite = self.is_finite
if finite is False:
return False
extended_negative = self.is_extended_negative
if finite is True:
return extended_negative
if extended_negative is False:
return False
def _eval_is_extended_positive_negative(self, positive):
from sympy.core.numbers import pure_complex
from sympy.polys.numberfields import minimal_polynomial
from sympy.polys.polyerrors import NotAlgebraic
if self.is_number:
if self.is_extended_real is False:
return False
# check to see that we can get a value
try:
n2 = self._eval_evalf(2)
# XXX: This shouldn't be caught here
# Catches ValueError: hypsum() failed to converge to the requested
# 34 bits of accuracy
except ValueError:
return None
if n2 is None:
return None
if getattr(n2, '_prec', 1) == 1: # no significance
return None
if n2 is S.NaN:
return None
f = self.evalf(2)
if f.is_Float:
match = f, S.Zero
else:
match = pure_complex(f)
if match is None:
return False
r, i = match
if not (i.is_Number and r.is_Number):
return False
if r._prec != 1 and i._prec != 1:
return bool(not i and ((r > 0) if positive else (r < 0)))
elif r._prec == 1 and (not i or i._prec == 1) and \
self.is_algebraic and not self.has(Function):
try:
if minimal_polynomial(self).is_Symbol:
return False
except (NotAlgebraic, NotImplementedError):
pass
def _eval_is_extended_positive(self):
return self._eval_is_extended_positive_negative(positive=True)
def _eval_is_extended_negative(self):
return self._eval_is_extended_positive_negative(positive=False)
def _eval_interval(self, x, a, b):
"""
Returns evaluation over an interval. For most functions this is:
self.subs(x, b) - self.subs(x, a),
possibly using limit() if NaN is returned from subs, or if
singularities are found between a and b.
If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
respectively.
"""
from sympy.series import limit, Limit
from sympy.solvers.solveset import solveset
from sympy.sets.sets import Interval
from sympy.functions.elementary.exponential import log
from sympy.calculus.util import AccumBounds
if (a is None and b is None):
raise ValueError('Both interval ends cannot be None.')
def _eval_endpoint(left):
c = a if left else b
if c is None:
return 0
else:
C = self.subs(x, c)
if C.has(S.NaN, S.Infinity, S.NegativeInfinity,
S.ComplexInfinity, AccumBounds):
if (a < b) != False:
C = limit(self, x, c, "+" if left else "-")
else:
C = limit(self, x, c, "-" if left else "+")
if isinstance(C, Limit):
raise NotImplementedError("Could not compute limit")
return C
if a == b:
return 0
A = _eval_endpoint(left=True)
if A is S.NaN:
return A
B = _eval_endpoint(left=False)
if (a and b) is None:
return B - A
value = B - A
if a.is_comparable and b.is_comparable:
if a < b:
domain = Interval(a, b)
else:
domain = Interval(b, a)
# check the singularities of self within the interval
# if singularities is a ConditionSet (not iterable), catch the exception and pass
singularities = solveset(self.cancel().as_numer_denom()[1], x,
domain=domain)
for logterm in self.atoms(log):
singularities = singularities | solveset(logterm.args[0], x,
domain=domain)
try:
for s in singularities:
if value is S.NaN:
# no need to keep adding, it will stay NaN
break
if not s.is_comparable:
continue
if (a < s) == (s < b) == True:
value += -limit(self, x, s, "+") + limit(self, x, s, "-")
elif (b < s) == (s < a) == True:
value += limit(self, x, s, "+") - limit(self, x, s, "-")
except TypeError:
pass
return value
def _eval_power(self, other):
# subclass to compute self**other for cases when
# other is not NaN, 0, or 1
return None
def _eval_conjugate(self):
if self.is_extended_real:
return self
elif self.is_imaginary:
return -self
def conjugate(self):
"""Returns the complex conjugate of 'self'."""
from sympy.functions.elementary.complexes import conjugate as c
return c(self)
def dir(self, x, cdir):
from sympy import log
minexp = S.Zero
if self.is_zero:
return S.Zero
arg = self
while arg:
minexp += S.One
arg = arg.diff(x)
coeff = arg.subs(x, 0)
if coeff in (S.NaN, S.ComplexInfinity):
try:
coeff, _ = arg.leadterm(x)
if coeff.has(log(x)):
raise ValueError()
except ValueError:
coeff = arg.limit(x, 0)
if coeff != S.Zero:
break
return coeff*cdir**minexp
def _eval_transpose(self):
from sympy.functions.elementary.complexes import conjugate
if (self.is_complex or self.is_infinite):
return self
elif self.is_hermitian:
return conjugate(self)
elif self.is_antihermitian:
return -conjugate(self)
def transpose(self):
from sympy.functions.elementary.complexes import transpose
return transpose(self)
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import conjugate, transpose
if self.is_hermitian:
return self
elif self.is_antihermitian:
return -self
obj = self._eval_conjugate()
if obj is not None:
return transpose(obj)
obj = self._eval_transpose()
if obj is not None:
return conjugate(obj)
def adjoint(self):
from sympy.functions.elementary.complexes import adjoint
return adjoint(self)
@classmethod
def _parse_order(cls, order):
"""Parse and configure the ordering of terms. """
from sympy.polys.orderings import monomial_key
startswith = getattr(order, "startswith", None)
if startswith is None:
reverse = False
else:
reverse = startswith('rev-')
if reverse:
order = order[4:]
monom_key = monomial_key(order)
def neg(monom):
result = []
for m in monom:
if isinstance(m, tuple):
result.append(neg(m))
else:
result.append(-m)
return tuple(result)
def key(term):
_, ((re, im), monom, ncpart) = term
monom = neg(monom_key(monom))
ncpart = tuple([e.sort_key(order=order) for e in ncpart])
coeff = ((bool(im), im), (re, im))
return monom, ncpart, coeff
return key, reverse
def as_ordered_factors(self, order=None):
"""Return list of ordered factors (if Mul) else [self]."""
return [self]
def as_poly(self, *gens, **args):
"""Converts ``self`` to a polynomial or returns ``None``.
Explanation
===========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
"""
from sympy.polys import Poly, PolynomialError
try:
poly = Poly(self, *gens, **args)
if not poly.is_Poly:
return None
else:
return poly
except PolynomialError:
return None
def as_ordered_terms(self, order=None, data=False):
"""
Transform an expression to an ordered list of terms.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
"""
from .numbers import Number, NumberSymbol
if order is None and self.is_Add:
# Spot the special case of Add(Number, Mul(Number, expr)) with the
# first number positive and thhe second number nagative
key = lambda x:not isinstance(x, (Number, NumberSymbol))
add_args = sorted(Add.make_args(self), key=key)
if (len(add_args) == 2
and isinstance(add_args[0], (Number, NumberSymbol))
and isinstance(add_args[1], Mul)):
mul_args = sorted(Mul.make_args(add_args[1]), key=key)
if (len(mul_args) == 2
and isinstance(mul_args[0], Number)
and add_args[0].is_positive
and mul_args[0].is_negative):
return add_args
key, reverse = self._parse_order(order)
terms, gens = self.as_terms()
if not any(term.is_Order for term, _ in terms):
ordered = sorted(terms, key=key, reverse=reverse)
else:
_terms, _order = [], []
for term, repr in terms:
if not term.is_Order:
_terms.append((term, repr))
else:
_order.append((term, repr))
ordered = sorted(_terms, key=key, reverse=True) \
+ sorted(_order, key=key, reverse=True)
if data:
return ordered, gens
else:
return [term for term, _ in ordered]
def as_terms(self):
"""Transform an expression to a list of terms. """
from .add import Add
from .mul import Mul
from .exprtools import decompose_power
gens, terms = set(), []
for term in Add.make_args(self):
coeff, _term = term.as_coeff_Mul()
coeff = complex(coeff)
cpart, ncpart = {}, []
if _term is not S.One:
for factor in Mul.make_args(_term):
if factor.is_number:
try:
coeff *= complex(factor)
except (TypeError, ValueError):
pass
else:
continue
if factor.is_commutative:
base, exp = decompose_power(factor)
cpart[base] = exp
gens.add(base)
else:
ncpart.append(factor)
coeff = coeff.real, coeff.imag
ncpart = tuple(ncpart)
terms.append((term, (coeff, cpart, ncpart)))
gens = sorted(gens, key=default_sort_key)
k, indices = len(gens), {}
for i, g in enumerate(gens):
indices[g] = i
result = []
for term, (coeff, cpart, ncpart) in terms:
monom = [0]*k
for base, exp in cpart.items():
monom[indices[base]] = exp
result.append((term, (coeff, tuple(monom), ncpart)))
return result, gens
def removeO(self):
"""Removes the additive O(..) symbol if there is one"""
return self
def getO(self):
"""Returns the additive O(..) symbol if there is one, else None."""
return None
def getn(self):
"""
Returns the order of the expression.
Explanation
===========
The order is determined either from the O(...) term. If there
is no O(...) term, it returns None.
Examples
========
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
"""
from sympy import Dummy, Symbol
o = self.getO()
if o is None:
return None
elif o.is_Order:
o = o.expr
if o is S.One:
return S.Zero
if o.is_Symbol:
return S.One
if o.is_Pow:
return o.args[1]
if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n
for oi in o.args:
if oi.is_Symbol:
return S.One
if oi.is_Pow:
syms = oi.atoms(Symbol)
if len(syms) == 1:
x = syms.pop()
oi = oi.subs(x, Dummy('x', positive=True))
if oi.base.is_Symbol and oi.exp.is_Rational:
return abs(oi.exp)
raise NotImplementedError('not sure of order of %s' % o)
def count_ops(self, visual=None):
"""wrapper for count_ops that returns the operation count."""
from .function import count_ops
return count_ops(self, visual)
def args_cnc(self, cset=False, warn=True, split_1=True):
"""Return [commutative factors, non-commutative factors] of self.
Explanation
===========
self is treated as a Mul and the ordering of the factors is maintained.
If ``cset`` is True the commutative factors will be returned in a set.
If there were repeated factors (as may happen with an unevaluated Mul)
then an error will be raised unless it is explicitly suppressed by
setting ``warn`` to False.
Note: -1 is always separated from a Number unless split_1 is False.
Examples
========
>>> from sympy import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*A*B*y).args_cnc(split_1=False)
[[-2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[{-1, 2, x, y}, []]
The arg is always treated as a Mul:
>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]
"""
if self.is_Mul:
args = list(self.args)
else:
args = [self]
for i, mi in enumerate(args):
if not mi.is_commutative:
c = args[:i]
nc = args[i:]
break
else:
c = args
nc = []
if c and split_1 and (
c[0].is_Number and
c[0].is_extended_negative and
c[0] is not S.NegativeOne):
c[:1] = [S.NegativeOne, -c[0]]
if cset:
clen = len(c)
c = set(c)
if clen and warn and len(c) != clen:
raise ValueError('repeated commutative arguments: %s' %
[ci for ci in c if list(self.args).count(ci) > 1])
return [c, nc]
def coeff(self, x, n=1, right=False):
"""
Returns the coefficient from the term(s) containing ``x**n``. If ``n``
is zero then all terms independent of ``x`` will be returned.
Explanation
===========
When ``x`` is noncommutative, the coefficient to the left (default) or
right of ``x`` can be returned. The keyword 'right' is ignored when
``x`` is commutative.
Examples
========
>>> from sympy import symbols
>>> from sympy.abc import x, y, z
You can select terms that have an explicit negative in front of them:
>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y
You can select terms with no Rational coefficient:
>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0
You can select terms independent of x by making n=0; in this case
expr.as_independent(x)[0] is returned (and 0 will be returned instead
of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
from the following:
>>> (x + z*(x + x*y)).coeff(x)
1
If such factoring is desired, factor_terms can be used first:
>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n)
0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1
See Also
========
as_coefficient: separate the expression into a coefficient and factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
x = sympify(x)
if not isinstance(x, Basic):
return S.Zero
n = as_int(n)
if not x:
return S.Zero
if x == self:
if n == 1:
return S.One
return S.Zero
if x is S.One:
co = [a for a in Add.make_args(self)
if a.as_coeff_Mul()[0] is S.One]
if not co:
return S.Zero
return Add(*co)
if n == 0:
if x.is_Add and self.is_Add:
c = self.coeff(x, right=right)
if not c:
return S.Zero
if not right:
return self - Add(*[a*x for a in Add.make_args(c)])
return self - Add(*[x*a for a in Add.make_args(c)])
return self.as_independent(x, as_Add=True)[0]
# continue with the full method, looking for this power of x:
x = x**n
def incommon(l1, l2):
if not l1 or not l2:
return []
n = min(len(l1), len(l2))
for i in range(n):
if l1[i] != l2[i]:
return l1[:i]
return l1[:]
def find(l, sub, first=True):
""" Find where list sub appears in list l. When ``first`` is True
the first occurrence from the left is returned, else the last
occurrence is returned. Return None if sub is not in l.
Examples
========
>> l = range(5)*2
>> find(l, [2, 3])
2
>> find(l, [2, 3], first=0)
7
>> find(l, [2, 4])
None
"""
if not sub or not l or len(sub) > len(l):
return None
n = len(sub)
if not first:
l.reverse()
sub.reverse()
for i in range(0, len(l) - n + 1):
if all(l[i + j] == sub[j] for j in range(n)):
break
else:
i = None
if not first:
l.reverse()
sub.reverse()
if i is not None and not first:
i = len(l) - (i + n)
return i
co = []
args = Add.make_args(self)
self_c = self.is_commutative
x_c = x.is_commutative
if self_c and not x_c:
return S.Zero
one_c = self_c or x_c
xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c))
# find the parts that pass the commutative terms
for a in args:
margs, nc = a.args_cnc(cset=True, warn=bool(not self_c))
if nc is None:
nc = []
if len(xargs) > len(margs):
continue
resid = margs.difference(xargs)
if len(resid) + len(xargs) == len(margs):
if one_c:
co.append(Mul(*(list(resid) + nc)))
else:
co.append((resid, nc))
if one_c:
if co == []:
return S.Zero
elif co:
return Add(*co)
else: # both nc
# now check the non-comm parts
if not co:
return S.Zero
if all(n == co[0][1] for r, n in co):
ii = find(co[0][1], nx, right)
if ii is not None:
if not right:
return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii]))
else:
return Mul(*co[0][1][ii + len(nx):])
beg = reduce(incommon, (n[1] for n in co))
if beg:
ii = find(beg, nx, right)
if ii is not None:
if not right:
gcdc = co[0][0]
for i in range(1, len(co)):
gcdc = gcdc.intersection(co[i][0])
if not gcdc:
break
return Mul(*(list(gcdc) + beg[:ii]))
else:
m = ii + len(nx)
return Add(*[Mul(*(list(r) + n[m:])) for r, n in co])
end = list(reversed(
reduce(incommon, (list(reversed(n[1])) for n in co))))
if end:
ii = find(end, nx, right)
if ii is not None:
if not right:
return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co])
else:
return Mul(*end[ii + len(nx):])
# look for single match
hit = None
for i, (r, n) in enumerate(co):
ii = find(n, nx, right)
if ii is not None:
if not hit:
hit = ii, r, n
else:
break
else:
if hit:
ii, r, n = hit
if not right:
return Mul(*(list(r) + n[:ii]))
else:
return Mul(*n[ii + len(nx):])
return S.Zero
def as_expr(self, *gens):
"""
Convert a polynomial to a SymPy expression.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y
>>> sin(x).as_expr()
sin(x)
"""
return self
def as_coefficient(self, expr):
"""
Extracts symbolic coefficient at the given expression. In
other words, this functions separates 'self' into the product
of 'expr' and 'expr'-free coefficient. If such separation
is not possible it will return None.
Examples
========
>>> from sympy import E, pi, sin, I, Poly
>>> from sympy.abc import x
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
Two terms have E in them so a sum is returned. (If one were
desiring the coefficient of the term exactly matching E then
the constant from the returned expression could be selected.
Or, for greater precision, a method of Poly can be used to
indicate the desired term from which the coefficient is
desired.)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> _.args[0] # just want the exact match
2
>>> p = Poly(2*E + x*E); p
Poly(x*E + 2*E, x, E, domain='ZZ')
>>> p.coeff_monomial(E)
2
>>> p.nth(0, 1)
2
Since the following cannot be written as a product containing
E as a factor, None is returned. (If the coefficient ``2*x`` is
desired then the ``coeff`` method should be used.)
>>> (2*E*x + x).as_coefficient(E)
>>> (2*E*x + x).coeff(E)
2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
See Also
========
coeff: return sum of terms have a given factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
r = self.extract_multiplicatively(expr)
if r and not r.has(expr):
return r
def as_independent(self, *deps, **hint):
"""
A mostly naive separation of a Mul or Add into arguments that are not
are dependent on deps. To obtain as complete a separation of variables
as possible, use a separation method first, e.g.:
* separatevars() to change Mul, Add and Pow (including exp) into Mul
* .expand(mul=True) to change Add or Mul into Add
* .expand(log=True) to change log expr into an Add
The only non-naive thing that is done here is to respect noncommutative
ordering of variables and to always return (0, 0) for `self` of zero
regardless of hints.
For nonzero `self`, the returned tuple (i, d) has the
following interpretation:
* i will has no variable that appears in deps
* d will either have terms that contain variables that are in deps, or
be equal to 0 (when self is an Add) or 1 (when self is a Mul)
* if self is an Add then self = i + d
* if self is a Mul then self = i*d
* otherwise (self, S.One) or (S.One, self) is returned.
To force the expression to be treated as an Add, use the hint as_Add=True
Examples
========
-- self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.abc import x, y, z
>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)
-- self is a Mul
>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))
non-commutative terms cannot always be separated out when self is a Mul
>>> from sympy import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))
-- self is anything else:
>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))
-- force self to be treated as an Add:
>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)
-- force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=False)
(1, x - 3)
Note how the below differs from the above in making the
constant on the dep term positive.
>>> (y*(-3+x)).as_independent(x)
(y, x - 3)
-- use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free
symbols while the latter considers all symbols
>>> from sympy import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True
Note: when trying to get independent terms, a separation method
might need to be used first. In this case, it is important to keep
track of what you send to this routine so you know how to interpret
the returned values
>>> from sympy import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b', positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))
See Also
========
.separatevars(), .expand(log=True), sympy.core.add.Add.as_two_terms(),
sympy.core.mul.Mul.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
"""
from .symbol import Symbol
from .add import _unevaluated_Add
from .mul import _unevaluated_Mul
from sympy.utilities.iterables import sift
if self.is_zero:
return S.Zero, S.Zero
func = self.func
if hint.get('as_Add', isinstance(self, Add) ):
want = Add
else:
want = Mul
# sift out deps into symbolic and other and ignore
# all symbols but those that are in the free symbols
sym = set()
other = []
for d in deps:
if isinstance(d, Symbol): # Symbol.is_Symbol is True
sym.add(d)
else:
other.append(d)
def has(e):
"""return the standard has() if there are no literal symbols, else
check to see that symbol-deps are in the free symbols."""
has_other = e.has(*other)
if not sym:
return has_other
return has_other or e.has(*(e.free_symbols & sym))
if (want is not func or
func is not Add and func is not Mul):
if has(self):
return (want.identity, self)
else:
return (self, want.identity)
else:
if func is Add:
args = list(self.args)
else:
args, nc = self.args_cnc()
d = sift(args, lambda x: has(x))
depend = d[True]
indep = d[False]
if func is Add: # all terms were treated as commutative
return (Add(*indep), _unevaluated_Add(*depend))
else: # handle noncommutative by stopping at first dependent term
for i, n in enumerate(nc):
if has(n):
depend.extend(nc[i:])
break
indep.append(n)
return Mul(*indep), (
Mul(*depend, evaluate=False) if nc else
_unevaluated_Mul(*depend))
def as_real_imag(self, deep=True, **hints):
"""Performs complex expansion on 'self' and returns a tuple
containing collected both real and imaginary parts. This
method can't be confused with re() and im() functions,
which does not perform complex expansion at evaluation.
However it is possible to expand both re() and im()
functions and get exactly the same results as with
a single call to this function.
>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
"""
from sympy import im, re
if hints.get('ignore') == self:
return None
else:
return (re(self), im(self))
def as_powers_dict(self):
"""Return self as a dictionary of factors with each factor being
treated as a power. The keys are the bases of the factors and the
values, the corresponding exponents. The resulting dictionary should
be used with caution if the expression is a Mul and contains non-
commutative factors since the order that they appeared will be lost in
the dictionary.
See Also
========
as_ordered_factors: An alternative for noncommutative applications,
returning an ordered list of factors.
args_cnc: Similar to as_ordered_factors, but guarantees separation
of commutative and noncommutative factors.
"""
d = defaultdict(int)
d.update(dict([self.as_base_exp()]))
return d
def as_coefficients_dict(self):
"""Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. If an expression is
not an Add it is considered to have a single term.
Examples
========
>>> from sympy.abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
"""
c, m = self.as_coeff_Mul()
if not c.is_Rational:
c = S.One
m = self
d = defaultdict(int)
d.update({m: c})
return d
def as_base_exp(self):
# a -> b ** e
return self, S.One
def as_coeff_mul(self, *deps, **kwargs):
"""Return the tuple (c, args) where self is written as a Mul, ``m``.
c should be a Rational multiplied by any factors of the Mul that are
independent of deps.
args should be a tuple of all other factors of m; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you don't know if self is a Mul or not but
you want to treat self as a Mul or if you want to process the
individual arguments of the tail of self as a Mul.
- if you know self is a Mul and want only the head, use self.args[0];
- if you don't want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail;
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
"""
if deps:
if not self.has(*deps):
return self, tuple()
return S.One, (self,)
def as_coeff_add(self, *deps):
"""Return the tuple (c, args) where self is written as an Add, ``a``.
c should be a Rational added to any terms of the Add that are
independent of deps.
args should be a tuple of all other terms of ``a``; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you don't know if self is an Add or not but
you want to treat self as an Add or if you want to process the
individual arguments of the tail of self as an Add.
- if you know self is an Add and want only the head, use self.args[0];
- if you don't want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail.
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
"""
if deps:
if not self.has(*deps):
return self, tuple()
return S.Zero, (self,)
def primitive(self):
"""Return the positive Rational that can be extracted non-recursively
from every term of self (i.e., self is treated like an Add). This is
like the as_coeff_Mul() method but primitive always extracts a positive
Rational (never a negative or a Float).
Examples
========
>>> from sympy.abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True
"""
if not self:
return S.One, S.Zero
c, r = self.as_coeff_Mul(rational=True)
if c.is_negative:
c, r = -c, -r
return c, r
def as_content_primitive(self, radical=False, clear=True):
"""This method should recursively remove a Rational from all arguments
and return that (content) and the new self (primitive). The content
should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
The primitive need not be in canonical form and should try to preserve
the underlying structure if possible (i.e. expand_mul should not be
applied to self).
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
The as_content_primitive function is recursive and retains structure:
>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)
Integer powers will have Rationals extracted from the base:
>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))
Terms may end up joining once their as_content_primitives are added:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
(1, 4.84*x**2*(y + 1)**2)
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))
If clear=False (default is True) then content will not be removed
from an Add if it can be distributed to leave one or more
terms with integer coefficients.
>>> (x/2 + y).as_content_primitive()
(1/2, x + 2*y)
>>> (x/2 + y).as_content_primitive(clear=False)
(1, x/2 + y)
"""
return S.One, self
def as_numer_denom(self):
""" expression -> a/b -> a, b
This is just a stub that should be defined by
an object's class methods to get anything else.
See Also
========
normal: return ``a/b`` instead of ``(a, b)``
"""
return self, S.One
def normal(self):
""" expression -> a/b
See Also
========
as_numer_denom: return ``(a, b)`` instead of ``a/b``
"""
from .mul import _unevaluated_Mul
n, d = self.as_numer_denom()
if d is S.One:
return n
if d.is_Number:
return _unevaluated_Mul(n, 1/d)
else:
return n/d
def extract_multiplicatively(self, c):
"""Return None if it's not possible to make self in the form
c * something in a nice way, i.e. preserving the properties
of arguments of self.
Examples
========
>>> from sympy import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2)
x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3)
x/6
"""
from .add import _unevaluated_Add
c = sympify(c)
if self is S.NaN:
return None
if c is S.One:
return self
elif c == self:
return S.One
if c.is_Add:
cc, pc = c.primitive()
if cc is not S.One:
c = Mul(cc, pc, evaluate=False)
if c.is_Mul:
a, b = c.as_two_terms()
x = self.extract_multiplicatively(a)
if x is not None:
return x.extract_multiplicatively(b)
else:
return x
quotient = self / c
if self.is_Number:
if self is S.Infinity:
if c.is_positive:
return S.Infinity
elif self is S.NegativeInfinity:
if c.is_negative:
return S.Infinity
elif c.is_positive:
return S.NegativeInfinity
elif self is S.ComplexInfinity:
if not c.is_zero:
return S.ComplexInfinity
elif self.is_Integer:
if not quotient.is_Integer:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Rational:
if not quotient.is_Rational:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Float:
if not quotient.is_Float:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
if quotient.is_Mul and len(quotient.args) == 2:
if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self:
return quotient
elif quotient.is_Integer and c.is_Number:
return quotient
elif self.is_Add:
cs, ps = self.primitive()
# assert cs >= 1
if c.is_Number and c is not S.NegativeOne:
# assert c != 1 (handled at top)
if cs is not S.One:
if c.is_negative:
xc = -(cs.extract_multiplicatively(-c))
else:
xc = cs.extract_multiplicatively(c)
if xc is not None:
return xc*ps # rely on 2-arg Mul to restore Add
return # |c| != 1 can only be extracted from cs
if c == ps:
return cs
# check args of ps
newargs = []
for arg in ps.args:
newarg = arg.extract_multiplicatively(c)
if newarg is None:
return # all or nothing
newargs.append(newarg)
if cs is not S.One:
args = [cs*t for t in newargs]
# args may be in different order
return _unevaluated_Add(*args)
else:
return Add._from_args(newargs)
elif self.is_Mul:
args = list(self.args)
for i, arg in enumerate(args):
newarg = arg.extract_multiplicatively(c)
if newarg is not None:
args[i] = newarg
return Mul(*args)
elif self.is_Pow:
if c.is_Pow and c.base == self.base:
new_exp = self.exp.extract_additively(c.exp)
if new_exp is not None:
return self.base ** (new_exp)
elif c == self.base:
new_exp = self.exp.extract_additively(1)
if new_exp is not None:
return self.base ** (new_exp)
def extract_additively(self, c):
"""Return self - c if it's possible to subtract c from self and
make all matching coefficients move towards zero, else return None.
Examples
========
>>> from sympy.abc import x, y
>>> e = 2*x + 3
>>> e.extract_additively(x + 1)
x + 2
>>> e.extract_additively(3*x)
>>> e.extract_additively(4)
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3
Sometimes auto-expansion will return a less simplified result
than desired; gcd_terms might be used in such cases:
>>> from sympy import gcd_terms
>>> (4*x*(y + 1) + y).extract_additively(x)
4*x*(y + 1) + x*(4*y + 3) - x*(4*y + 4) + y
>>> gcd_terms(_)
x*(4*y + 3) + y
See Also
========
extract_multiplicatively
coeff
as_coefficient
"""
c = sympify(c)
if self is S.NaN:
return None
if c.is_zero:
return self
elif c == self:
return S.Zero
elif self == S.Zero:
return None
if self.is_Number:
if not c.is_Number:
return None
co = self
diff = co - c
# XXX should we match types? i.e should 3 - .1 succeed?
if (co > 0 and diff > 0 and diff < co or
co < 0 and diff < 0 and diff > co):
return diff
return None
if c.is_Number:
co, t = self.as_coeff_Add()
xa = co.extract_additively(c)
if xa is None:
return None
return xa + t
# handle the args[0].is_Number case separately
# since we will have trouble looking for the coeff of
# a number.
if c.is_Add and c.args[0].is_Number:
# whole term as a term factor
co = self.coeff(c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
diff = self - co*c
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
h, t = c.as_coeff_Add()
sh, st = self.as_coeff_Add()
xa = sh.extract_additively(h)
if xa is None:
return None
xa2 = st.extract_additively(t)
if xa2 is None:
return None
return xa + xa2
# whole term as a term factor
co = self.coeff(c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
diff = self - co*c
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
coeffs = []
for a in Add.make_args(c):
ac, at = a.as_coeff_Mul()
co = self.coeff(at)
if not co:
return None
coc, cot = co.as_coeff_Add()
xa = coc.extract_additively(ac)
if xa is None:
return None
self -= co*at
coeffs.append((cot + xa)*at)
coeffs.append(self)
return Add(*coeffs)
@property
def expr_free_symbols(self):
"""
Like ``free_symbols``, but returns the free symbols only if they are contained in an expression node.
Examples
========
>>> from sympy.abc import x, y
>>> (x + y).expr_free_symbols
{x, y}
If the expression is contained in a non-expression object, don't return
the free symbols. Compare:
>>> from sympy import Tuple
>>> t = Tuple(x + y)
>>> t.expr_free_symbols
set()
>>> t.free_symbols
{x, y}
"""
return {j for i in self.args for j in i.expr_free_symbols}
def could_extract_minus_sign(self):
"""Return True if self is not in a canonical form with respect
to its sign.
For most expressions, e, there will be a difference in e and -e.
When there is, True will be returned for one and False for the
other; False will be returned if there is no difference.
Examples
========
>>> from sympy.abc import x, y
>>> e = x - y
>>> {i.could_extract_minus_sign() for i in (e, -e)}
{False, True}
"""
negative_self = -self
if self == negative_self:
return False # e.g. zoo*x == -zoo*x
self_has_minus = (self.extract_multiplicatively(-1) is not None)
negative_self_has_minus = (
(negative_self).extract_multiplicatively(-1) is not None)
if self_has_minus != negative_self_has_minus:
return self_has_minus
else:
if self.is_Add:
# We choose the one with less arguments with minus signs
all_args = len(self.args)
negative_args = len([False for arg in self.args if arg.could_extract_minus_sign()])
positive_args = all_args - negative_args
if positive_args > negative_args:
return False
elif positive_args < negative_args:
return True
elif self.is_Mul:
# We choose the one with an odd number of minus signs
num, den = self.as_numer_denom()
args = Mul.make_args(num) + Mul.make_args(den)
arg_signs = [arg.could_extract_minus_sign() for arg in args]
negative_args = list(filter(None, arg_signs))
return len(negative_args) % 2 == 1
# As a last resort, we choose the one with greater value of .sort_key()
return bool(self.sort_key() < negative_self.sort_key())
def extract_branch_factor(self, allow_half=False):
"""
Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
Return (z, n).
>>> from sympy import exp_polar, I, pi
>>> from sympy.abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)
If allow_half is True, also extract exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)
"""
from sympy import exp_polar, pi, I, ceiling, Add
n = S.Zero
res = S.One
args = Mul.make_args(self)
exps = []
for arg in args:
if isinstance(arg, exp_polar):
exps += [arg.exp]
else:
res *= arg
piimult = S.Zero
extras = []
while exps:
exp = exps.pop()
if exp.is_Add:
exps += exp.args
continue
if exp.is_Mul:
coeff = exp.as_coefficient(pi*I)
if coeff is not None:
piimult += coeff
continue
extras += [exp]
if piimult.is_number:
coeff = piimult
tail = ()
else:
coeff, tail = piimult.as_coeff_add(*piimult.free_symbols)
# round down to nearest multiple of 2
branchfact = ceiling(coeff/2 - S.Half)*2
n += branchfact/2
c = coeff - branchfact
if allow_half:
nc = c.extract_additively(1)
if nc is not None:
n += S.Half
c = nc
newexp = pi*I*Add(*((c, ) + tail)) + Add(*extras)
if newexp != 0:
res *= exp_polar(newexp)
return res, n
def _eval_is_polynomial(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_polynomial(self, *syms):
r"""
Return True if self is a polynomial in syms and False otherwise.
This checks if self is an exact polynomial in syms. This function
returns False for expressions that are "polynomials" with symbolic
exponents. Thus, you should be able to apply polynomial algorithms to
expressions for which this returns True, and Poly(expr, \*syms) should
work if and only if expr.is_polynomial(\*syms) returns True. The
polynomial does not have to be in expanded form. If no symbols are
given, all free symbols in the expression will be used.
This is not part of the assumptions system. You cannot do
Symbol('z', polynomial=True).
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False
>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a polynomial to
become one.
>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True
>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True
See also .is_rational_function()
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant polynomial
return True
else:
return self._eval_is_polynomial(syms)
def _eval_is_rational_function(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_rational_function(self, *syms):
"""
Test whether function is a ratio of two polynomials in the given
symbols, syms. When syms is not given, all free symbols will be used.
The rational function does not have to be in expanded or in any kind of
canonical form.
This function returns False for expressions that are "rational
functions" with symbolic exponents. Thus, you should be able to call
.as_numer_denom() and apply polynomial algorithms to the result for
expressions for which this returns True.
This is not part of the assumptions system. You cannot do
Symbol('z', rational_function=True).
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.abc import x, y
>>> (x/y).is_rational_function()
True
>>> (x**2).is_rational_function()
True
>>> (x/sin(y)).is_rational_function(y)
False
>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a rational function
to become one.
>>> from sympy import sqrt, factor
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True
See also is_algebraic_expr().
"""
if self in [S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
return False
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant rational function
return True
else:
return self._eval_is_rational_function(syms)
def _eval_is_meromorphic(self, x, a):
# Default implementation, return True for constants.
return None if self.has(x) else True
def is_meromorphic(self, x, a):
"""
This tests whether an expression is meromorphic as
a function of the given symbol ``x`` at the point ``a``.
This method is intended as a quick test that will return
None if no decision can be made without simplification or
more detailed analysis.
Examples
========
>>> from sympy import zoo, log, sin, sqrt
>>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3
>>> f.is_meromorphic(x, 0)
True
>>> f.is_meromorphic(x, 1)
True
>>> f.is_meromorphic(x, zoo)
True
>>> g = x**log(3)
>>> g.is_meromorphic(x, 0)
False
>>> g.is_meromorphic(x, 1)
True
>>> g.is_meromorphic(x, zoo)
False
>>> h = sin(1/x)*x**2
>>> h.is_meromorphic(x, 0)
False
>>> h.is_meromorphic(x, 1)
True
>>> h.is_meromorphic(x, zoo)
True
Multivalued functions are considered meromorphic when their
branches are meromorphic. Thus most functions are meromorphic
everywhere except at essential singularities and branch points.
In particular, they will be meromorphic also on branch cuts
except at their endpoints.
>>> log(x).is_meromorphic(x, -1)
True
>>> log(x).is_meromorphic(x, 0)
False
>>> sqrt(x).is_meromorphic(x, -1)
True
>>> sqrt(x).is_meromorphic(x, 0)
False
"""
if not x.is_symbol:
raise TypeError("{} should be of symbol type".format(x))
a = sympify(a)
return self._eval_is_meromorphic(x, a)
def _eval_is_algebraic_expr(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_algebraic_expr(self, *syms):
"""
This tests whether a given expression is algebraic or not, in the
given symbols, syms. When syms is not given, all free symbols
will be used. The rational function does not have to be in expanded
or in any kind of canonical form.
This function returns False for expressions that are "algebraic
expressions" with symbolic exponents. This is a simple extension to the
is_rational_function, including rational exponentiation.
Examples
========
>>> from sympy import Symbol, sqrt
>>> x = Symbol('x', real=True)
>>> sqrt(1 + x).is_rational_function()
False
>>> sqrt(1 + x).is_algebraic_expr()
True
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be an algebraic
expression to become one.
>>> from sympy import exp, factor
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
>>> a.is_algebraic_expr(x)
False
>>> factor(a).is_algebraic_expr()
True
See Also
========
is_rational_function()
References
==========
- https://en.wikipedia.org/wiki/Algebraic_expression
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant algebraic expression
return True
else:
return self._eval_is_algebraic_expr(syms)
###################################################################################
##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ##################
###################################################################################
def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0):
"""
Series expansion of "self" around ``x = x0`` yielding either terms of
the series one by one (the lazy series given when n=None), else
all the terms at once when n != None.
Returns the series expansion of "self" around the point ``x = x0``
with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).
If ``x=None`` and ``self`` is univariate, the univariate symbol will
be supplied, otherwise an error will be raised.
Parameters
==========
expr : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
x0 : Value
The value around which ``x`` is calculated. Can be any value
from ``-oo`` to ``oo``.
n : Value
The number of terms upto which the series is to be expanded.
dir : String, optional
The series-expansion can be bi-directional. If ``dir="+"``,
then (x->x0+). If ``dir="-", then (x->x0-). For infinite
``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
from the direction of the infinity (i.e., ``dir="-"`` for
``oo``).
logx : optional
It is used to replace any log(x) in the returned series with a
symbolic value rather than evaluating the actual value.
cdir : optional
It stands for complex direction, and indicates the direction
from which the expansion needs to be evaluated.
Examples
========
>>> from sympy import cos, exp, tan
>>> from sympy.abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> cos(x).series(x, x0=1, n=2)
cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)
If ``n=None`` then a generator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [next(term) for i in range(2)]
[1, -x**2/2]
For ``dir=+`` (default) the series is calculated from the right and
for ``dir=-`` the series from the left. For smooth functions this
flag will not alter the results.
>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x
>>> f = tan(x)
>>> f.series(x, 2, 6, "+")
tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
(x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-")
tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
+ O((x - 2)**3, (x, 2))
Returns
=======
Expr : Expression
Series expansion of the expression about x0
Raises
======
TypeError
If "n" and "x0" are infinity objects
PoleError
If "x0" is an infinity object
"""
from sympy import collect, Dummy, Order, Rational, Symbol, ceiling
if x is None:
syms = self.free_symbols
if not syms:
return self
elif len(syms) > 1:
raise ValueError('x must be given for multivariate functions.')
x = syms.pop()
if isinstance(x, Symbol):
dep = x in self.free_symbols
else:
d = Dummy()
dep = d in self.xreplace({x: d}).free_symbols
if not dep:
if n is None:
return (s for s in [self])
else:
return self
if len(dir) != 1 or dir not in '+-':
raise ValueError("Dir must be '+' or '-'")
if x0 in [S.Infinity, S.NegativeInfinity]:
sgn = 1 if x0 is S.Infinity else -1
s = self.subs(x, sgn/x).series(x, n=n, dir='+', cdir=cdir)
if n is None:
return (si.subs(x, sgn/x) for si in s)
return s.subs(x, sgn/x)
# use rep to shift origin to x0 and change sign (if dir is negative)
# and undo the process with rep2
if x0 or dir == '-':
if dir == '-':
rep = -x + x0
rep2 = -x
rep2b = x0
else:
rep = x + x0
rep2 = x
rep2b = -x0
s = self.subs(x, rep).series(x, x0=0, n=n, dir='+', logx=logx, cdir=cdir)
if n is None: # lseries...
return (si.subs(x, rep2 + rep2b) for si in s)
return s.subs(x, rep2 + rep2b)
# from here on it's x0=0 and dir='+' handling
if x.is_positive is x.is_negative is None or x.is_Symbol is not True:
# replace x with an x that has a positive assumption
xpos = Dummy('x', positive=True, finite=True)
rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir)
if n is None:
return (s.subs(xpos, x) for s in rv)
else:
return rv.subs(xpos, x)
if n is not None: # nseries handling
s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
o = s1.getO() or S.Zero
if o:
# make sure the requested order is returned
ngot = o.getn()
if ngot > n:
# leave o in its current form (e.g. with x*log(x)) so
# it eats terms properly, then replace it below
if n != 0:
s1 += o.subs(x, x**Rational(n, ngot))
else:
s1 += Order(1, x)
elif ngot < n:
# increase the requested number of terms to get the desired
# number keep increasing (up to 9) until the received order
# is different than the original order and then predict how
# many additional terms are needed
for more in range(1, 9):
s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir)
newn = s1.getn()
if newn != ngot:
ndo = n + ceiling((n - ngot)*more/(newn - ngot))
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
while s1.getn() < n:
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
ndo += 1
break
else:
raise ValueError('Could not calculate %s terms for %s'
% (str(n), self))
s1 += Order(x**n, x)
o = s1.getO()
s1 = s1.removeO()
else:
o = Order(x**n, x)
s1done = s1.doit()
if (s1done + o).removeO() == s1done:
o = S.Zero
try:
return collect(s1, x) + o
except NotImplementedError:
return s1 + o
else: # lseries handling
def yield_lseries(s):
"""Return terms of lseries one at a time."""
for si in s:
if not si.is_Add:
yield si
continue
# yield terms 1 at a time if possible
# by increasing order until all the
# terms have been returned
yielded = 0
o = Order(si, x)*x
ndid = 0
ndo = len(si.args)
while 1:
do = (si - yielded + o).removeO()
o *= x
if not do or do.is_Order:
continue
if do.is_Add:
ndid += len(do.args)
else:
ndid += 1
yield do
if ndid == ndo:
break
yielded += do
return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir))
def aseries(self, x=None, n=6, bound=0, hir=False):
"""Asymptotic Series expansion of self.
This is equivalent to ``self.series(x, oo, n)``.
Parameters
==========
self : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
n : Value
The number of terms upto which the series is to be expanded.
hir : Boolean
Set this parameter to be True to produce hierarchical series.
It stops the recursion at an early level and may provide nicer
and more useful results.
bound : Value, Integer
Use the ``bound`` parameter to give limit on rewriting
coefficients in its normalised form.
Examples
========
>>> from sympy import sin, exp
>>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x)
(1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True)
-exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x)
exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3)
exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
Returns
=======
Expr
Asymptotic series expansion of the expression.
Notes
=====
This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
to look for the most rapidly varying subexpression w of a given expression f and then expands f
in a series in w. Then same thing is recursively done on the leading coefficient
till we get constant coefficients.
If the most rapidly varying subexpression of a given expression f is f itself,
the algorithm tries to find a normalised representation of the mrv set and rewrites f
using this normalised representation.
If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
where ``w`` belongs to the most rapidly varying expression of ``self``.
References
==========
.. [1] A New Algorithm for Computing Asymptotic Series - Dominik Gruntz
.. [2] Gruntz thesis - p90
.. [3] http://en.wikipedia.org/wiki/Asymptotic_expansion
See Also
========
Expr.aseries: See the docstring of this function for complete details of this wrapper.
"""
from sympy import Order, Dummy
from sympy.functions import exp, log
from sympy.series.gruntz import mrv, rewrite
if x.is_positive is x.is_negative is None:
xpos = Dummy('x', positive=True)
return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x)
om, exps = mrv(self, x)
# We move one level up by replacing `x` by `exp(x)`, and then
# computing the asymptotic series for f(exp(x)). Then asymptotic series
# can be obtained by moving one-step back, by replacing x by ln(x).
if x in om:
s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x))
if s.getO():
return s + Order(1/x**n, (x, S.Infinity))
return s
k = Dummy('k', positive=True)
# f is rewritten in terms of omega
func, logw = rewrite(exps, om, x, k)
if self in om:
if bound <= 0:
return self
s = (self.exp).aseries(x, n, bound=bound)
s = s.func(*[t.removeO() for t in s.args])
res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
func = exp(self.args[0] - res.args[0]) / k
logw = log(1/res)
s = func.series(k, 0, n)
# Hierarchical series
if hir:
return s.subs(k, exp(logw))
o = s.getO()
terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1]))
s = S.Zero
has_ord = False
# Then we recursively expand these coefficients one by one into
# their asymptotic series in terms of their most rapidly varying subexpressions.
for t in terms:
coeff, expo = t.as_coeff_exponent(k)
if coeff.has(x):
# Recursive step
snew = coeff.aseries(x, n, bound=bound-1)
if has_ord and snew.getO():
break
elif snew.getO():
has_ord = True
s += (snew * k**expo)
else:
s += t
if not o or has_ord:
return s.subs(k, exp(logw))
return (s + o).subs(k, exp(logw))
def taylor_term(self, n, x, *previous_terms):
"""General method for the taylor term.
This method is slow, because it differentiates n-times. Subclasses can
redefine it to make it faster by using the "previous_terms".
"""
from sympy import Dummy, factorial
x = sympify(x)
_x = Dummy('x')
return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n)
def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0):
"""
Wrapper for series yielding an iterator of the terms of the series.
Note: an infinite series will yield an infinite iterator. The following,
for exaxmple, will never terminate. It will just keep printing terms
of the sin(x) series::
for term in sin(x).lseries(x):
print term
The advantage of lseries() over nseries() is that many times you are
just interested in the next term in the series (i.e. the first term for
example), but you don't know how many you should ask for in nseries()
using the "n" parameter.
See also nseries().
"""
return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir)
def _eval_lseries(self, x, logx=None, cdir=0):
# default implementation of lseries is using nseries(), and adaptively
# increasing the "n". As you can see, it is not very efficient, because
# we are calculating the series over and over again. Subclasses should
# override this method and implement much more efficient yielding of
# terms.
n = 0
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
while series.is_Order:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
e = series.removeO()
yield e
if e is S.Zero:
return
while 1:
while 1:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO()
if e != series:
break
if (series - self).cancel() is S.Zero:
return
yield series - e
e = series
def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0):
"""
Wrapper to _eval_nseries if assumptions allow, else to series.
If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
called. This calculates "n" terms in the innermost expressions and
then builds up the final series just by "cross-multiplying" everything
out.
The optional ``logx`` parameter can be used to replace any log(x) in the
returned series with a symbolic value to avoid evaluating log(x) at 0. A
symbol to use in place of log(x) should be provided.
Advantage -- it's fast, because we don't have to determine how many
terms we need to calculate in advance.
Disadvantage -- you may end up with less terms than you may have
expected, but the O(x**n) term appended will always be correct and
so the result, though perhaps shorter, will also be correct.
If any of those assumptions is not met, this is treated like a
wrapper to series which will try harder to return the correct
number of terms.
See also lseries().
Examples
========
>>> from sympy import sin, log, Symbol
>>> from sympy.abc import x, y
>>> sin(x).nseries(x, 0, 6)
x - x**3/6 + x**5/120 + O(x**6)
>>> log(x+1).nseries(x, 0, 5)
x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
Handling of the ``logx`` parameter --- in the following example the
expansion fails since ``sin`` does not have an asymptotic expansion
at -oo (the limit of log(x) as x approaches 0):
>>> e = sin(log(x))
>>> e.nseries(x, 0, 6)
Traceback (most recent call last):
...
PoleError: ...
...
>>> logx = Symbol('logx')
>>> e.nseries(x, 0, 6, logx=logx)
sin(logx)
In the following example, the expansion works but gives only an Order term
unless the ``logx`` parameter is used:
>>> e = x**y
>>> e.nseries(x, 0, 2)
O(log(x)**2)
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
"""
if x and not x in self.free_symbols:
return self
if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None):
return self.series(x, x0, n, dir, cdir=cdir)
else:
return self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir):
"""
Return terms of series for self up to O(x**n) at x=0
from the positive direction.
This is a method that should be overridden in subclasses. Users should
never call this method directly (use .nseries() instead), so you don't
have to write docstrings for _eval_nseries().
"""
from sympy.utilities.misc import filldedent
raise NotImplementedError(filldedent("""
The _eval_nseries method should be added to
%s to give terms up to O(x**n) at x=0
from the positive direction so it is available when
nseries calls it.""" % self.func)
)
def limit(self, x, xlim, dir='+'):
""" Compute limit x->xlim.
"""
from sympy.series.limits import limit
return limit(self, x, xlim, dir)
def compute_leading_term(self, x, logx=None):
"""
as_leading_term is only allowed for results of .series()
This is a wrapper to compute a series first.
"""
from sympy import Dummy, log, Piecewise, piecewise_fold
from sympy.series.gruntz import calculate_series
if self.has(Piecewise):
expr = piecewise_fold(self)
else:
expr = self
if self.removeO() == 0:
return self
if logx is None:
d = Dummy('logx')
s = calculate_series(expr, x, d).subs(d, log(x))
else:
s = calculate_series(expr, x, logx)
return s.as_leading_term(x)
@cacheit
def as_leading_term(self, *symbols, cdir=0):
"""
Returns the leading (nonzero) term of the series expansion of self.
The _eval_as_leading_term routines are used to do this, and they must
always return a non-zero value.
Examples
========
>>> from sympy.abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)
"""
from sympy import powsimp
if len(symbols) > 1:
c = self
for x in symbols:
c = c.as_leading_term(x, cdir=cdir)
return c
elif not symbols:
return self
x = sympify(symbols[0])
if not x.is_symbol:
raise ValueError('expecting a Symbol but got %s' % x)
if x not in self.free_symbols:
return self
obj = self._eval_as_leading_term(x, cdir=cdir)
if obj is not None:
return powsimp(obj, deep=True, combine='exp')
raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
def _eval_as_leading_term(self, x, cdir=0):
return self
def as_coeff_exponent(self, x):
""" ``c*x**e -> c,e`` where x can be any symbolic expression.
"""
from sympy import collect
s = collect(self, x)
c, p = s.as_coeff_mul(x)
if len(p) == 1:
b, e = p[0].as_base_exp()
if b == x:
return c, e
return s, S.Zero
def leadterm(self, x, cdir=0):
"""
Returns the leading term a*x**b as a tuple (a, b).
Examples
========
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
"""
from sympy import Dummy, log
l = self.as_leading_term(x, cdir=cdir)
d = Dummy('logx')
if l.has(log(x)):
l = l.subs(log(x), d)
c, e = l.as_coeff_exponent(x)
if x in c.free_symbols:
from sympy.utilities.misc import filldedent
raise ValueError(filldedent("""
cannot compute leadterm(%s, %s). The coefficient
should have been free of %s but got %s""" % (self, x, x, c)))
c = c.subs(d, log(x))
return c, e
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return S.One, self
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return S.Zero, self
def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True,
full=False):
"""
Compute formal power power series of self.
See the docstring of the :func:`fps` function in sympy.series.formal for
more information.
"""
from sympy.series.formal import fps
return fps(self, x, x0, dir, hyper, order, rational, full)
def fourier_series(self, limits=None):
"""Compute fourier sine/cosine series of self.
See the docstring of the :func:`fourier_series` in sympy.series.fourier
for more information.
"""
from sympy.series.fourier import fourier_series
return fourier_series(self, limits)
###################################################################################
##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS ####################
###################################################################################
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return _derivative_dispatch(self, *symbols, **assumptions)
###########################################################################
###################### EXPRESSION EXPANSION METHODS #######################
###########################################################################
# Relevant subclasses should override _eval_expand_hint() methods. See
# the docstring of expand() for more info.
def _eval_expand_complex(self, **hints):
real, imag = self.as_real_imag(**hints)
return real + S.ImaginaryUnit*imag
@staticmethod
def _expand_hint(expr, hint, deep=True, **hints):
"""
Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``.
Returns ``(expr, hit)``, where expr is the (possibly) expanded
``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
``False`` otherwise.
"""
hit = False
# XXX: Hack to support non-Basic args
# |
# V
if deep and getattr(expr, 'args', ()) and not expr.is_Atom:
sargs = []
for arg in expr.args:
arg, arghit = Expr._expand_hint(arg, hint, **hints)
hit |= arghit
sargs.append(arg)
if hit:
expr = expr.func(*sargs)
if hasattr(expr, hint):
newexpr = getattr(expr, hint)(**hints)
if newexpr != expr:
return (newexpr, True)
return (expr, hit)
@cacheit
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
"""
Expand an expression using hints.
See the docstring of the expand() function in sympy.core.function for
more information.
"""
from sympy.simplify.radsimp import fraction
hints.update(power_base=power_base, power_exp=power_exp, mul=mul,
log=log, multinomial=multinomial, basic=basic)
expr = self
if hints.pop('frac', False):
n, d = [a.expand(deep=deep, modulus=modulus, **hints)
for a in fraction(self)]
return n/d
elif hints.pop('denom', False):
n, d = fraction(self)
return n/d.expand(deep=deep, modulus=modulus, **hints)
elif hints.pop('numer', False):
n, d = fraction(self)
return n.expand(deep=deep, modulus=modulus, **hints)/d
# Although the hints are sorted here, an earlier hint may get applied
# at a given node in the expression tree before another because of how
# the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y +
# x*z) because while applying log at the top level, log and mul are
# applied at the deeper level in the tree so that when the log at the
# upper level gets applied, the mul has already been applied at the
# lower level.
# Additionally, because hints are only applied once, the expression
# may not be expanded all the way. For example, if mul is applied
# before multinomial, x*(x + 1)**2 won't be expanded all the way. For
# now, we just use a special case to make multinomial run before mul,
# so that at least polynomials will be expanded all the way. In the
# future, smarter heuristics should be applied.
# TODO: Smarter heuristics
def _expand_hint_key(hint):
"""Make multinomial come before mul"""
if hint == 'mul':
return 'mulz'
return hint
for hint in sorted(hints.keys(), key=_expand_hint_key):
use_hint = hints[hint]
if use_hint:
hint = '_eval_expand_' + hint
expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints)
while True:
was = expr
if hints.get('multinomial', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_multinomial', deep=deep, **hints)
if hints.get('mul', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_mul', deep=deep, **hints)
if hints.get('log', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_log', deep=deep, **hints)
if expr == was:
break
if modulus is not None:
modulus = sympify(modulus)
if not modulus.is_Integer or modulus <= 0:
raise ValueError(
"modulus must be a positive integer, got %s" % modulus)
terms = []
for term in Add.make_args(expr):
coeff, tail = term.as_coeff_Mul(rational=True)
coeff %= modulus
if coeff:
terms.append(coeff*tail)
expr = Add(*terms)
return expr
###########################################################################
################### GLOBAL ACTION VERB WRAPPER METHODS ####################
###########################################################################
def integrate(self, *args, **kwargs):
"""See the integrate function in sympy.integrals"""
from sympy.integrals import integrate
return integrate(self, *args, **kwargs)
def nsimplify(self, constants=[], tolerance=None, full=False):
"""See the nsimplify function in sympy.simplify"""
from sympy.simplify import nsimplify
return nsimplify(self, constants, tolerance, full)
def separate(self, deep=False, force=False):
"""See the separate function in sympy.simplify"""
from sympy.core.function import expand_power_base
return expand_power_base(self, deep=deep, force=force)
def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True):
"""See the collect function in sympy.simplify"""
from sympy.simplify import collect
return collect(self, syms, func, evaluate, exact, distribute_order_term)
def together(self, *args, **kwargs):
"""See the together function in sympy.polys"""
from sympy.polys import together
return together(self, *args, **kwargs)
def apart(self, x=None, **args):
"""See the apart function in sympy.polys"""
from sympy.polys import apart
return apart(self, x, **args)
def ratsimp(self):
"""See the ratsimp function in sympy.simplify"""
from sympy.simplify import ratsimp
return ratsimp(self)
def trigsimp(self, **args):
"""See the trigsimp function in sympy.simplify"""
from sympy.simplify import trigsimp
return trigsimp(self, **args)
def radsimp(self, **kwargs):
"""See the radsimp function in sympy.simplify"""
from sympy.simplify import radsimp
return radsimp(self, **kwargs)
def powsimp(self, *args, **kwargs):
"""See the powsimp function in sympy.simplify"""
from sympy.simplify import powsimp
return powsimp(self, *args, **kwargs)
def combsimp(self):
"""See the combsimp function in sympy.simplify"""
from sympy.simplify import combsimp
return combsimp(self)
def gammasimp(self):
"""See the gammasimp function in sympy.simplify"""
from sympy.simplify import gammasimp
return gammasimp(self)
def factor(self, *gens, **args):
"""See the factor() function in sympy.polys.polytools"""
from sympy.polys import factor
return factor(self, *gens, **args)
def cancel(self, *gens, **args):
"""See the cancel function in sympy.polys"""
from sympy.polys import cancel
return cancel(self, *gens, **args)
def invert(self, g, *gens, **args):
"""Return the multiplicative inverse of ``self`` mod ``g``
where ``self`` (and ``g``) may be symbolic expressions).
See Also
========
sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert
"""
from sympy.polys.polytools import invert
from sympy.core.numbers import mod_inverse
if self.is_number and getattr(g, 'is_number', True):
return mod_inverse(self, g)
return invert(self, g, *gens, **args)
def round(self, n=None):
"""Return x rounded to the given decimal place.
If a complex number would results, apply round to the real
and imaginary components of the number.
Examples
========
>>> from sympy import pi, E, I, S, Number
>>> pi.round()
3
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6 + 3*I
The round method has a chopping effect:
>>> (2*pi + I/10).round()
6
>>> (pi/10 + 2*I).round()
2*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I
Notes
=====
The Python ``round`` function uses the SymPy ``round`` method so it
will always return a SymPy number (not a Python float or int):
>>> isinstance(round(S(123), -2), Number)
True
"""
from sympy.core.numbers import Float
x = self
if not x.is_number:
raise TypeError("can't round symbolic expression")
if not x.is_Atom:
if not pure_complex(x.n(2), or_real=True):
raise TypeError(
'Expected a number but got %s:' % func_name(x))
elif x in (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity):
return x
if not x.is_extended_real:
r, i = x.as_real_imag()
return r.round(n) + S.ImaginaryUnit*i.round(n)
if not x:
return S.Zero if n is None else x
p = as_int(n or 0)
if x.is_Integer:
return Integer(round(int(x), p))
digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1
allow = digits_to_decimal + p
precs = [f._prec for f in x.atoms(Float)]
dps = prec_to_dps(max(precs)) if precs else None
if dps is None:
# assume everything is exact so use the Python
# float default or whatever was requested
dps = max(15, allow)
else:
allow = min(allow, dps)
# this will shift all digits to right of decimal
# and give us dps to work with as an int
shift = -digits_to_decimal + dps
extra = 1 # how far we look past known digits
# NOTE
# mpmath will calculate the binary representation to
# an arbitrary number of digits but we must base our
# answer on a finite number of those digits, e.g.
# .575 2589569785738035/2**52 in binary.
# mpmath shows us that the first 18 digits are
# >>> Float(.575).n(18)
# 0.574999999999999956
# The default precision is 15 digits and if we ask
# for 15 we get
# >>> Float(.575).n(15)
# 0.575000000000000
# mpmath handles rounding at the 15th digit. But we
# need to be careful since the user might be asking
# for rounding at the last digit and our semantics
# are to round toward the even final digit when there
# is a tie. So the extra digit will be used to make
# that decision. In this case, the value is the same
# to 15 digits:
# >>> Float(.575).n(16)
# 0.5750000000000000
# Now converting this to the 15 known digits gives
# 575000000000000.0
# which rounds to integer
# 5750000000000000
# And now we can round to the desired digt, e.g. at
# the second from the left and we get
# 5800000000000000
# and rescaling that gives
# 0.58
# as the final result.
# If the value is made slightly less than 0.575 we might
# still obtain the same value:
# >>> Float(.575-1e-16).n(16)*10**15
# 574999999999999.8
# What 15 digits best represents the known digits (which are
# to the left of the decimal? 5750000000000000, the same as
# before. The only way we will round down (in this case) is
# if we declared that we had more than 15 digits of precision.
# For example, if we use 16 digits of precision, the integer
# we deal with is
# >>> Float(.575-1e-16).n(17)*10**16
# 5749999999999998.4
# and this now rounds to 5749999999999998 and (if we round to
# the 2nd digit from the left) we get 5700000000000000.
#
xf = x.n(dps + extra)*Pow(10, shift)
xi = Integer(xf)
# use the last digit to select the value of xi
# nearest to x before rounding at the desired digit
sign = 1 if x > 0 else -1
dif2 = sign*(xf - xi).n(extra)
if dif2 < 0:
raise NotImplementedError(
'not expecting int(x) to round away from 0')
if dif2 > .5:
xi += sign # round away from 0
elif dif2 == .5:
xi += sign if xi%2 else -sign # round toward even
# shift p to the new position
ip = p - shift
# let Python handle the int rounding then rescale
xr = round(xi.p, ip)
# restore scale
rv = Rational(xr, Pow(10, shift))
# return Float or Integer
if rv.is_Integer:
if n is None: # the single-arg case
return rv
# use str or else it won't be a float
return Float(str(rv), dps) # keep same precision
else:
if not allow and rv > self:
allow += 1
return Float(rv, allow)
__round__ = round
def _eval_derivative_matrix_lines(self, x):
from sympy.matrices.expressions.matexpr import _LeftRightArgs
return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))]
class AtomicExpr(Atom, Expr):
"""
A parent class for object which are both atoms and Exprs.
For example: Symbol, Number, Rational, Integer, ...
But not: Add, Mul, Pow, ...
"""
is_number = False
is_Atom = True
__slots__ = ()
def _eval_derivative(self, s):
if self == s:
return S.One
return S.Zero
def _eval_derivative_n_times(self, s, n):
from sympy import Piecewise, Eq
from sympy import Tuple, MatrixExpr
from sympy.matrices.common import MatrixCommon
if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)):
return super()._eval_derivative_n_times(s, n)
if self == s:
return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
else:
return Piecewise((self, Eq(n, 0)), (0, True))
def _eval_is_polynomial(self, syms):
return True
def _eval_is_rational_function(self, syms):
return True
def _eval_is_meromorphic(self, x, a):
from sympy.calculus.util import AccumBounds
return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds)
def _eval_is_algebraic_expr(self, syms):
return True
def _eval_nseries(self, x, n, logx, cdir=0):
return self
@property
def expr_free_symbols(self):
return {self}
def _mag(x):
"""Return integer ``i`` such that .1 <= x/10**i < 1
Examples
========
>>> from sympy.core.expr import _mag
>>> from sympy import Float
>>> _mag(Float(.1))
0
>>> _mag(Float(.01))
-1
>>> _mag(Float(1234))
4
"""
from math import log10, ceil, log
from sympy import Float
xpos = abs(x.n())
if not xpos:
return S.Zero
try:
mag_first_dig = int(ceil(log10(xpos)))
except (ValueError, OverflowError):
mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10)))
# check that we aren't off by 1
if (xpos/10**mag_first_dig) >= 1:
assert 1 <= (xpos/10**mag_first_dig) < 10
mag_first_dig += 1
return mag_first_dig
class UnevaluatedExpr(Expr):
"""
Expression that is not evaluated unless released.
Examples
========
>>> from sympy import UnevaluatedExpr
>>> from sympy.abc import x
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
"""
def __new__(cls, arg, **kwargs):
arg = _sympify(arg)
obj = Expr.__new__(cls, arg, **kwargs)
return obj
def doit(self, **kwargs):
if kwargs.get("deep", True):
return self.args[0].doit(**kwargs)
else:
return self.args[0]
def unchanged(func, *args):
"""Return True if `func` applied to the `args` is unchanged.
Can be used instead of `assert foo == foo`.
Examples
========
>>> from sympy import Piecewise, cos, pi
>>> from sympy.core.expr import unchanged
>>> from sympy.abc import x
>>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
True
>>> unchanged(cos, pi)
False
Comparison of args uses the builtin capabilities of the object's
arguments to test for equality so args can be defined loosely. Here,
the ExprCondPair arguments of Piecewise compare as equal to the
tuples that can be used to create the Piecewise:
>>> unchanged(Piecewise, (x, x > 1), (0, True))
True
"""
f = func(*args)
return f.func == func and f.args == args
class ExprBuilder:
def __init__(self, op, args=[], validator=None, check=True):
if not hasattr(op, "__call__"):
raise TypeError("op {} needs to be callable".format(op))
self.op = op
self.args = args
self.validator = validator
if (validator is not None) and check:
self.validate()
@staticmethod
def _build_args(args):
return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
def validate(self):
if self.validator is None:
return
args = self._build_args(self.args)
self.validator(*args)
def build(self, check=True):
args = self._build_args(self.args)
if self.validator and check:
self.validator(*args)
return self.op(*args)
def append_argument(self, arg, check=True):
self.args.append(arg)
if self.validator and check:
self.validate(*self.args)
def __getitem__(self, item):
if item == 0:
return self.op
else:
return self.args[item-1]
def __repr__(self):
return str(self.build())
def search_element(self, elem):
for i, arg in enumerate(self.args):
if isinstance(arg, ExprBuilder):
ret = arg.search_index(elem)
if ret is not None:
return (i,) + ret
elif id(arg) == id(elem):
return (i,)
return None
from .mul import Mul
from .add import Add
from .power import Pow
from .function import Function, _derivative_dispatch
from .mod import Mod
from .exprtools import factor_terms
from .numbers import Integer, Rational
|
a29ec5fd4fec553a3031832b471dd4261fa282b526d6107e5888995ff426ec19 | import numbers
import decimal
import fractions
import math
import re as regex
import sys
from .containers import Tuple
from .sympify import (SympifyError, converter, sympify, _convert_numpy_types, _sympify,
_is_numpy_instance)
from .singleton import S, Singleton
from .expr import Expr, AtomicExpr
from .evalf import pure_complex
from .decorators import _sympifyit
from .cache import cacheit, clear_cache
from .logic import fuzzy_not
from sympy.core.compatibility import (as_int, HAS_GMPY, SYMPY_INTS,
gmpy)
from sympy.core.cache import lru_cache
from .kind import NumberKind
from sympy.multipledispatch import dispatch
import mpmath
import mpmath.libmp as mlib
from mpmath.libmp import bitcount
from mpmath.libmp.backend import MPZ
from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed
from mpmath.ctx_mp import mpnumeric
from mpmath.libmp.libmpf import (
finf as _mpf_inf, fninf as _mpf_ninf,
fnan as _mpf_nan, fzero, _normalize as mpf_normalize,
prec_to_dps)
from sympy.utilities.misc import debug, filldedent
from .parameters import global_parameters
from sympy.utilities.exceptions import SymPyDeprecationWarning
rnd = mlib.round_nearest
_LOG2 = math.log(2)
def comp(z1, z2, tol=None):
"""Return a bool indicating whether the error between z1 and z2
is <= tol.
Examples
========
If ``tol`` is None then True will be returned if
``abs(z1 - z2)*10**p <= 5`` where ``p`` is minimum value of the
decimal precision of each value.
>>> from sympy.core.numbers import comp, pi
>>> pi4 = pi.n(4); pi4
3.142
>>> comp(_, 3.142)
True
>>> comp(pi4, 3.141)
False
>>> comp(pi4, 3.143)
False
A comparison of strings will be made
if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''.
>>> comp(pi4, 3.1415)
True
>>> comp(pi4, 3.1415, '')
False
When ``tol`` is provided and ``z2`` is non-zero and
``|z1| > 1`` the error is normalized by ``|z1|``:
>>> abs(pi4 - 3.14)/pi4
0.000509791731426756
>>> comp(pi4, 3.14, .001) # difference less than 0.1%
True
>>> comp(pi4, 3.14, .0005) # difference less than 0.1%
False
When ``|z1| <= 1`` the absolute error is used:
>>> 1/pi4
0.3183
>>> abs(1/pi4 - 0.3183)/(1/pi4)
3.07371499106316e-5
>>> abs(1/pi4 - 0.3183)
9.78393554684764e-6
>>> comp(1/pi4, 0.3183, 1e-5)
True
To see if the absolute error between ``z1`` and ``z2`` is less
than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)``
or ``comp(z1 - z2, tol=tol)``:
>>> abs(pi4 - 3.14)
0.00160156249999988
>>> comp(pi4 - 3.14, 0, .002)
True
>>> comp(pi4 - 3.14, 0, .001)
False
"""
if type(z2) is str:
if not pure_complex(z1, or_real=True):
raise ValueError('when z2 is a str z1 must be a Number')
return str(z1) == z2
if not z1:
z1, z2 = z2, z1
if not z1:
return True
if not tol:
a, b = z1, z2
if tol == '':
return str(a) == str(b)
if tol is None:
a, b = sympify(a), sympify(b)
if not all(i.is_number for i in (a, b)):
raise ValueError('expecting 2 numbers')
fa = a.atoms(Float)
fb = b.atoms(Float)
if not fa and not fb:
# no floats -- compare exactly
return a == b
# get a to be pure_complex
for do in range(2):
ca = pure_complex(a, or_real=True)
if not ca:
if fa:
a = a.n(prec_to_dps(min([i._prec for i in fa])))
ca = pure_complex(a, or_real=True)
break
else:
fa, fb = fb, fa
a, b = b, a
cb = pure_complex(b)
if not cb and fb:
b = b.n(prec_to_dps(min([i._prec for i in fb])))
cb = pure_complex(b, or_real=True)
if ca and cb and (ca[1] or cb[1]):
return all(comp(i, j) for i, j in zip(ca, cb))
tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec)))
return int(abs(a - b)*tol) <= 5
diff = abs(z1 - z2)
az1 = abs(z1)
if z2 and az1 > 1:
return diff/az1 <= tol
else:
return diff <= tol
def mpf_norm(mpf, prec):
"""Return the mpf tuple normalized appropriately for the indicated
precision after doing a check to see if zero should be returned or
not when the mantissa is 0. ``mpf_normlize`` always assumes that this
is zero, but it may not be since the mantissa for mpf's values "+inf",
"-inf" and "nan" have a mantissa of zero, too.
Note: this is not intended to validate a given mpf tuple, so sending
mpf tuples that were not created by mpmath may produce bad results. This
is only a wrapper to ``mpf_normalize`` which provides the check for non-
zero mpfs that have a 0 for the mantissa.
"""
sign, man, expt, bc = mpf
if not man:
# hack for mpf_normalize which does not do this;
# it assumes that if man is zero the result is 0
# (see issue 6639)
if not bc:
return fzero
else:
# don't change anything; this should already
# be a well formed mpf tuple
return mpf
# Necessary if mpmath is using the gmpy backend
from mpmath.libmp.backend import MPZ
rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)
return rv
# TODO: we should use the warnings module
_errdict = {"divide": False}
def seterr(divide=False):
"""
Should sympy raise an exception on 0/0 or return a nan?
divide == True .... raise an exception
divide == False ... return nan
"""
if _errdict["divide"] != divide:
clear_cache()
_errdict["divide"] = divide
def _as_integer_ratio(p):
neg_pow, man, expt, bc = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_)
p = [1, -1][neg_pow % 2]*man
if expt < 0:
q = 2**-expt
else:
q = 1
p *= 2**expt
return int(p), int(q)
def _decimal_to_Rational_prec(dec):
"""Convert an ordinary decimal instance to a Rational."""
if not dec.is_finite():
raise TypeError("dec must be finite, got %s." % dec)
s, d, e = dec.as_tuple()
prec = len(d)
if e >= 0: # it's an integer
rv = Integer(int(dec))
else:
s = (-1)**s
d = sum([di*10**i for i, di in enumerate(reversed(d))])
rv = Rational(s*d, 10**-e)
return rv, prec
_floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))")
def _literal_float(f):
"""Return True if n starts like a floating point number."""
return bool(_floatpat.match(f))
# (a,b) -> gcd(a,b)
# TODO caching with decorator, but not to degrade performance
@lru_cache(1024)
def igcd(*args):
"""Computes nonnegative integer greatest common divisor.
Explanation
===========
The algorithm is based on the well known Euclid's algorithm. To
improve speed, igcd() has its own caching mechanism implemented.
Examples
========
>>> from sympy.core.numbers import igcd
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
"""
if len(args) < 2:
raise TypeError(
'igcd() takes at least 2 arguments (%s given)' % len(args))
args_temp = [abs(as_int(i)) for i in args]
if 1 in args_temp:
return 1
a = args_temp.pop()
if HAS_GMPY: # Using gmpy if present to speed up.
for b in args_temp:
a = gmpy.gcd(a, b) if b else a
return as_int(a)
for b in args_temp:
a = math.gcd(a, b)
return a
igcd2 = math.gcd
def igcd_lehmer(a, b):
"""Computes greatest common divisor of two integers.
Explanation
===========
Euclid's algorithm for the computation of the greatest
common divisor gcd(a, b) of two (positive) integers
a and b is based on the division identity
a = q*b + r,
where the quotient q and the remainder r are integers
and 0 <= r < b. Then each common divisor of a and b
divides r, and it follows that gcd(a, b) == gcd(b, r).
The algorithm works by constructing the sequence
r0, r1, r2, ..., where r0 = a, r1 = b, and each rn
is the remainder from the division of the two preceding
elements.
In Python, q = a // b and r = a % b are obtained by the
floor division and the remainder operations, respectively.
These are the most expensive arithmetic operations, especially
for large a and b.
Lehmer's algorithm is based on the observation that the quotients
qn = r(n-1) // rn are in general small integers even
when a and b are very large. Hence the quotients can be
usually determined from a relatively small number of most
significant bits.
The efficiency of the algorithm is further enhanced by not
computing each long remainder in Euclid's sequence. The remainders
are linear combinations of a and b with integer coefficients
derived from the quotients. The coefficients can be computed
as far as the quotients can be determined from the chosen
most significant parts of a and b. Only then a new pair of
consecutive remainders is computed and the algorithm starts
anew with this pair.
References
==========
.. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm
"""
a, b = abs(as_int(a)), abs(as_int(b))
if a < b:
a, b = b, a
# The algorithm works by using one or two digit division
# whenever possible. The outer loop will replace the
# pair (a, b) with a pair of shorter consecutive elements
# of the Euclidean gcd sequence until a and b
# fit into two Python (long) int digits.
nbits = 2*sys.int_info.bits_per_digit
while a.bit_length() > nbits and b != 0:
# Quotients are mostly small integers that can
# be determined from most significant bits.
n = a.bit_length() - nbits
x, y = int(a >> n), int(b >> n) # most significant bits
# Elements of the Euclidean gcd sequence are linear
# combinations of a and b with integer coefficients.
# Compute the coefficients of consecutive pairs
# a' = A*a + B*b, b' = C*a + D*b
# using small integer arithmetic as far as possible.
A, B, C, D = 1, 0, 0, 1 # initial values
while True:
# The coefficients alternate in sign while looping.
# The inner loop combines two steps to keep track
# of the signs.
# At this point we have
# A > 0, B <= 0, C <= 0, D > 0,
# x' = x + B <= x < x" = x + A,
# y' = y + C <= y < y" = y + D,
# and
# x'*N <= a' < x"*N, y'*N <= b' < y"*N,
# where N = 2**n.
# Now, if y' > 0, and x"//y' and x'//y" agree,
# then their common value is equal to q = a'//b'.
# In addition,
# x'%y" = x' - q*y" < x" - q*y' = x"%y',
# and
# (x'%y")*N < a'%b' < (x"%y')*N.
# On the other hand, we also have x//y == q,
# and therefore
# x'%y" = x + B - q*(y + D) = x%y + B',
# x"%y' = x + A - q*(y + C) = x%y + A',
# where
# B' = B - q*D < 0, A' = A - q*C > 0.
if y + C <= 0:
break
q = (x + A) // (y + C)
# Now x'//y" <= q, and equality holds if
# x' - q*y" = (x - q*y) + (B - q*D) >= 0.
# This is a minor optimization to avoid division.
x_qy, B_qD = x - q*y, B - q*D
if x_qy + B_qD < 0:
break
# Next step in the Euclidean sequence.
x, y = y, x_qy
A, B, C, D = C, D, A - q*C, B_qD
# At this point the signs of the coefficients
# change and their roles are interchanged.
# A <= 0, B > 0, C > 0, D < 0,
# x' = x + A <= x < x" = x + B,
# y' = y + D < y < y" = y + C.
if y + D <= 0:
break
q = (x + B) // (y + D)
x_qy, A_qC = x - q*y, A - q*C
if x_qy + A_qC < 0:
break
x, y = y, x_qy
A, B, C, D = C, D, A_qC, B - q*D
# Now the conditions on top of the loop
# are again satisfied.
# A > 0, B < 0, C < 0, D > 0.
if B == 0:
# This can only happen when y == 0 in the beginning
# and the inner loop does nothing.
# Long division is forced.
a, b = b, a % b
continue
# Compute new long arguments using the coefficients.
a, b = A*a + B*b, C*a + D*b
# Small divisors. Finish with the standard algorithm.
while b:
a, b = b, a % b
return a
def ilcm(*args):
"""Computes integer least common multiple.
Examples
========
>>> from sympy.core.numbers import ilcm
>>> ilcm(5, 10)
10
>>> ilcm(7, 3)
21
>>> ilcm(5, 10, 15)
30
"""
if len(args) < 2:
raise TypeError(
'ilcm() takes at least 2 arguments (%s given)' % len(args))
if 0 in args:
return 0
a = args[0]
for b in args[1:]:
a = a // igcd(a, b) * b # since gcd(a,b) | a
return a
def igcdex(a, b):
"""Returns x, y, g such that g = x*a + y*b = gcd(a, b).
Examples
========
>>> from sympy.core.numbers import igcdex
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> x, y, g = igcdex(100, 2004)
>>> x, y, g
(-20, 1, 4)
>>> x*100 + y*2004
4
"""
if (not a) and (not b):
return (0, 1, 0)
if not a:
return (0, b//abs(b), abs(b))
if not b:
return (a//abs(a), 0, abs(a))
if a < 0:
a, x_sign = -a, -1
else:
x_sign = 1
if b < 0:
b, y_sign = -b, -1
else:
y_sign = 1
x, y, r, s = 1, 0, 0, 1
while b:
(c, q) = (a % b, a // b)
(a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s)
return (x*x_sign, y*y_sign, a)
def mod_inverse(a, m):
"""
Return the number c such that, (a * c) = 1 (mod m)
where c has the same sign as m. If no such value exists,
a ValueError is raised.
Examples
========
>>> from sympy import S
>>> from sympy.core.numbers import mod_inverse
Suppose we wish to find multiplicative inverse x of
3 modulo 11. This is the same as finding x such
that 3 * x = 1 (mod 11). One value of x that satisfies
this congruence is 4. Because 3 * 4 = 12 and 12 = 1 (mod 11).
This is the value returned by mod_inverse:
>>> mod_inverse(3, 11)
4
>>> mod_inverse(-3, 11)
7
When there is a common factor between the numerators of
``a`` and ``m`` the inverse does not exist:
>>> mod_inverse(2, 4)
Traceback (most recent call last):
...
ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2)
7/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
.. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
"""
c = None
try:
a, m = as_int(a), as_int(m)
if m != 1 and m != -1:
x, y, g = igcdex(a, m)
if g == 1:
c = x % m
except ValueError:
a, m = sympify(a), sympify(m)
if not (a.is_number and m.is_number):
raise TypeError(filldedent('''
Expected numbers for arguments; symbolic `mod_inverse`
is not implemented
but symbolic expressions can be handled with the
similar function,
sympy.polys.polytools.invert'''))
big = (m > 1)
if not (big is S.true or big is S.false):
raise ValueError('m > 1 did not evaluate; try to simplify %s' % m)
elif big:
c = 1/a
if c is None:
raise ValueError('inverse of %s (mod %s) does not exist' % (a, m))
return c
class Number(AtomicExpr):
"""Represents atomic numbers in SymPy.
Explanation
===========
Floating point numbers are represented by the Float class.
Rational numbers (of any size) are represented by the Rational class.
Integer numbers (of any size) are represented by the Integer class.
Float and Rational are subclasses of Number; Integer is a subclass
of Rational.
For example, ``2/3`` is represented as ``Rational(2, 3)`` which is
a different object from the floating point number obtained with
Python division ``2/3``. Even for numbers that are exactly
represented in binary, there is a difference between how two forms,
such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy.
The rational form is to be preferred in symbolic computations.
Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or
complex numbers ``3 + 4*I``, are not instances of Number class as
they are not atomic.
See Also
========
Float, Integer, Rational
"""
is_commutative = True
is_number = True
is_Number = True
__slots__ = ()
# Used to make max(x._prec, y._prec) return x._prec when only x is a float
_prec = -1
kind = NumberKind
def __new__(cls, *obj):
if len(obj) == 1:
obj = obj[0]
if isinstance(obj, Number):
return obj
if isinstance(obj, SYMPY_INTS):
return Integer(obj)
if isinstance(obj, tuple) and len(obj) == 2:
return Rational(*obj)
if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
return Float(obj)
if isinstance(obj, str):
_obj = obj.lower() # float('INF') == float('inf')
if _obj == 'nan':
return S.NaN
elif _obj == 'inf':
return S.Infinity
elif _obj == '+inf':
return S.Infinity
elif _obj == '-inf':
return S.NegativeInfinity
val = sympify(obj)
if isinstance(val, Number):
return val
else:
raise ValueError('String "%s" does not denote a Number' % obj)
msg = "expected str|int|long|float|Decimal|Number object but got %r"
raise TypeError(msg % type(obj).__name__)
def invert(self, other, *gens, **args):
from sympy.polys.polytools import invert
if getattr(other, 'is_number', True):
return mod_inverse(self, other)
return invert(self, other, *gens, **args)
def __divmod__(self, other):
from .containers import Tuple
from sympy.functions.elementary.complexes import sign
try:
other = Number(other)
if self.is_infinite or S.NaN in (self, other):
return (S.NaN, S.NaN)
except TypeError:
return NotImplemented
if not other:
raise ZeroDivisionError('modulo by zero')
if self.is_Integer and other.is_Integer:
return Tuple(*divmod(self.p, other.p))
elif isinstance(other, Float):
rat = self/Rational(other)
else:
rat = self/other
if other.is_finite:
w = int(rat) if rat >= 0 else int(rat) - 1
r = self - other*w
else:
w = 0 if not self or (sign(self) == sign(other)) else -1
r = other if w else self
return Tuple(w, r)
def __rdivmod__(self, other):
try:
other = Number(other)
except TypeError:
return NotImplemented
return divmod(other, self)
def _as_mpf_val(self, prec):
"""Evaluation of mpf tuple accurate to at least prec bits."""
raise NotImplementedError('%s needs ._as_mpf_val() method' %
(self.__class__.__name__))
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def _as_mpf_op(self, prec):
prec = max(prec, self._prec)
return self._as_mpf_val(prec), prec
def __float__(self):
return mlib.to_float(self._as_mpf_val(53))
def floor(self):
raise NotImplementedError('%s needs .floor() method' %
(self.__class__.__name__))
def ceiling(self):
raise NotImplementedError('%s needs .ceiling() method' %
(self.__class__.__name__))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def _eval_conjugate(self):
return self
def _eval_order(self, *symbols):
from sympy import Order
# Order(5, x, y) -> Order(1,x,y)
return Order(S.One, *symbols)
def _eval_subs(self, old, new):
if old == -self:
return -new
return self # there is no other possibility
def _eval_is_finite(self):
return True
@classmethod
def class_key(cls):
return 1, 0, 'Number'
@cacheit
def sort_key(self, order=None):
return self.class_key(), (0, ()), (), self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.Infinity
elif other is S.NegativeInfinity:
return S.NegativeInfinity
return AtomicExpr.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
return S.Infinity
return AtomicExpr.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.Infinity
else:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.NegativeInfinity
else:
return S.Infinity
elif isinstance(other, Tuple):
return NotImplemented
return AtomicExpr.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity or other is S.NegativeInfinity:
return S.Zero
return AtomicExpr.__truediv__(self, other)
def __eq__(self, other):
raise NotImplementedError('%s needs .__eq__() method' %
(self.__class__.__name__))
def __ne__(self, other):
raise NotImplementedError('%s needs .__ne__() method' %
(self.__class__.__name__))
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, other))
raise NotImplementedError('%s needs .__lt__() method' %
(self.__class__.__name__))
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s <= %s" % (self, other))
raise NotImplementedError('%s needs .__le__() method' %
(self.__class__.__name__))
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s > %s" % (self, other))
return _sympify(other).__lt__(self)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s >= %s" % (self, other))
return _sympify(other).__le__(self)
def __hash__(self):
return super().__hash__()
def is_constant(self, *wrt, **flags):
return True
def as_coeff_mul(self, *deps, rational=True, **kwargs):
# a -> c*t
if self.is_Rational or not rational:
return self, tuple()
elif self.is_negative:
return S.NegativeOne, (-self,)
return S.One, (self,)
def as_coeff_add(self, *deps):
# a -> c + t
if self.is_Rational:
return self, tuple()
return S.Zero, (self,)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
if rational and not self.is_Rational:
return S.One, self
return (self, S.One) if self else (S.One, self)
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
if not rational:
return self, S.Zero
return S.Zero, self
def gcd(self, other):
"""Compute GCD of `self` and `other`. """
from sympy.polys import gcd
return gcd(self, other)
def lcm(self, other):
"""Compute LCM of `self` and `other`. """
from sympy.polys import lcm
return lcm(self, other)
def cofactors(self, other):
"""Compute GCD and cofactors of `self` and `other`. """
from sympy.polys import cofactors
return cofactors(self, other)
class Float(Number):
"""Represent a floating-point number of arbitrary precision.
Examples
========
>>> from sympy import Float
>>> Float(3.5)
3.50000000000000
>>> Float(3)
3.00000000000000
Creating Floats from strings (and Python ``int`` and ``long``
types) will give a minimum precision of 15 digits, but the
precision will automatically increase to capture all digits
entered.
>>> Float(1)
1.00000000000000
>>> Float(10**20)
100000000000000000000.
>>> Float('1e20')
100000000000000000000.
However, *floating-point* numbers (Python ``float`` types) retain
only 15 digits of precision:
>>> Float(1e20)
1.00000000000000e+20
>>> Float(1.23456789123456789)
1.23456789123457
It may be preferable to enter high-precision decimal numbers
as strings:
>>> Float('1.23456789123456789')
1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e-3', 3)
0.00100
>>> Float(100, 4)
100.0
Float can automatically count significant figures if a null string
is sent for the precision; spaces or underscores are also allowed. (Auto-
counting is only allowed for strings, ints and longs).
>>> Float('123 456 789.123_456', '')
123456789.123456
>>> Float('12e-3', '')
0.012
>>> Float(3, '')
3.
If a number is written in scientific notation, only the digits before the
exponent are considered significant if a decimal appears, otherwise the
"e" signifies only how to move the decimal:
>>> Float('60.e2', '') # 2 digits significant
6.0e+3
>>> Float('60e2', '') # 4 digits significant
6000.
>>> Float('600e-2', '') # 3 digits significant
6.00
Notes
=====
Floats are inexact by their nature unless their value is a binary-exact
value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, evalf needs to be able to change the precision
but this will not increase the accuracy of the inexact value. The
following is the most accurate 5-digit approximation of a value of 0.1
that had only 1 digit of precision:
>>> approx.evalf(5)
0.099609
By contrast, 0.125 is exact in binary (as it is in base 10) and so it
can be passed to Float or evalf to obtain an arbitrary precision with
matching accuracy:
>>> Float(exact, 5)
0.12500
>>> exact.evalf(20)
0.12500000000000000000
Trying to make a high-precision Float from a float is not disallowed,
but one must keep in mind that the *underlying float* (not the apparent
decimal value) is being obtained with high precision. For example, 0.3
does not have a finite binary representation. The closest rational is
the fraction 5404319552844595/2**54. So if you try to obtain a Float of
0.3 to 20 digits of precision you will not see the same thing as 0.3
followed by 19 zeros:
>>> Float(0.3, 20)
0.29999999999999998890
If you want a 20-digit value of the decimal 0.3 (not the floating point
approximation of 0.3) you should send the 0.3 as a string. The underlying
representation is still binary but a higher precision than Python's float
is used:
>>> Float('0.3', 20)
0.30000000000000000000
Although you can increase the precision of an existing Float using Float
it will not increase the accuracy -- the underlying value is not changed:
>>> def show(f): # binary rep of Float
... from sympy import Mul, Pow
... s, m, e, b = f._mpf_
... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
... print('%s at prec=%s' % (v, f._prec))
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10
The same thing happens when evalf is used on a Float:
>>> show(t.evalf(20))
4915/2**14 at prec=70
>>> show(t.evalf(2))
307/2**10 at prec=10
Finally, Floats can be instantiated with an mpf tuple (n, c, p) to
produce the number (-1)**n*c*2**p:
>>> n, c, p = 1, 5, 0
>>> (-1)**n*c*2**p
-5
>>> Float((1, 5, 0))
-5.00000000000000
An actual mpf tuple also contains the number of bits in c as the last
element of the tuple:
>>> _._mpf_
(1, 5, 0, 3)
This is not needed for instantiation and is not the same thing as the
precision. The mpf tuple and the precision are two separate quantities
that Float tracks.
In SymPy, a Float is a number that can be computed with arbitrary
precision. Although floating point 'inf' and 'nan' are not such
numbers, Float can create these numbers:
>>> Float('-inf')
-oo
>>> _.is_Float
False
"""
__slots__ = ('_mpf_', '_prec')
# A Float represents many real numbers,
# both rational and irrational.
is_rational = None
is_irrational = None
is_number = True
is_real = True
is_extended_real = True
is_Float = True
def __new__(cls, num, dps=None, prec=None, precision=None):
if prec is not None:
SymPyDeprecationWarning(
feature="Using 'prec=XX' to denote decimal precision",
useinstead="'dps=XX' for decimal precision and 'precision=XX' "\
"for binary precision",
issue=12820,
deprecated_since_version="1.1").warn()
dps = prec
del prec # avoid using this deprecated kwarg
if dps is not None and precision is not None:
raise ValueError('Both decimal and binary precision supplied. '
'Supply only one. ')
if isinstance(num, str):
# Float accepts spaces as digit separators
num = num.replace(' ', '').lower()
# in Py 3.6
# underscores are allowed. In anticipation of that, we ignore
# legally placed underscores
if '_' in num:
parts = num.split('_')
if not (all(parts) and
all(parts[i][-1].isdigit()
for i in range(0, len(parts), 2)) and
all(parts[i][0].isdigit()
for i in range(1, len(parts), 2))):
# copy Py 3.6 error
raise ValueError("could not convert string to float: '%s'" % num)
num = ''.join(parts)
if num.startswith('.') and len(num) > 1:
num = '0' + num
elif num.startswith('-.') and len(num) > 2:
num = '-0.' + num[2:]
elif num in ('inf', '+inf'):
return S.Infinity
elif num == '-inf':
return S.NegativeInfinity
elif isinstance(num, float) and num == 0:
num = '0'
elif isinstance(num, float) and num == float('inf'):
return S.Infinity
elif isinstance(num, float) and num == float('-inf'):
return S.NegativeInfinity
elif isinstance(num, float) and num == float('nan'):
return S.NaN
elif isinstance(num, (SYMPY_INTS, Integer)):
num = str(num)
elif num is S.Infinity:
return num
elif num is S.NegativeInfinity:
return num
elif num is S.NaN:
return num
elif _is_numpy_instance(num): # support for numpy datatypes
num = _convert_numpy_types(num)
elif isinstance(num, mpmath.mpf):
if precision is None:
if dps is None:
precision = num.context.prec
num = num._mpf_
if dps is None and precision is None:
dps = 15
if isinstance(num, Float):
return num
if isinstance(num, str) and _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
dps = max(15, dps)
precision = mlib.libmpf.dps_to_prec(dps)
elif precision == '' and dps is None or precision is None and dps == '':
if not isinstance(num, str):
raise ValueError('The null string can only be used when '
'the number to Float is passed as a string or an integer.')
ok = None
if _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
precision = mlib.libmpf.dps_to_prec(dps)
ok = True
if ok is None:
raise ValueError('string-float not recognized: %s' % num)
# decimal precision(dps) is set and maybe binary precision(precision)
# as well.From here on binary precision is used to compute the Float.
# Hence, if supplied use binary precision else translate from decimal
# precision.
if precision is None or precision == '':
precision = mlib.libmpf.dps_to_prec(dps)
precision = int(precision)
if isinstance(num, float):
_mpf_ = mlib.from_float(num, precision, rnd)
elif isinstance(num, str):
_mpf_ = mlib.from_str(num, precision, rnd)
elif isinstance(num, decimal.Decimal):
if num.is_finite():
_mpf_ = mlib.from_str(str(num), precision, rnd)
elif num.is_nan():
return S.NaN
elif num.is_infinite():
if num > 0:
return S.Infinity
return S.NegativeInfinity
else:
raise ValueError("unexpected decimal value %s" % str(num))
elif isinstance(num, tuple) and len(num) in (3, 4):
if type(num[1]) is str:
# it's a hexadecimal (coming from a pickled object)
# assume that it is in standard form
num = list(num)
# If we're loading an object pickled in Python 2 into
# Python 3, we may need to strip a tailing 'L' because
# of a shim for int on Python 3, see issue #13470.
if num[1].endswith('L'):
num[1] = num[1][:-1]
num[1] = MPZ(num[1], 16)
_mpf_ = tuple(num)
else:
if len(num) == 4:
# handle normalization hack
return Float._new(num, precision)
else:
if not all((
num[0] in (0, 1),
num[1] >= 0,
all(type(i) in (int, int) for i in num)
)):
raise ValueError('malformed mpf: %s' % (num,))
# don't compute number or else it may
# over/underflow
return Float._new(
(num[0], num[1], num[2], bitcount(num[1])),
precision)
else:
try:
_mpf_ = num._as_mpf_val(precision)
except (NotImplementedError, AttributeError):
_mpf_ = mpmath.mpf(num, prec=precision)._mpf_
return cls._new(_mpf_, precision, zero=False)
@classmethod
def _new(cls, _mpf_, _prec, zero=True):
# special cases
if zero and _mpf_ == fzero:
return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0
elif _mpf_ == _mpf_nan:
return S.NaN
elif _mpf_ == _mpf_inf:
return S.Infinity
elif _mpf_ == _mpf_ninf:
return S.NegativeInfinity
obj = Expr.__new__(cls)
obj._mpf_ = mpf_norm(_mpf_, _prec)
obj._prec = _prec
return obj
# mpz can't be pickled
def __getnewargs__(self):
return (mlib.to_pickable(self._mpf_),)
def __getstate__(self):
return {'_prec': self._prec}
def _hashable_content(self):
return (self._mpf_, self._prec)
def floor(self):
return Integer(int(mlib.to_int(
mlib.mpf_floor(self._mpf_, self._prec))))
def ceiling(self):
return Integer(int(mlib.to_int(
mlib.mpf_ceil(self._mpf_, self._prec))))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
@property
def num(self):
return mpmath.mpf(self._mpf_)
def _as_mpf_val(self, prec):
rv = mpf_norm(self._mpf_, prec)
if rv != self._mpf_ and self._prec == prec:
debug(self._mpf_, rv)
return rv
def _as_mpf_op(self, prec):
return self._mpf_, max(prec, self._prec)
def _eval_is_finite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return False
return True
def _eval_is_infinite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return True
return False
def _eval_is_integer(self):
return self._mpf_ == fzero
def _eval_is_negative(self):
if self._mpf_ == _mpf_ninf or self._mpf_ == _mpf_inf:
return False
return self.num < 0
def _eval_is_positive(self):
if self._mpf_ == _mpf_ninf or self._mpf_ == _mpf_inf:
return False
return self.num > 0
def _eval_is_extended_negative(self):
if self._mpf_ == _mpf_ninf:
return True
if self._mpf_ == _mpf_inf:
return False
return self.num < 0
def _eval_is_extended_positive(self):
if self._mpf_ == _mpf_inf:
return True
if self._mpf_ == _mpf_ninf:
return False
return self.num > 0
def _eval_is_zero(self):
return self._mpf_ == fzero
def __bool__(self):
return self._mpf_ != fzero
def __neg__(self):
return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
return Number.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
return Number.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and other != 0 and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate:
# calculate mod with Rationals, *then* round the result
return Float(Rational.__mod__(Rational(self), other),
precision=self._prec)
if isinstance(other, Float) and global_parameters.evaluate:
r = self/other
if r == int(r):
return Float(0, precision=max(self._prec, other._prec))
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Float) and global_parameters.evaluate:
return other.__mod__(self)
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
"""
expt is symbolic object but not equal to 0, 1
(-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
-> p**r*(sin(Pi*r) + cos(Pi*r)*I)
"""
if self == 0:
if expt.is_positive:
return S.Zero
if expt.is_negative:
return S.Infinity
if isinstance(expt, Number):
if isinstance(expt, Integer):
prec = self._prec
return Float._new(
mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec)
elif isinstance(expt, Rational) and \
expt.p == 1 and expt.q % 2 and self.is_negative:
return Pow(S.NegativeOne, expt, evaluate=False)*(
-self)._eval_power(expt)
expt, prec = expt._as_mpf_op(self._prec)
mpfself = self._mpf_
try:
y = mpf_pow(mpfself, expt, prec, rnd)
return Float._new(y, prec)
except mlib.ComplexResult:
re, im = mlib.mpc_pow(
(mpfself, fzero), (expt, fzero), prec, rnd)
return Float._new(re, prec) + \
Float._new(im, prec)*S.ImaginaryUnit
def __abs__(self):
return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
def __int__(self):
if self._mpf_ == fzero:
return 0
return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
def __eq__(self, other):
from sympy.logic.boolalg import Boolean
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if isinstance(other, Boolean):
return False
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Float:
# comparison is exact
# so Float(.1, 3) != Float(.1, 33)
return self._mpf_ == other._mpf_
if other.is_Rational:
return other.__eq__(self)
if other.is_Number:
# numbers should compare at the same precision;
# all _as_mpf_val routines should be sure to abide
# by the request to change the prec if necessary; if
# they don't, the equality test will fail since it compares
# the mpf tuples
ompf = other._as_mpf_val(self._prec)
return bool(mlib.mpf_eq(self._mpf_, ompf))
if not self:
return not other
return False # Float != non-Number
def __ne__(self, other):
return not self == other
def _Frel(self, other, op):
from sympy.core.numbers import prec_to_dps
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Rational:
# test self*other.q <?> other.p without losing precision
'''
>>> f = Float(.1,2)
>>> i = 1234567890
>>> (f*i)._mpf_
(0, 471, 18, 9)
>>> mlib.mpf_mul(f._mpf_, mlib.from_int(i))
(0, 505555550955, -12, 39)
'''
smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q))
ompf = mlib.from_int(other.p)
return _sympify(bool(op(smpf, ompf)))
elif other.is_Float:
return _sympify(bool(
op(self._mpf_, other._mpf_)))
elif other.is_comparable and other not in (
S.Infinity, S.NegativeInfinity):
other = other.evalf(prec_to_dps(self._prec))
if other._prec > 1:
if other.is_Number:
return _sympify(bool(
op(self._mpf_, other._as_mpf_val(self._prec))))
def __gt__(self, other):
if isinstance(other, NumberSymbol):
return other.__lt__(self)
rv = self._Frel(other, mlib.mpf_gt)
if rv is None:
return Expr.__gt__(self, other)
return rv
def __ge__(self, other):
if isinstance(other, NumberSymbol):
return other.__le__(self)
rv = self._Frel(other, mlib.mpf_ge)
if rv is None:
return Expr.__ge__(self, other)
return rv
def __lt__(self, other):
if isinstance(other, NumberSymbol):
return other.__gt__(self)
rv = self._Frel(other, mlib.mpf_lt)
if rv is None:
return Expr.__lt__(self, other)
return rv
def __le__(self, other):
if isinstance(other, NumberSymbol):
return other.__ge__(self)
rv = self._Frel(other, mlib.mpf_le)
if rv is None:
return Expr.__le__(self, other)
return rv
def __hash__(self):
return super().__hash__()
def epsilon_eq(self, other, epsilon="1e-15"):
return abs(self - other) < Float(epsilon)
def _sage_(self):
import sage.all as sage
return sage.RealNumber(str(self))
def __format__(self, format_spec):
return format(decimal.Decimal(str(self)), format_spec)
# Add sympify converters
converter[float] = converter[decimal.Decimal] = Float
# this is here to work nicely in Sage
RealNumber = Float
class Rational(Number):
"""Represents rational numbers (p/q) of any size.
Examples
========
>>> from sympy import Rational, nsimplify, S, pi
>>> Rational(1, 2)
1/2
Rational is unprejudiced in accepting input. If a float is passed, the
underlying value of the binary representation will be returned:
>>> Rational(.5)
1/2
>>> Rational(.2)
3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider
limiting the denominator to the desired value or convert the float to
a string (which is roughly equivalent to limiting the denominator to
10**12):
>>> Rational(str(.2))
1/5
>>> Rational(.2).limit_denominator(10**12)
1/5
An arbitrarily precise Rational is obtained when a string literal is
passed:
>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10
>>> Rational('1e-2/3.2')
1/320
The conversion of other types of strings can be handled by
the sympify() function, and conversion of floats to expressions
or simple fractions can be handled with nsimplify:
>>> S('.[3]') # repeating digits in brackets
1/3
>>> S('3**2/10') # general expressions
9/10
>>> nsimplify(.3) # numbers that have a simple form
3/10
But if the input does not reduce to a literal Rational, an error will
be raised:
>>> Rational(pi)
Traceback (most recent call last):
...
TypeError: invalid input: pi
Low-level
---------
Access numerator and denominator as .p and .q:
>>> r = Rational(3, 4)
>>> r
3/4
>>> r.p
3
>>> r.q
4
Note that p and q return integers (not SymPy Integers) so some care
is needed when using them in expressions:
>>> r.p/r.q
0.75
See Also
========
sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify
"""
is_real = True
is_integer = False
is_rational = True
is_number = True
__slots__ = ('p', 'q')
is_Rational = True
@cacheit
def __new__(cls, p, q=None, gcd=None):
if q is None:
if isinstance(p, Rational):
return p
if isinstance(p, SYMPY_INTS):
pass
else:
if isinstance(p, (float, Float)):
return Rational(*_as_integer_ratio(p))
if not isinstance(p, str):
try:
p = sympify(p)
except (SympifyError, SyntaxError):
pass # error will raise below
else:
if p.count('/') > 1:
raise TypeError('invalid input: %s' % p)
p = p.replace(' ', '')
pq = p.rsplit('/', 1)
if len(pq) == 2:
p, q = pq
fp = fractions.Fraction(p)
fq = fractions.Fraction(q)
p = fp/fq
try:
p = fractions.Fraction(p)
except ValueError:
pass # error will raise below
else:
return Rational(p.numerator, p.denominator, 1)
if not isinstance(p, Rational):
raise TypeError('invalid input: %s' % p)
q = 1
gcd = 1
else:
p = Rational(p)
q = Rational(q)
if isinstance(q, Rational):
p *= q.q
q = q.p
if isinstance(p, Rational):
q *= p.q
p = p.p
# p and q are now integers
if q == 0:
if p == 0:
if _errdict["divide"]:
raise ValueError("Indeterminate 0/0")
else:
return S.NaN
return S.ComplexInfinity
if q < 0:
q = -q
p = -p
if not gcd:
gcd = igcd(abs(p), q)
if gcd > 1:
p //= gcd
q //= gcd
if q == 1:
return Integer(p)
if p == 1 and q == 2:
return S.Half
obj = Expr.__new__(cls)
obj.p = p
obj.q = q
return obj
def limit_denominator(self, max_denominator=1000000):
"""Closest Rational to self with denominator at most max_denominator.
Examples
========
>>> from sympy import Rational
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99
"""
f = fractions.Fraction(self.p, self.q)
return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator))))
def __getnewargs__(self):
return (self.p, self.q)
def _hashable_content(self):
return (self.p, self.q)
def _eval_is_positive(self):
return self.p > 0
def _eval_is_zero(self):
return self.p == 0
def __neg__(self):
return Rational(-self.p, self.q)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p + self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
#TODO: this can probably be optimized more
return Rational(self.p*other.q + self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return other + self
else:
return Number.__add__(self, other)
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p - self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.p*other.q - self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return -other + self
else:
return Number.__sub__(self, other)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.q*other.p - self.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.q*other.p - self.p*other.q, self.q*other.q)
elif isinstance(other, Float):
return -self + other
else:
return Number.__rsub__(self, other)
return Number.__rsub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p*other.p, self.q, igcd(other.p, self.q))
elif isinstance(other, Rational):
return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p))
elif isinstance(other, Float):
return other*self
else:
return Number.__mul__(self, other)
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
if self.p and other.p == S.Zero:
return S.ComplexInfinity
else:
return Rational(self.p, self.q*other.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return self*(1/other)
else:
return Number.__truediv__(self, other)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __rtruediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(other.p*self.q, self.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return other*(1/self)
else:
return Number.__rtruediv__(self, other)
return Number.__rtruediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, Rational):
n = (self.p*other.q) // (other.p*self.q)
return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q)
if isinstance(other, Float):
# calculate mod with Rationals, *then* round the answer
return Float(self.__mod__(Rational(other)),
precision=other._prec)
return Number.__mod__(self, other)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Rational):
return Rational.__mod__(other, self)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
if isinstance(expt, Number):
if isinstance(expt, Float):
return self._eval_evalf(expt._prec)**expt
if expt.is_extended_negative:
# (3/4)**-2 -> (4/3)**2
ne = -expt
if (ne is S.One):
return Rational(self.q, self.p)
if self.is_negative:
return S.NegativeOne**expt*Rational(self.q, -self.p)**ne
else:
return Rational(self.q, self.p)**ne
if expt is S.Infinity: # -oo already caught by test for negative
if self.p > self.q:
# (3/2)**oo -> oo
return S.Infinity
if self.p < -self.q:
# (-3/2)**oo -> oo + I*oo
return S.Infinity + S.Infinity*S.ImaginaryUnit
return S.Zero
if isinstance(expt, Integer):
# (4/3)**2 -> 4**2 / 3**2
return Rational(self.p**expt.p, self.q**expt.p, 1)
if isinstance(expt, Rational):
if self.p != 1:
# (4/3)**(5/6) -> 4**(5/6)*3**(-5/6)
return Integer(self.p)**expt*Integer(self.q)**(-expt)
# as the above caught negative self.p, now self is positive
return Integer(self.q)**Rational(
expt.p*(expt.q - 1), expt.q) / \
Integer(self.q)**Integer(expt.p)
if self.is_extended_negative and expt.is_even:
return (-self)**expt
return
def _as_mpf_val(self, prec):
return mlib.from_rational(self.p, self.q, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd))
def __abs__(self):
return Rational(abs(self.p), self.q)
def __int__(self):
p, q = self.p, self.q
if p < 0:
return -int(-p//q)
return int(p//q)
def floor(self):
return Integer(self.p // self.q)
def ceiling(self):
return -Integer(-self.p // self.q)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __eq__(self, other):
from sympy.core.power import integer_log
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if not isinstance(other, Number):
# S(0) == S.false is False
# S(0) == False is True
return False
if not self:
return not other
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Rational:
# a Rational is always in reduced form so will never be 2/4
# so we can just check equivalence of args
return self.p == other.p and self.q == other.q
if other.is_Float:
# all Floats have a denominator that is a power of 2
# so if self doesn't, it can't be equal to other
if self.q & (self.q - 1):
return False
s, m, t = other._mpf_[:3]
if s:
m = -m
if not t:
# other is an odd integer
if not self.is_Integer or self.is_even:
return False
return m == self.p
if t > 0:
# other is an even integer
if not self.is_Integer:
return False
# does m*2**t == self.p
return self.p and not self.p % m and \
integer_log(self.p//m, 2) == (t, True)
# does non-integer s*m/2**-t = p/q?
if self.is_Integer:
return False
return m == self.p and integer_log(self.q, 2) == (-t, True)
return False
def __ne__(self, other):
return not self == other
def _Rrel(self, other, attr):
# if you want self < other, pass self, other, __gt__
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Number:
op = None
s, o = self, other
if other.is_NumberSymbol:
op = getattr(o, attr)
elif other.is_Float:
op = getattr(o, attr)
elif other.is_Rational:
s, o = Integer(s.p*o.q), Integer(s.q*o.p)
op = getattr(o, attr)
if op:
return op(s)
if o.is_number and o.is_extended_real:
return Integer(s.p), s.q*o
def __gt__(self, other):
rv = self._Rrel(other, '__lt__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__gt__(*rv)
def __ge__(self, other):
rv = self._Rrel(other, '__le__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__ge__(*rv)
def __lt__(self, other):
rv = self._Rrel(other, '__gt__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__lt__(*rv)
def __le__(self, other):
rv = self._Rrel(other, '__ge__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__le__(*rv)
def __hash__(self):
return super().__hash__()
def factors(self, limit=None, use_trial=True, use_rho=False,
use_pm1=False, verbose=False, visual=False):
"""A wrapper to factorint which return factors of self that are
smaller than limit (or cheap to compute). Special methods of
factoring are disabled by default so that only trial division is used.
"""
from sympy.ntheory import factorrat
return factorrat(self, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
def numerator(self):
return self.p
def denominator(self):
return self.q
@_sympifyit('other', NotImplemented)
def gcd(self, other):
if isinstance(other, Rational):
if other == S.Zero:
return other
return Rational(
Integer(igcd(self.p, other.p)),
Integer(ilcm(self.q, other.q)))
return Number.gcd(self, other)
@_sympifyit('other', NotImplemented)
def lcm(self, other):
if isinstance(other, Rational):
return Rational(
self.p // igcd(self.p, other.p) * other.p,
igcd(self.q, other.q))
return Number.lcm(self, other)
def as_numer_denom(self):
return Integer(self.p), Integer(self.q)
def _sage_(self):
import sage.all as sage
return sage.Integer(self.p)/sage.Integer(self.q)
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import S
>>> (S(-3)/2).as_content_primitive()
(3/2, -1)
See docstring of Expr.as_content_primitive for more examples.
"""
if self:
if self.is_positive:
return self, S.One
return -self, S.NegativeOne
return S.One, self
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return self, S.One
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return self, S.Zero
class Integer(Rational):
"""Represents integer numbers of any size.
Examples
========
>>> from sympy import Integer
>>> Integer(3)
3
If a float or a rational is passed to Integer, the fractional part
will be discarded; the effect is of rounding toward zero.
>>> Integer(3.8)
3
>>> Integer(-3.8)
-3
A string is acceptable input if it can be parsed as an integer:
>>> Integer("9" * 20)
99999999999999999999
It is rarely needed to explicitly instantiate an Integer, because
Python integers are automatically converted to Integer when they
are used in SymPy expressions.
"""
q = 1
is_integer = True
is_number = True
is_Integer = True
__slots__ = ('p',)
def _as_mpf_val(self, prec):
return mlib.from_int(self.p, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(self._as_mpf_val(prec))
@cacheit
def __new__(cls, i):
if isinstance(i, str):
i = i.replace(' ', '')
# whereas we cannot, in general, make a Rational from an
# arbitrary expression, we can make an Integer unambiguously
# (except when a non-integer expression happens to round to
# an integer). So we proceed by taking int() of the input and
# let the int routines determine whether the expression can
# be made into an int or whether an error should be raised.
try:
ival = int(i)
except TypeError:
raise TypeError(
"Argument of Integer should be of numeric type, got %s." % i)
# We only work with well-behaved integer types. This converts, for
# example, numpy.int32 instances.
if ival == 1:
return S.One
if ival == -1:
return S.NegativeOne
if ival == 0:
return S.Zero
obj = Expr.__new__(cls)
obj.p = ival
return obj
def __getnewargs__(self):
return (self.p,)
# Arithmetic operations are here for efficiency
def __int__(self):
return self.p
def floor(self):
return Integer(self.p)
def ceiling(self):
return Integer(self.p)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __neg__(self):
return Integer(-self.p)
def __abs__(self):
if self.p >= 0:
return self
else:
return Integer(-self.p)
def __divmod__(self, other):
from .containers import Tuple
if isinstance(other, Integer) and global_parameters.evaluate:
return Tuple(*(divmod(self.p, other.p)))
else:
return Number.__divmod__(self, other)
def __rdivmod__(self, other):
from .containers import Tuple
if isinstance(other, int) and global_parameters.evaluate:
return Tuple(*(divmod(other, self.p)))
else:
try:
other = Number(other)
except TypeError:
msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
oname = type(other).__name__
sname = type(self).__name__
raise TypeError(msg % (oname, sname))
return Number.__divmod__(other, self)
# TODO make it decorator + bytecodehacks?
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p + other)
elif isinstance(other, Integer):
return Integer(self.p + other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q + other.p, other.q, 1)
return Rational.__add__(self, other)
else:
return Add(self, other)
def __radd__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other + self.p)
elif isinstance(other, Rational):
return Rational(other.p + self.p*other.q, other.q, 1)
return Rational.__radd__(self, other)
return Rational.__radd__(self, other)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p - other)
elif isinstance(other, Integer):
return Integer(self.p - other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q - other.p, other.q, 1)
return Rational.__sub__(self, other)
return Rational.__sub__(self, other)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other - self.p)
elif isinstance(other, Rational):
return Rational(other.p - self.p*other.q, other.q, 1)
return Rational.__rsub__(self, other)
return Rational.__rsub__(self, other)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p*other)
elif isinstance(other, Integer):
return Integer(self.p*other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.p, other.q, igcd(self.p, other.q))
return Rational.__mul__(self, other)
return Rational.__mul__(self, other)
def __rmul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other*self.p)
elif isinstance(other, Rational):
return Rational(other.p*self.p, other.q, igcd(self.p, other.q))
return Rational.__rmul__(self, other)
return Rational.__rmul__(self, other)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p % other)
elif isinstance(other, Integer):
return Integer(self.p % other.p)
return Rational.__mod__(self, other)
return Rational.__mod__(self, other)
def __rmod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other % self.p)
elif isinstance(other, Integer):
return Integer(other.p % self.p)
return Rational.__rmod__(self, other)
return Rational.__rmod__(self, other)
def __eq__(self, other):
if isinstance(other, int):
return (self.p == other)
elif isinstance(other, Integer):
return (self.p == other.p)
return Rational.__eq__(self, other)
def __ne__(self, other):
return not self == other
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p > other.p)
return Rational.__gt__(self, other)
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p < other.p)
return Rational.__lt__(self, other)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p >= other.p)
return Rational.__ge__(self, other)
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p <= other.p)
return Rational.__le__(self, other)
def __hash__(self):
return hash(self.p)
def __index__(self):
return self.p
########################################
def _eval_is_odd(self):
return bool(self.p % 2)
def _eval_power(self, expt):
"""
Tries to do some simplifications on self**expt
Returns None if no further simplifications can be done.
Explanation
===========
When exponent is a fraction (so we have for example a square root),
we try to find a simpler representation by factoring the argument
up to factors of 2**15, e.g.
- sqrt(4) becomes 2
- sqrt(-4) becomes 2*I
- (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
Further simplification would require a special call to factorint on
the argument which is not done here for sake of speed.
"""
from sympy.ntheory.factor_ import perfect_power
if expt is S.Infinity:
if self.p > S.One:
return S.Infinity
# cases -1, 0, 1 are done in their respective classes
return S.Infinity + S.ImaginaryUnit*S.Infinity
if expt is S.NegativeInfinity:
return Rational(1, self)**S.Infinity
if not isinstance(expt, Number):
# simplify when expt is even
# (-2)**k --> 2**k
if self.is_negative and expt.is_even:
return (-self)**expt
if isinstance(expt, Float):
# Rational knows how to exponentiate by a Float
return super()._eval_power(expt)
if not isinstance(expt, Rational):
return
if expt is S.Half and self.is_negative:
# we extract I for this special case since everyone is doing so
return S.ImaginaryUnit*Pow(-self, expt)
if expt.is_negative:
# invert base and change sign on exponent
ne = -expt
if self.is_negative:
return S.NegativeOne**expt*Rational(1, -self)**ne
else:
return Rational(1, self.p)**ne
# see if base is a perfect root, sqrt(4) --> 2
x, xexact = integer_nthroot(abs(self.p), expt.q)
if xexact:
# if it's a perfect root we've finished
result = Integer(x**abs(expt.p))
if self.is_negative:
result *= S.NegativeOne**expt
return result
# The following is an algorithm where we collect perfect roots
# from the factors of base.
# if it's not an nth root, it still might be a perfect power
b_pos = int(abs(self.p))
p = perfect_power(b_pos)
if p is not False:
dict = {p[0]: p[1]}
else:
dict = Integer(b_pos).factors(limit=2**15)
# now process the dict of factors
out_int = 1 # integer part
out_rad = 1 # extracted radicals
sqr_int = 1
sqr_gcd = 0
sqr_dict = {}
for prime, exponent in dict.items():
exponent *= expt.p
# remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
div_e, div_m = divmod(exponent, expt.q)
if div_e > 0:
out_int *= prime**div_e
if div_m > 0:
# see if the reduced exponent shares a gcd with e.q
# (2**2)**(1/10) -> 2**(1/5)
g = igcd(div_m, expt.q)
if g != 1:
out_rad *= Pow(prime, Rational(div_m//g, expt.q//g))
else:
sqr_dict[prime] = div_m
# identify gcd of remaining powers
for p, ex in sqr_dict.items():
if sqr_gcd == 0:
sqr_gcd = ex
else:
sqr_gcd = igcd(sqr_gcd, ex)
if sqr_gcd == 1:
break
for k, v in sqr_dict.items():
sqr_int *= k**(v//sqr_gcd)
if sqr_int == b_pos and out_int == 1 and out_rad == 1:
result = None
else:
result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
if self.is_negative:
result *= Pow(S.NegativeOne, expt)
return result
def _eval_is_prime(self):
from sympy.ntheory import isprime
return isprime(self)
def _eval_is_composite(self):
if self > 1:
return fuzzy_not(self.is_prime)
else:
return False
def as_numer_denom(self):
return self, S.One
@_sympifyit('other', NotImplemented)
def __floordiv__(self, other):
if not isinstance(other, Expr):
return NotImplemented
if isinstance(other, Integer):
return Integer(self.p // other)
return Integer(divmod(self, other)[0])
def __rfloordiv__(self, other):
return Integer(Integer(other).p // self.p)
# Add sympify converters
converter[int] = Integer
class AlgebraicNumber(Expr):
"""Class for representing algebraic numbers in SymPy. """
__slots__ = ('rep', 'root', 'alias', 'minpoly')
is_AlgebraicNumber = True
is_algebraic = True
is_number = True
kind = NumberKind
# Optional alias symbol is not free.
# Actually, alias should be a Str, but some methods
# expect that it be an instance of Expr.
free_symbols = set()
def __new__(cls, expr, coeffs=None, alias=None, **args):
"""Construct a new algebraic number. """
from sympy import Poly
from sympy.polys.polyclasses import ANP, DMP
from sympy.polys.numberfields import minimal_polynomial
from sympy.core.symbol import Symbol
expr = sympify(expr)
if isinstance(expr, (tuple, Tuple)):
minpoly, root = expr
if not minpoly.is_Poly:
minpoly = Poly(minpoly)
elif expr.is_AlgebraicNumber:
minpoly, root = expr.minpoly, expr.root
else:
minpoly, root = minimal_polynomial(
expr, args.get('gen'), polys=True), expr
dom = minpoly.get_domain()
if coeffs is not None:
if not isinstance(coeffs, ANP):
rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
scoeffs = Tuple(*coeffs)
else:
rep = DMP.from_list(coeffs.to_list(), 0, dom)
scoeffs = Tuple(*coeffs.to_list())
if rep.degree() >= minpoly.degree():
rep = rep.rem(minpoly.rep)
else:
rep = DMP.from_list([1, 0], 0, dom)
scoeffs = Tuple(1, 0)
sargs = (root, scoeffs)
if alias is not None:
if not isinstance(alias, Symbol):
alias = Symbol(alias)
sargs = sargs + (alias,)
obj = Expr.__new__(cls, *sargs)
obj.rep = rep
obj.root = root
obj.alias = alias
obj.minpoly = minpoly
return obj
def __hash__(self):
return super().__hash__()
def _eval_evalf(self, prec):
return self.as_expr()._evalf(prec)
@property
def is_aliased(self):
"""Returns ``True`` if ``alias`` was set. """
return self.alias is not None
def as_poly(self, x=None):
"""Create a Poly instance from ``self``. """
from sympy import Dummy, Poly, PurePoly
if x is not None:
return Poly.new(self.rep, x)
else:
if self.alias is not None:
return Poly.new(self.rep, self.alias)
else:
return PurePoly.new(self.rep, Dummy('x'))
def as_expr(self, x=None):
"""Create a Basic expression from ``self``. """
return self.as_poly(x or self.root).as_expr().expand()
def coeffs(self):
"""Returns all SymPy coefficients of an algebraic number. """
return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ]
def native_coeffs(self):
"""Returns all native coefficients of an algebraic number. """
return self.rep.all_coeffs()
def to_algebraic_integer(self):
"""Convert ``self`` to an algebraic integer. """
from sympy import Poly
f = self.minpoly
if f.LC() == 1:
return self
coeff = f.LC()**(f.degree() - 1)
poly = f.compose(Poly(f.gen/f.LC()))
minpoly = poly*coeff
root = f.LC()*self.root
return AlgebraicNumber((minpoly, root), self.coeffs())
def _eval_simplify(self, **kwargs):
from sympy.polys import CRootOf, minpoly
measure, ratio = kwargs['measure'], kwargs['ratio']
for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]:
if minpoly(self.root - r).is_Symbol:
# use the matching root if it's simpler
if measure(r) < ratio*measure(self.root):
return AlgebraicNumber(r)
return self
class RationalConstant(Rational):
"""
Abstract base class for rationals with specific behaviors
Derived classes must define class attributes p and q and should probably all
be singletons.
"""
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class IntegerConstant(Integer):
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class Zero(IntegerConstant, metaclass=Singleton):
"""The number zero.
Zero is a singleton, and can be accessed by ``S.Zero``
Examples
========
>>> from sympy import S, Integer
>>> Integer(0) is S.Zero
True
>>> 1/S.Zero
zoo
References
==========
.. [1] https://en.wikipedia.org/wiki/Zero
"""
p = 0
q = 1
is_positive = False
is_negative = False
is_zero = True
is_number = True
is_comparable = True
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Zero
@staticmethod
def __neg__():
return S.Zero
def _eval_power(self, expt):
if expt.is_positive:
return self
if expt.is_negative:
return S.ComplexInfinity
if expt.is_extended_real is False:
return S.NaN
# infinities are already handled with pos and neg
# tests above; now throw away leading numbers on Mul
# exponent
coeff, terms = expt.as_coeff_Mul()
if coeff.is_negative:
return S.ComplexInfinity**terms
if coeff is not S.One: # there is a Number to discard
return self**terms
def _eval_order(self, *symbols):
# Order(0,x) -> 0
return self
def __bool__(self):
return False
def as_coeff_Mul(self, rational=False): # XXX this routine should be deleted
"""Efficiently extract the coefficient of a summation. """
return S.One, self
class One(IntegerConstant, metaclass=Singleton):
"""The number one.
One is a singleton, and can be accessed by ``S.One``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(1) is S.One
True
References
==========
.. [1] https://en.wikipedia.org/wiki/1_%28number%29
"""
is_number = True
p = 1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.NegativeOne
def _eval_power(self, expt):
return self
def _eval_order(self, *symbols):
return
@staticmethod
def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False,
verbose=False, visual=False):
if visual:
return S.One
else:
return {}
class NegativeOne(IntegerConstant, metaclass=Singleton):
"""The number negative one.
NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(-1) is S.NegativeOne
True
See Also
========
One
References
==========
.. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
"""
is_number = True
p = -1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.One
def _eval_power(self, expt):
if expt.is_odd:
return S.NegativeOne
if expt.is_even:
return S.One
if isinstance(expt, Number):
if isinstance(expt, Float):
return Float(-1.0)**expt
if expt is S.NaN:
return S.NaN
if expt is S.Infinity or expt is S.NegativeInfinity:
return S.NaN
if expt is S.Half:
return S.ImaginaryUnit
if isinstance(expt, Rational):
if expt.q == 2:
return S.ImaginaryUnit**Integer(expt.p)
i, r = divmod(expt.p, expt.q)
if i:
return self**i*self**Rational(r, expt.q)
return
class Half(RationalConstant, metaclass=Singleton):
"""The rational number 1/2.
Half is a singleton, and can be accessed by ``S.Half``.
Examples
========
>>> from sympy import S, Rational
>>> Rational(1, 2) is S.Half
True
References
==========
.. [1] https://en.wikipedia.org/wiki/One_half
"""
is_number = True
p = 1
q = 2
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Half
class Infinity(Number, metaclass=Singleton):
r"""Positive infinite quantity.
Explanation
===========
In real analysis the symbol `\infty` denotes an unbounded
limit: `x\to\infty` means that `x` grows without bound.
Infinity is often used not only to define a limit but as a value
in the affinely extended real number system. Points labeled `+\infty`
and `-\infty` can be added to the topological space of the real numbers,
producing the two-point compactification of the real numbers. Adding
algebraic properties to this gives us the extended real numbers.
Infinity is a singleton, and can be accessed by ``S.Infinity``,
or can be imported as ``oo``.
Examples
========
>>> from sympy import oo, exp, limit, Symbol
>>> 1 + oo
oo
>>> 42/oo
0
>>> x = Symbol('x')
>>> limit(exp(x), x, oo)
oo
See Also
========
NegativeInfinity, NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Infinity
"""
is_commutative = True
is_number = True
is_complex = False
is_extended_real = True
is_infinite = True
is_comparable = True
is_extended_positive = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NegativeInfinity or other is S.NaN:
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or other is S.NaN:
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.NegativeInfinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.NegativeInfinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.NegativeInfinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``oo ** nan`` ``nan``
``oo ** -p`` ``0`` ``p`` is number, ``oo``
================ ======= ==============================
See Also
========
Pow
NaN
NegativeInfinity
"""
from sympy.functions import re
if expt.is_extended_positive:
return S.Infinity
if expt.is_extended_negative:
return S.Zero
if expt is S.NaN:
return S.NaN
if expt is S.ComplexInfinity:
return S.NaN
if expt.is_extended_real is False and expt.is_number:
expt_real = re(expt)
if expt_real.is_positive:
return S.ComplexInfinity
if expt_real.is_negative:
return S.Zero
if expt_real.is_zero:
return S.NaN
return self**expt.evalf()
def _as_mpf_val(self, prec):
return mlib.finf
def _sage_(self):
import sage.all as sage
return sage.oo
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.Infinity or other == float('inf')
def __ne__(self, other):
return other is not S.Infinity and other != float('inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
oo = S.Infinity
class NegativeInfinity(Number, metaclass=Singleton):
"""Negative infinite quantity.
NegativeInfinity is a singleton, and can be accessed
by ``S.NegativeInfinity``.
See Also
========
Infinity
"""
is_extended_real = True
is_complex = False
is_commutative = True
is_infinite = True
is_comparable = True
is_extended_negative = True
is_number = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"-\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('-inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or other is S.NaN:
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NegativeInfinity or other is S.NaN:
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.Infinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.Infinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.Infinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``(-oo) ** nan`` ``nan``
``(-oo) ** oo`` ``nan``
``(-oo) ** -oo`` ``nan``
``(-oo) ** e`` ``oo`` ``e`` is positive even integer
``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer
================ ======= ==============================
See Also
========
Infinity
Pow
NaN
"""
if expt.is_number:
if expt is S.NaN or \
expt is S.Infinity or \
expt is S.NegativeInfinity:
return S.NaN
if isinstance(expt, Integer) and expt.is_extended_positive:
if expt.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
return S.NegativeOne**expt*S.Infinity**expt
def _as_mpf_val(self, prec):
return mlib.fninf
def _sage_(self):
import sage.all as sage
return -(sage.oo)
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.NegativeInfinity or other == float('-inf')
def __ne__(self, other):
return other is not S.NegativeInfinity and other != float('-inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
def as_powers_dict(self):
return {S.NegativeOne: 1, S.Infinity: 1}
class NaN(Number, metaclass=Singleton):
"""
Not a Number.
Explanation
===========
This serves as a place holder for numeric values that are indeterminate.
Most operations on NaN, produce another NaN. Most indeterminate forms,
such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0``
and ``oo**0``, which all produce ``1`` (this is consistent with Python's
float).
NaN is loosely related to floating point nan, which is defined in the
IEEE 754 floating point standard, and corresponds to the Python
``float('nan')``. Differences are noted below.
NaN is mathematically not equal to anything else, even NaN itself. This
explains the initially counter-intuitive results with ``Eq`` and ``==`` in
the examples below.
NaN is not comparable so inequalities raise a TypeError. This is in
contrast with floating point nan where all inequalities are false.
NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported
as ``nan``.
Examples
========
>>> from sympy import nan, S, oo, Eq
>>> nan is S.NaN
True
>>> oo - oo
nan
>>> nan + 1
nan
>>> Eq(nan, nan) # mathematical equality
False
>>> nan == nan # structural equality
True
References
==========
.. [1] https://en.wikipedia.org/wiki/NaN
"""
is_commutative = True
is_extended_real = None
is_real = None
is_rational = None
is_algebraic = None
is_transcendental = None
is_integer = None
is_comparable = False
is_finite = None
is_zero = None
is_prime = None
is_positive = None
is_negative = None
is_number = True
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\text{NaN}"
def __neg__(self):
return self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
return self
def floor(self):
return self
def ceiling(self):
return self
def _as_mpf_val(self, prec):
return _mpf_nan
def _sage_(self):
import sage.all as sage
return sage.NaN
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
# NaN is structurally equal to another NaN
return other is S.NaN
def __ne__(self, other):
return other is not S.NaN
# Expr will _sympify and raise TypeError
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
nan = S.NaN
@dispatch(NaN, Expr) # type:ignore
def _eval_is_eq(a, b): # noqa:F811
return False
class ComplexInfinity(AtomicExpr, metaclass=Singleton):
r"""Complex infinity.
Explanation
===========
In complex analysis the symbol `\tilde\infty`, called "complex
infinity", represents a quantity with infinite magnitude, but
undetermined complex phase.
ComplexInfinity is a singleton, and can be accessed by
``S.ComplexInfinity``, or can be imported as ``zoo``.
Examples
========
>>> from sympy import zoo
>>> zoo + 42
zoo
>>> 42/zoo
0
>>> zoo + zoo
nan
>>> zoo*zoo
zoo
See Also
========
Infinity
"""
is_commutative = True
is_infinite = True
is_number = True
is_prime = False
is_complex = False
is_extended_real = False
kind = NumberKind
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\tilde{\infty}"
@staticmethod
def __abs__():
return S.Infinity
def floor(self):
return self
def ceiling(self):
return self
@staticmethod
def __neg__():
return S.ComplexInfinity
def _eval_power(self, expt):
if expt is S.ComplexInfinity:
return S.NaN
if isinstance(expt, Number):
if expt.is_zero:
return S.NaN
else:
if expt.is_positive:
return S.ComplexInfinity
else:
return S.Zero
def _sage_(self):
import sage.all as sage
return sage.UnsignedInfinityRing.gen()
zoo = S.ComplexInfinity
class NumberSymbol(AtomicExpr):
is_commutative = True
is_finite = True
is_number = True
__slots__ = ()
is_NumberSymbol = True
kind = NumberKind
def __new__(cls):
return AtomicExpr.__new__(cls)
def approximation(self, number_cls):
""" Return an interval with number_cls endpoints
that contains the value of NumberSymbol.
If not implemented, then return None.
"""
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def __eq__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if self is other:
return True
if other.is_Number and self.is_irrational:
return False
return False # NumberSymbol != non-(Number|self)
def __ne__(self, other):
return not self == other
def __le__(self, other):
if self is other:
return S.true
return Expr.__le__(self, other)
def __ge__(self, other):
if self is other:
return S.true
return Expr.__ge__(self, other)
def __int__(self):
# subclass with appropriate return value
raise NotImplementedError
def __hash__(self):
return super().__hash__()
class Exp1(NumberSymbol, metaclass=Singleton):
r"""The `e` constant.
Explanation
===========
The transcendental number `e = 2.718281828\ldots` is the base of the
natural logarithm and of the exponential function, `e = \exp(1)`.
Sometimes called Euler's number or Napier's constant.
Exp1 is a singleton, and can be accessed by ``S.Exp1``,
or can be imported as ``E``.
Examples
========
>>> from sympy import exp, log, E
>>> E is exp(1)
True
>>> log(E)
1
References
==========
.. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
"""
is_real = True
is_positive = True
is_negative = False # XXX Forces is_negative/is_nonnegative
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"e"
@staticmethod
def __abs__():
return S.Exp1
def __int__(self):
return 2
def _as_mpf_val(self, prec):
return mpf_e(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(2), Integer(3))
elif issubclass(number_cls, Rational):
pass
def _eval_power(self, expt):
from sympy import exp
if global_parameters.exp_is_pow:
return self._eval_power_exp_is_pow(expt)
else:
return exp(expt)
def _eval_power_exp_is_pow(self, arg):
from ..functions.elementary.exponential import log
from . import Add, Mul, Pow
if arg.is_Number:
if arg is oo:
return oo
elif arg == -oo:
return S.Zero
elif isinstance(arg, log):
return arg.args[0]
# don't autoexpand Pow or Mul (see the issue 3351):
elif not arg.is_Add:
Ioo = I*oo
if arg in [Ioo, -Ioo]:
return nan
coeff = arg.coeff(pi*I)
if coeff:
if (2*coeff).is_integer:
if coeff.is_even:
return S.One
elif coeff.is_odd:
return S.NegativeOne
elif (coeff + S.Half).is_even:
return -I
elif (coeff + S.Half).is_odd:
return I
elif coeff.is_Rational:
ncoeff = coeff % 2 # restrict to [0, 2pi)
if ncoeff > 1: # restrict to (-pi, pi]
ncoeff -= 2
if ncoeff != coeff:
return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit)
# Warning: code in risch.py will be very sensitive to changes
# in this (see DifferentialExtension).
# look for a single log factor
coeff, terms = arg.as_coeff_Mul()
# but it can't be multiplied by oo
if coeff in (oo, -oo):
return
coeffs, log_term = [coeff], None
for term in Mul.make_args(terms):
if isinstance(term, log):
if log_term is None:
log_term = term.args[0]
else:
return
elif term.is_comparable:
coeffs.append(term)
else:
return
return log_term**Mul(*coeffs) if log_term else None
elif arg.is_Add:
out = []
add = []
argchanged = False
for a in arg.args:
if a is S.One:
add.append(a)
continue
newa = self**a
if isinstance(newa, Pow) and newa.base is self:
if newa.exp != a:
add.append(newa.exp)
argchanged = True
else:
add.append(a)
else:
out.append(newa)
if out or argchanged:
return Mul(*out)*Pow(self, Add(*add), evaluate=False)
elif arg.is_Matrix:
return arg.exp()
def _eval_rewrite_as_sin(self, **kwargs):
from sympy import sin
I = S.ImaginaryUnit
return sin(I + S.Pi/2) - I*sin(I)
def _eval_rewrite_as_cos(self, **kwargs):
from sympy import cos
I = S.ImaginaryUnit
return cos(I) + I*cos(I + S.Pi/2)
def _sage_(self):
import sage.all as sage
return sage.e
E = S.Exp1
class Pi(NumberSymbol, metaclass=Singleton):
r"""The `\pi` constant.
Explanation
===========
The transcendental number `\pi = 3.141592654\ldots` represents the ratio
of a circle's circumference to its diameter, the area of the unit circle,
the half-period of trigonometric functions, and many other things
in mathematics.
Pi is a singleton, and can be accessed by ``S.Pi``, or can
be imported as ``pi``.
Examples
========
>>> from sympy import S, pi, oo, sin, exp, integrate, Symbol
>>> S.Pi
pi
>>> pi > 3
True
>>> pi.is_irrational
True
>>> x = Symbol('x')
>>> sin(x + 2*pi)
sin(x)
>>> integrate(exp(-x**2), (x, -oo, oo))
sqrt(pi)
References
==========
.. [1] https://en.wikipedia.org/wiki/Pi
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"\pi"
@staticmethod
def __abs__():
return S.Pi
def __int__(self):
return 3
def _as_mpf_val(self, prec):
return mpf_pi(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(3), Integer(4))
elif issubclass(number_cls, Rational):
return (Rational(223, 71), Rational(22, 7))
def _sage_(self):
import sage.all as sage
return sage.pi
pi = S.Pi
class GoldenRatio(NumberSymbol, metaclass=Singleton):
r"""The golden ratio, `\phi`.
Explanation
===========
`\phi = \frac{1 + \sqrt{5}}{2}` is algebraic number. Two quantities
are in the golden ratio if their ratio is the same as the ratio of
their sum to the larger of the two quantities, i.e. their maximum.
GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``.
Examples
========
>>> from sympy import S
>>> S.GoldenRatio > 1
True
>>> S.GoldenRatio.expand(func=True)
1/2 + sqrt(5)/2
>>> S.GoldenRatio.is_irrational
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Golden_ratio
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\phi"
def __int__(self):
return 1
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10)
return mpf_norm(rv, prec)
def _eval_expand_func(self, **hints):
from sympy import sqrt
return S.Half + S.Half*sqrt(5)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
def _sage_(self):
import sage.all as sage
return sage.golden_ratio
_eval_rewrite_as_sqrt = _eval_expand_func
class TribonacciConstant(NumberSymbol, metaclass=Singleton):
r"""The tribonacci constant.
Explanation
===========
The tribonacci numbers are like the Fibonacci numbers, but instead
of starting with two predetermined terms, the sequence starts with
three predetermined terms and each term afterwards is the sum of the
preceding three terms.
The tribonacci constant is the ratio toward which adjacent tribonacci
numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`,
and also satisfies the equation `x + x^{-3} = 2`.
TribonacciConstant is a singleton, and can be accessed
by ``S.TribonacciConstant``.
Examples
========
>>> from sympy import S
>>> S.TribonacciConstant > 1
True
>>> S.TribonacciConstant.expand(func=True)
1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3
>>> S.TribonacciConstant.is_irrational
True
>>> S.TribonacciConstant.n(20)
1.8392867552141611326
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\text{TribonacciConstant}"
def __int__(self):
return 2
def _eval_evalf(self, prec):
rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4)
return Float(rv, precision=prec)
def _eval_expand_func(self, **hints):
from sympy import sqrt, cbrt
return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
_eval_rewrite_as_sqrt = _eval_expand_func
class EulerGamma(NumberSymbol, metaclass=Singleton):
r"""The Euler-Mascheroni constant.
Explanation
===========
`\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
constant recurring in analysis and number theory. It is defined as the
limiting difference between the harmonic series and the
natural logarithm:
.. math:: \gamma = \lim\limits_{n\to\infty}
\left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
Examples
========
>>> from sympy import S
>>> S.EulerGamma.is_irrational
>>> S.EulerGamma > 0
True
>>> S.EulerGamma > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def _latex(self, printer):
return r"\gamma"
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.libhyper.euler_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (S.Half, Rational(3, 5))
def _sage_(self):
import sage.all as sage
return sage.euler_gamma
class Catalan(NumberSymbol, metaclass=Singleton):
r"""Catalan's constant.
Explanation
===========
`K = 0.91596559\ldots` is given by the infinite series
.. math:: K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}
Catalan is a singleton, and can be accessed by ``S.Catalan``.
Examples
========
>>> from sympy import S
>>> S.Catalan.is_irrational
>>> S.Catalan > 0
True
>>> S.Catalan > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.catalan_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (Rational(9, 10), S.One)
def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
from sympy import Sum, Dummy
if (k_sym is not None) or (symbols is not None):
return self
k = Dummy('k', integer=True, nonnegative=True)
return Sum((-1)**k / (2*k+1)**2, (k, 0, S.Infinity))
def _sage_(self):
import sage.all as sage
return sage.catalan
class ImaginaryUnit(AtomicExpr, metaclass=Singleton):
r"""The imaginary unit, `i = \sqrt{-1}`.
I is a singleton, and can be accessed by ``S.I``, or can be
imported as ``I``.
Examples
========
>>> from sympy import I, sqrt
>>> sqrt(-1)
I
>>> I*I
-1
>>> 1/I
-I
References
==========
.. [1] https://en.wikipedia.org/wiki/Imaginary_unit
"""
is_commutative = True
is_imaginary = True
is_finite = True
is_number = True
is_algebraic = True
is_transcendental = False
kind = NumberKind
__slots__ = ()
def _latex(self, printer):
return printer._settings['imaginary_unit_latex']
@staticmethod
def __abs__():
return S.One
def _eval_evalf(self, prec):
return self
def _eval_conjugate(self):
return -S.ImaginaryUnit
def _eval_power(self, expt):
"""
b is I = sqrt(-1)
e is symbolic object but not equal to 0, 1
I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal
I**0 mod 4 -> 1
I**1 mod 4 -> I
I**2 mod 4 -> -1
I**3 mod 4 -> -I
"""
if isinstance(expt, Number):
if isinstance(expt, Integer):
expt = expt.p % 4
if expt == 0:
return S.One
if expt == 1:
return S.ImaginaryUnit
if expt == 2:
return -S.One
return -S.ImaginaryUnit
return
def as_base_exp(self):
return S.NegativeOne, S.Half
def _sage_(self):
import sage.all as sage
return sage.I
@property
def _mpc_(self):
return (Float(0)._mpf_, Float(1)._mpf_)
I = S.ImaginaryUnit
@dispatch(Tuple, Number) # type:ignore
def _eval_is_eq(self, other): # noqa: F811
return False
def sympify_fractions(f):
return Rational(f.numerator, f.denominator, 1)
converter[fractions.Fraction] = sympify_fractions
if HAS_GMPY:
def sympify_mpz(x):
return Integer(int(x))
# XXX: The sympify_mpq function here was never used because it is
# overridden by the other sympify_mpq function below. Maybe it should just
# be removed or maybe it should be used for something...
def sympify_mpq(x):
return Rational(int(x.numerator), int(x.denominator))
converter[type(gmpy.mpz(1))] = sympify_mpz
converter[type(gmpy.mpq(1, 2))] = sympify_mpq
def sympify_mpmath_mpq(x):
p, q = x._mpq_
return Rational(p, q, 1)
converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
def sympify_mpmath(x):
return Expr._from_mpmath(x, x.context.prec)
converter[mpnumeric] = sympify_mpmath
def sympify_complex(a):
real, imag = list(map(sympify, (a.real, a.imag)))
return real + S.ImaginaryUnit*imag
converter[complex] = sympify_complex
from .power import Pow, integer_nthroot
from .mul import Mul
Mul.identity = One()
from .add import Add
Add.identity = Zero()
def _register_classes():
numbers.Number.register(Number)
numbers.Real.register(Float)
numbers.Rational.register(Rational)
numbers.Rational.register(Integer)
_register_classes()
|
b0e0321af376ded04b200a0689e5047b6b2e2cbf88a81a88ae0283db19f0f2b6 | from sympy.core.assumptions import StdFactKB, _assume_defined
from sympy.core.compatibility import is_sequence, ordered
from .basic import Basic, Atom
from .sympify import sympify
from .singleton import S
from .expr import Expr, AtomicExpr
from .cache import cacheit
from .function import FunctionClass
from .kind import NumberKind, UndefinedKind
from sympy.core.logic import fuzzy_bool
from sympy.logic.boolalg import Boolean
from sympy.utilities.iterables import cartes, sift
from sympy.core.containers import Tuple
import string
import re as _re
import random
class Str(Atom):
"""
Represents string in SymPy.
Explanation
===========
Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy
objects, e.g. denoting the name of the instance. However, since ``Symbol``
represents mathematical scalar, this class should be used instead.
"""
__slots__ = ('name',)
def __new__(cls, name, **kwargs):
if not isinstance(name, str):
raise TypeError("name should be a string, not %s" % repr(type(name)))
obj = Expr.__new__(cls, **kwargs)
obj.name = name
return obj
def __getnewargs__(self):
return (self.name,)
def _hashable_content(self):
return (self.name,)
def _filter_assumptions(kwargs):
"""Split the given dict into assumptions and non-assumptions.
Keys are taken as assumptions if they correspond to an
entry in ``_assume_defined``.
"""
assumptions, nonassumptions = map(dict, sift(kwargs.items(),
lambda i: i[0] in _assume_defined,
binary=True))
Symbol._sanitize(assumptions)
return assumptions, nonassumptions
def _symbol(s, matching_symbol=None, **assumptions):
"""Return s if s is a Symbol, else if s is a string, return either
the matching_symbol if the names are the same or else a new symbol
with the same assumptions as the matching symbol (or the
assumptions as provided).
Examples
========
>>> from sympy import Symbol
>>> from sympy.core.symbol import _symbol
>>> _symbol('y')
y
>>> _.is_real is None
True
>>> _symbol('y', real=True).is_real
True
>>> x = Symbol('x')
>>> _symbol(x, real=True)
x
>>> _.is_real is None # ignore attribute if s is a Symbol
True
Below, the variable sym has the name 'foo':
>>> sym = Symbol('foo', real=True)
Since 'x' is not the same as sym's name, a new symbol is created:
>>> _symbol('x', sym).name
'x'
It will acquire any assumptions give:
>>> _symbol('x', sym, real=False).is_real
False
Since 'foo' is the same as sym's name, sym is returned
>>> _symbol('foo', sym)
foo
Any assumptions given are ignored:
>>> _symbol('foo', sym, real=False).is_real
True
NB: the symbol here may not be the same as a symbol with the same
name defined elsewhere as a result of different assumptions.
See Also
========
sympy.core.symbol.Symbol
"""
if isinstance(s, str):
if matching_symbol and matching_symbol.name == s:
return matching_symbol
return Symbol(s, **assumptions)
elif isinstance(s, Symbol):
return s
else:
raise ValueError('symbol must be string for symbol name or Symbol')
def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions):
"""Return a symbol which, when printed, will have a name unique
from any other already in the expressions given. The name is made
unique by appending numbers (default) but this can be
customized with the keyword 'modify'.
Parameters
==========
xname : a string or a Symbol (when symbol xname <- str(xname))
compare : a single arg function that takes a symbol and returns
a string to be compared with xname (the default is the str
function which indicates how the name will look when it
is printed, e.g. this includes underscores that appear on
Dummy symbols)
modify : a single arg function that changes its string argument
in some way (the default is to append numbers)
Examples
========
>>> from sympy.core.symbol import uniquely_named_symbol
>>> from sympy.abc import x
>>> uniquely_named_symbol('x', x)
x0
"""
from sympy.core.function import AppliedUndef
def numbered_string_incr(s, start=0):
if not s:
return str(start)
i = len(s) - 1
while i != -1:
if not s[i].isdigit():
break
i -= 1
n = str(int(s[i + 1:] or start - 1) + 1)
return s[:i + 1] + n
default = None
if is_sequence(xname):
xname, default = xname
x = str(xname)
if not exprs:
return _symbol(x, default, **assumptions)
if not is_sequence(exprs):
exprs = [exprs]
names = set().union(
[i.name for e in exprs for i in e.atoms(Symbol)] +
[i.func.name for e in exprs for i in e.atoms(AppliedUndef)])
if modify is None:
modify = numbered_string_incr
while any(x == compare(s) for s in names):
x = modify(x)
return _symbol(x, default, **assumptions)
_uniquely_named_symbol = uniquely_named_symbol
class Symbol(AtomicExpr, Boolean):
"""
Assumptions:
commutative = True
You can override the default assumptions in the constructor.
Examples
========
>>> from sympy import symbols
>>> A,B = symbols('A,B', commutative = False)
>>> bool(A*B != B*A)
True
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
True
"""
is_comparable = False
__slots__ = ('name',)
is_Symbol = True
is_symbol = True
@property
def kind(self):
if self.is_commutative:
return NumberKind
return UndefinedKind
@property
def _diff_wrt(self):
"""Allow derivatives wrt Symbols.
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> x._diff_wrt
True
"""
return True
@staticmethod
def _sanitize(assumptions, obj=None):
"""Remove None, covert values to bool, check commutativity *in place*.
"""
# be strict about commutativity: cannot be None
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
if is_commutative is None:
whose = '%s ' % obj.__name__ if obj else ''
raise ValueError(
'%scommutativity must be True or False.' % whose)
# sanitize other assumptions so 1 -> True and 0 -> False
for key in list(assumptions.keys()):
v = assumptions[key]
if v is None:
assumptions.pop(key)
continue
assumptions[key] = bool(v)
def _merge(self, assumptions):
base = self.assumptions0
for k in set(assumptions) & set(base):
if assumptions[k] != base[k]:
from sympy.utilities.misc import filldedent
raise ValueError(filldedent('''
non-matching assumptions for %s: existing value
is %s and new value is %s''' % (
k, base[k], assumptions[k])))
base.update(assumptions)
return base
def __new__(cls, name, **assumptions):
"""Symbols are identified by name and assumptions::
>>> from sympy import Symbol
>>> Symbol("x") == Symbol("x")
True
>>> Symbol("x", real=True) == Symbol("x", real=False)
False
"""
cls._sanitize(assumptions, cls)
return Symbol.__xnew_cached_(cls, name, **assumptions)
def __new_stage2__(cls, name, **assumptions):
if not isinstance(name, str):
raise TypeError("name should be a string, not %s" % repr(type(name)))
obj = Expr.__new__(cls)
obj.name = name
# TODO: Issue #8873: Forcing the commutative assumption here means
# later code such as ``srepr()`` cannot tell whether the user
# specified ``commutative=True`` or omitted it. To workaround this,
# we keep a copy of the assumptions dict, then create the StdFactKB,
# and finally overwrite its ``._generator`` with the dict copy. This
# is a bit of a hack because we assume StdFactKB merely copies the
# given dict as ``._generator``, but future modification might, e.g.,
# compute a minimal equivalent assumption set.
tmp_asm_copy = assumptions.copy()
# be strict about commutativity
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
assumptions['commutative'] = is_commutative
obj._assumptions = StdFactKB(assumptions)
obj._assumptions._generator = tmp_asm_copy # Issue #8873
return obj
__xnew__ = staticmethod(
__new_stage2__) # never cached (e.g. dummy)
__xnew_cached_ = staticmethod(
cacheit(__new_stage2__)) # symbols are always cached
def __getnewargs__(self):
return (self.name,)
def __getstate__(self):
return {'_assumptions': self._assumptions}
def _hashable_content(self):
# Note: user-specified assumptions not hashed, just derived ones
return (self.name,) + tuple(sorted(self.assumptions0.items()))
def _eval_subs(self, old, new):
from sympy.core.power import Pow
if old.is_Pow:
return Pow(self, S.One, evaluate=False)._eval_subs(old, new)
def _eval_refine(self, assumptions):
return self
@property
def assumptions0(self):
return {key: value for key, value
in self._assumptions.items() if value is not None}
@cacheit
def sort_key(self, order=None):
return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One
def as_dummy(self):
# only put commutativity in explicitly if it is False
return Dummy(self.name) if self.is_commutative is not False \
else Dummy(self.name, commutative=self.is_commutative)
def as_real_imag(self, deep=True, **hints):
from sympy import im, re
if hints.get('ignore') == self:
return None
else:
return (re(self), im(self))
def _sage_(self):
import sage.all as sage
return sage.var(self.name)
def is_constant(self, *wrt, **flags):
if not wrt:
return False
return not self in wrt
@property
def free_symbols(self):
return {self}
binary_symbols = free_symbols # in this case, not always
def as_set(self):
return S.UniversalSet
class Dummy(Symbol):
"""Dummy symbols are each unique, even if they have the same name:
Examples
========
>>> from sympy import Dummy
>>> Dummy("x") == Dummy("x")
False
If a name is not supplied then a string value of an internal count will be
used. This is useful when a temporary variable is needed and the name
of the variable used in the expression is not important.
>>> Dummy() #doctest: +SKIP
_Dummy_10
"""
# In the rare event that a Dummy object needs to be recreated, both the
# `name` and `dummy_index` should be passed. This is used by `srepr` for
# example:
# >>> d1 = Dummy()
# >>> d2 = eval(srepr(d1))
# >>> d2 == d1
# True
#
# If a new session is started between `srepr` and `eval`, there is a very
# small chance that `d2` will be equal to a previously-created Dummy.
_count = 0
_prng = random.Random()
_base_dummy_index = _prng.randint(10**6, 9*10**6)
__slots__ = ('dummy_index',)
is_Dummy = True
def __new__(cls, name=None, dummy_index=None, **assumptions):
if dummy_index is not None:
assert name is not None, "If you specify a dummy_index, you must also provide a name"
if name is None:
name = "Dummy_" + str(Dummy._count)
if dummy_index is None:
dummy_index = Dummy._base_dummy_index + Dummy._count
Dummy._count += 1
cls._sanitize(assumptions, cls)
obj = Symbol.__xnew__(cls, name, **assumptions)
obj.dummy_index = dummy_index
return obj
def __getstate__(self):
return {'_assumptions': self._assumptions, 'dummy_index': self.dummy_index}
@cacheit
def sort_key(self, order=None):
return self.class_key(), (
2, (self.name, self.dummy_index)), S.One.sort_key(), S.One
def _hashable_content(self):
return Symbol._hashable_content(self) + (self.dummy_index,)
class Wild(Symbol):
"""
A Wild symbol matches anything, or anything
without whatever is explicitly excluded.
Parameters
==========
name : str
Name of the Wild instance.
exclude : iterable, optional
Instances in ``exclude`` will not be matched.
properties : iterable of functions, optional
Functions, each taking an expressions as input
and returns a ``bool``. All functions in ``properties``
need to return ``True`` in order for the Wild instance
to match the expression.
Examples
========
>>> from sympy import Wild, WildFunction, cos, pi
>>> from sympy.abc import x, y, z
>>> a = Wild('a')
>>> x.match(a)
{a_: x}
>>> pi.match(a)
{a_: pi}
>>> (3*x**2).match(a*x)
{a_: 3*x}
>>> cos(x).match(a)
{a_: cos(x)}
>>> b = Wild('b', exclude=[x])
>>> (3*x**2).match(b*x)
>>> b.match(a)
{a_: b_}
>>> A = WildFunction('A')
>>> A.match(a)
{a_: A_}
Tips
====
When using Wild, be sure to use the exclude
keyword to make the pattern more precise.
Without the exclude pattern, you may get matches
that are technically correct, but not what you
wanted. For example, using the above without
exclude:
>>> from sympy import symbols
>>> a, b = symbols('a b', cls=Wild)
>>> (2 + 3*y).match(a*x + b*y)
{a_: 2/x, b_: 3}
This is technically correct, because
(2/x)*x + 3*y == 2 + 3*y, but you probably
wanted it to not match at all. The issue is that
you really didn't want a and b to include x and y,
and the exclude parameter lets you specify exactly
this. With the exclude parameter, the pattern will
not match.
>>> a = Wild('a', exclude=[x, y])
>>> b = Wild('b', exclude=[x, y])
>>> (2 + 3*y).match(a*x + b*y)
Exclude also helps remove ambiguity from matches.
>>> E = 2*x**3*y*z
>>> a, b = symbols('a b', cls=Wild)
>>> E.match(a*b)
{a_: 2*y*z, b_: x**3}
>>> a = Wild('a', exclude=[x, y])
>>> E.match(a*b)
{a_: z, b_: 2*x**3*y}
>>> a = Wild('a', exclude=[x, y, z])
>>> E.match(a*b)
{a_: 2, b_: x**3*y*z}
Wild also accepts a ``properties`` parameter:
>>> a = Wild('a', properties=[lambda k: k.is_Integer])
>>> E.match(a*b)
{a_: 2, b_: x**3*y*z}
"""
is_Wild = True
__slots__ = ('exclude', 'properties')
def __new__(cls, name, exclude=(), properties=(), **assumptions):
exclude = tuple([sympify(x) for x in exclude])
properties = tuple(properties)
cls._sanitize(assumptions, cls)
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
def __getnewargs__(self):
return (self.name, self.exclude, self.properties)
@staticmethod
@cacheit
def __xnew__(cls, name, exclude, properties, **assumptions):
obj = Symbol.__xnew__(cls, name, **assumptions)
obj.exclude = exclude
obj.properties = properties
return obj
def _hashable_content(self):
return super()._hashable_content() + (self.exclude, self.properties)
# TODO add check against another Wild
def matches(self, expr, repl_dict={}, old=False):
if any(expr.has(x) for x in self.exclude):
return None
if any(not f(expr) for f in self.properties):
return None
repl_dict = repl_dict.copy()
repl_dict[self] = expr
return repl_dict
_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')
def symbols(names, *, cls=Symbol, **args):
r"""
Transform strings into instances of :class:`Symbol` class.
:func:`symbols` function returns a sequence of symbols with names taken
from ``names`` argument, which can be a comma or whitespace delimited
string, or a sequence of strings::
>>> from sympy import symbols, Function
>>> x, y, z = symbols('x,y,z')
>>> a, b, c = symbols('a b c')
The type of output is dependent on the properties of input arguments::
>>> symbols('x')
x
>>> symbols('x,')
(x,)
>>> symbols('x,y')
(x, y)
>>> symbols(('a', 'b', 'c'))
(a, b, c)
>>> symbols(['a', 'b', 'c'])
[a, b, c]
>>> symbols({'a', 'b', 'c'})
{a, b, c}
If an iterable container is needed for a single symbol, set the ``seq``
argument to ``True`` or terminate the symbol name with a comma::
>>> symbols('x', seq=True)
(x,)
To reduce typing, range syntax is supported to create indexed symbols.
Ranges are indicated by a colon and the type of range is determined by
the character to the right of the colon. If the character is a digit
then all contiguous digits to the left are taken as the nonnegative
starting value (or 0 if there is no digit left of the colon) and all
contiguous digits to the right are taken as 1 greater than the ending
value::
>>> symbols('x:10')
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
>>> symbols('x5:10')
(x5, x6, x7, x8, x9)
>>> symbols('x5(:2)')
(x50, x51)
>>> symbols('x5:10,y:5')
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
>>> symbols(('x5:10', 'y:5'))
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
If the character to the right of the colon is a letter, then the single
letter to the left (or 'a' if there is none) is taken as the start
and all characters in the lexicographic range *through* the letter to
the right are used as the range::
>>> symbols('x:z')
(x, y, z)
>>> symbols('x:c') # null range
()
>>> symbols('x(:c)')
(xa, xb, xc)
>>> symbols(':c')
(a, b, c)
>>> symbols('a:d, x:z')
(a, b, c, d, x, y, z)
>>> symbols(('a:d', 'x:z'))
((a, b, c, d), (x, y, z))
Multiple ranges are supported; contiguous numerical ranges should be
separated by parentheses to disambiguate the ending number of one
range from the starting number of the next::
>>> symbols('x:2(1:3)')
(x01, x02, x11, x12)
>>> symbols(':3:2') # parsing is from left to right
(00, 01, 10, 11, 20, 21)
Only one pair of parentheses surrounding ranges are removed, so to
include parentheses around ranges, double them. And to include spaces,
commas, or colons, escape them with a backslash::
>>> symbols('x((a:b))')
(x(a), x(b))
>>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))'
(x(0,0), x(0,1))
All newly created symbols have assumptions set according to ``args``::
>>> a = symbols('a', integer=True)
>>> a.is_integer
True
>>> x, y, z = symbols('x,y,z', real=True)
>>> x.is_real and y.is_real and z.is_real
True
Despite its name, :func:`symbols` can create symbol-like objects like
instances of Function or Wild classes. To achieve this, set ``cls``
keyword argument to the desired type::
>>> symbols('f,g,h', cls=Function)
(f, g, h)
>>> type(_[0])
<class 'sympy.core.function.UndefinedFunction'>
"""
result = []
if isinstance(names, str):
marker = 0
literals = [r'\,', r'\:', r'\ ']
for i in range(len(literals)):
lit = literals.pop(0)
if lit in names:
while chr(marker) in names:
marker += 1
lit_char = chr(marker)
marker += 1
names = names.replace(lit, lit_char)
literals.append((lit_char, lit[1:]))
def literal(s):
if literals:
for c, l in literals:
s = s.replace(c, l)
return s
names = names.strip()
as_seq = names.endswith(',')
if as_seq:
names = names[:-1].rstrip()
if not names:
raise ValueError('no symbols given')
# split on commas
names = [n.strip() for n in names.split(',')]
if not all(n for n in names):
raise ValueError('missing symbol between commas')
# split on spaces
for i in range(len(names) - 1, -1, -1):
names[i: i + 1] = names[i].split()
seq = args.pop('seq', as_seq)
for name in names:
if not name:
raise ValueError('missing symbol')
if ':' not in name:
symbol = cls(literal(name), **args)
result.append(symbol)
continue
split = _range.split(name)
# remove 1 layer of bounding parentheses around ranges
for i in range(len(split) - 1):
if i and ':' in split[i] and split[i] != ':' and \
split[i - 1].endswith('(') and \
split[i + 1].startswith(')'):
split[i - 1] = split[i - 1][:-1]
split[i + 1] = split[i + 1][1:]
for i, s in enumerate(split):
if ':' in s:
if s[-1].endswith(':'):
raise ValueError('missing end range')
a, b = s.split(':')
if b[-1] in string.digits:
a = 0 if not a else int(a)
b = int(b)
split[i] = [str(c) for c in range(a, b)]
else:
a = a or 'a'
split[i] = [string.ascii_letters[c] for c in range(
string.ascii_letters.index(a),
string.ascii_letters.index(b) + 1)] # inclusive
if not split[i]:
break
else:
split[i] = [s]
else:
seq = True
if len(split) == 1:
names = split[0]
else:
names = [''.join(s) for s in cartes(*split)]
if literals:
result.extend([cls(literal(s), **args) for s in names])
else:
result.extend([cls(s, **args) for s in names])
if not seq and len(result) <= 1:
if not result:
return ()
return result[0]
return tuple(result)
else:
for name in names:
result.append(symbols(name, **args))
return type(names)(result)
def var(names, **args):
"""
Create symbols and inject them into the global namespace.
Explanation
===========
This calls :func:`symbols` with the same arguments and puts the results
into the *global* namespace. It's recommended not to use :func:`var` in
library code, where :func:`symbols` has to be used::
Examples
========
>>> from sympy import var
>>> var('x')
x
>>> x # noqa: F821
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc # noqa: F821
abc
>>> var('x,y', real=True)
(x, y)
>>> x.is_real and y.is_real # noqa: F821
True
See :func:`symbols` documentation for more details on what kinds of
arguments can be passed to :func:`var`.
"""
def traverse(symbols, frame):
"""Recursively inject symbols to the global namespace. """
for symbol in symbols:
if isinstance(symbol, Basic):
frame.f_globals[symbol.name] = symbol
elif isinstance(symbol, FunctionClass):
frame.f_globals[symbol.__name__] = symbol
else:
traverse(symbol, frame)
from inspect import currentframe
frame = currentframe().f_back
try:
syms = symbols(names, **args)
if syms is not None:
if isinstance(syms, Basic):
frame.f_globals[syms.name] = syms
elif isinstance(syms, FunctionClass):
frame.f_globals[syms.__name__] = syms
else:
traverse(syms, frame)
finally:
del frame # break cyclic dependencies as stated in inspect docs
return syms
def disambiguate(*iter):
"""
Return a Tuple containing the passed expressions with symbols
that appear the same when printed replaced with numerically
subscripted symbols, and all Dummy symbols replaced with Symbols.
Parameters
==========
iter: list of symbols or expressions.
Examples
========
>>> from sympy.core.symbol import disambiguate
>>> from sympy import Dummy, Symbol, Tuple
>>> from sympy.abc import y
>>> tup = Symbol('_x'), Dummy('x'), Dummy('x')
>>> disambiguate(*tup)
(x_2, x, x_1)
>>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y)
>>> disambiguate(*eqs)
(x_1/y, x/y)
>>> ix = Symbol('x', integer=True)
>>> vx = Symbol('x')
>>> disambiguate(vx + ix)
(x + x_1,)
To make your own mapping of symbols to use, pass only the free symbols
of the expressions and create a dictionary:
>>> free = eqs.free_symbols
>>> mapping = dict(zip(free, disambiguate(*free)))
>>> eqs.xreplace(mapping)
(x_1/y, x/y)
"""
new_iter = Tuple(*iter)
key = lambda x:tuple(sorted(x.assumptions0.items()))
syms = ordered(new_iter.free_symbols, keys=key)
mapping = {}
for s in syms:
mapping.setdefault(str(s).lstrip('_'), []).append(s)
reps = {}
for k in mapping:
# the first or only symbol doesn't get subscripted but make
# sure that it's a Symbol, not a Dummy
mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0)
if mapping[k][0] != mapk0:
reps[mapping[k][0]] = mapk0
# the others get subscripts (and are made into Symbols)
skip = 0
for i in range(1, len(mapping[k])):
while True:
name = "%s_%i" % (k, i + skip)
if name not in mapping:
break
skip += 1
ki = mapping[k][i]
reps[ki] = Symbol(name, **ki.assumptions0)
return new_iter.xreplace(reps)
|
9032a1538c4b94b0e0371a168f21fff68b07cc868be1825fe9d232fb11f49a08 | """
Adaptive numerical evaluation of SymPy expressions, using mpmath
for mathematical functions.
"""
from typing import Tuple
import math
import mpmath.libmp as libmp
from mpmath import (
make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
from mpmath import inf as mpmath_inf
from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
fnan, fnone, fone, fzero, mpf_abs, mpf_add,
mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
mpf_sqrt, normalize, round_nearest, to_int, to_str)
from mpmath.libmp import bitcount as mpmath_bitcount
from mpmath.libmp.backend import MPZ
from mpmath.libmp.libmpc import _infs_nan
from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
from mpmath.libmp.gammazeta import mpf_bernoulli
from .compatibility import SYMPY_INTS
from .sympify import sympify
from .singleton import S
from sympy.utilities.iterables import is_sequence
LG10 = math.log(10, 2)
rnd = round_nearest
def bitcount(n):
"""Return smallest integer, b, such that |n|/2**b < 1.
"""
return mpmath_bitcount(abs(int(n)))
# Used in a few places as placeholder values to denote exponents and
# precision levels, e.g. of exact numbers. Must be careful to avoid
# passing these to mpmath functions or returning them in final results.
INF = float(mpmath_inf)
MINUS_INF = float(-mpmath_inf)
# ~= 100 digits. Real men set this to INF.
DEFAULT_MAXPREC = 333
class PrecisionExhausted(ArithmeticError):
pass
#----------------------------------------------------------------------------#
# #
# Helper functions for arithmetic and complex parts #
# #
#----------------------------------------------------------------------------#
"""
An mpf value tuple is a tuple of integers (sign, man, exp, bc)
representing a floating-point number: [1, -1][sign]*man*2**exp where
sign is 0 or 1 and bc should correspond to the number of bits used to
represent the mantissa (man) in binary notation, e.g.
Explanation
===========
>>> from sympy.core.evalf import bitcount
>>> sign, man, exp, bc = 0, 5, 1, 3
>>> n = [1, -1][sign]*man*2**exp
>>> n, bitcount(man)
(10, 3)
A temporary result is a tuple (re, im, re_acc, im_acc) where
re and im are nonzero mpf value tuples representing approximate
numbers, or None to denote exact zeros.
re_acc, im_acc are integers denoting log2(e) where e is the estimated
relative accuracy of the respective complex part, but may be anything
if the corresponding complex part is None.
"""
def fastlog(x):
"""Fast approximation of log2(x) for an mpf value tuple x.
Explanation
===========
Calculated as exponent + width of mantissa. This is an
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
value and 2) it is too high by 1 in the case that x is an exact
power of 2. Although this is easy to remedy by testing to see if
the odd mpf mantissa is 1 (indicating that one was dealing with
an exact power of 2) that would decrease the speed and is not
necessary as this is only being used as an approximation for the
number of bits in x. The correct return value could be written as
"x[2] + (x[3] if x[1] != 1 else 0)".
Since mpf tuples always have an odd mantissa, no check is done
to see if the mantissa is a multiple of 2 (in which case the
result would be too large by 1).
Examples
========
>>> from sympy import log
>>> from sympy.core.evalf import fastlog, bitcount
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
"""
if not x or x == fzero:
return MINUS_INF
return x[2] + x[3]
def pure_complex(v, or_real=False):
"""Return a and b if v matches a + I*b where b is not zero and
a and b are Numbers, else None. If `or_real` is True then 0 will
be returned for `b` if `v` is a real number.
Examples
========
>>> from sympy.core.evalf import pure_complex
>>> from sympy import sqrt, I, S
>>> a, b, surd = S(2), S(3), sqrt(2)
>>> pure_complex(a)
>>> pure_complex(a, or_real=True)
(2, 0)
>>> pure_complex(surd)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
"""
h, t = v.as_coeff_Add()
if not t:
if or_real:
return h, t
return
c, i = t.as_coeff_Mul()
if i is S.ImaginaryUnit:
return h, c
def scaled_zero(mag, sign=1):
"""Return an mpf representing a power of two with magnitude ``mag``
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
remove the sign from within the list that it was initially wrapped
in.
Examples
========
>>> from sympy.core.evalf import scaled_zero
>>> from sympy import Float
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30
"""
if type(mag) is tuple and len(mag) == 4 and iszero(mag, scaled=True):
return (mag[0][0],) + mag[1:]
elif isinstance(mag, SYMPY_INTS):
if sign not in [-1, 1]:
raise ValueError('sign must be +/-1')
rv, p = mpf_shift(fone, mag), -1
s = 0 if sign == 1 else 1
rv = ([s],) + rv[1:]
return rv, p
else:
raise ValueError('scaled zero expects int or scaled_zero tuple.')
def iszero(mpf, scaled=False):
if not scaled:
return not mpf or not mpf[1] and not mpf[-1]
return mpf and type(mpf[0]) is list and mpf[1] == mpf[-1] == 1
def complex_accuracy(result):
"""
Returns relative accuracy of a complex number with given accuracies
for the real and imaginary parts. The relative accuracy is defined
in the complex norm sense as ||z|+|error|| / |z| where error
is equal to (real absolute error) + (imag absolute error)*i.
The full expression for the (logarithmic) error can be approximated
easily by using the max norm to approximate the complex norm.
In the worst case (re and im equal), this is wrong by a factor
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
"""
re, im, re_acc, im_acc = result
if not im:
if not re:
return INF
return re_acc
if not re:
return im_acc
re_size = fastlog(re)
im_size = fastlog(im)
absolute_error = max(re_size - re_acc, im_size - im_acc)
relative_error = absolute_error - max(re_size, im_size)
return -relative_error
def get_abs(expr, prec, options):
re, im, re_acc, im_acc = evalf(expr, prec + 2, options)
if not re:
re, re_acc, im, im_acc = im, im_acc, re, re_acc
if im:
if expr.is_number:
abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
prec + 2, options)
return abs_expr, None, acc, None
else:
if 'subs' in options:
return libmp.mpc_abs((re, im), prec), None, re_acc, None
return abs(expr), None, prec, None
elif re:
return mpf_abs(re), None, re_acc, None
else:
return None, None, None, None
def get_complex_part(expr, no, prec, options):
"""no = 0 for real part, no = 1 for imaginary part"""
workprec = prec
i = 0
while 1:
res = evalf(expr, workprec, options)
value, accuracy = res[no::2]
# XXX is the last one correct? Consider re((1+I)**2).n()
if (not value) or accuracy >= prec or -value[2] > prec:
return value, None, accuracy, None
workprec += max(30, 2**i)
i += 1
def evalf_abs(expr, prec, options):
return get_abs(expr.args[0], prec, options)
def evalf_re(expr, prec, options):
return get_complex_part(expr.args[0], 0, prec, options)
def evalf_im(expr, prec, options):
return get_complex_part(expr.args[0], 1, prec, options)
def finalize_complex(re, im, prec):
if re == fzero and im == fzero:
raise ValueError("got complex zero with unknown accuracy")
elif re == fzero:
return None, im, None, prec
elif im == fzero:
return re, None, prec, None
size_re = fastlog(re)
size_im = fastlog(im)
if size_re > size_im:
re_acc = prec
im_acc = prec + min(-(size_re - size_im), 0)
else:
im_acc = prec
re_acc = prec + min(-(size_im - size_re), 0)
return re, im, re_acc, im_acc
def chop_parts(value, prec):
"""
Chop off tiny real or complex parts.
"""
re, im, re_acc, im_acc = value
# Method 1: chop based on absolute value
if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
re, re_acc = None, None
if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
im, im_acc = None, None
# Method 2: chop if inaccurate and relatively small
if re and im:
delta = fastlog(re) - fastlog(im)
if re_acc < 2 and (delta - re_acc <= -prec + 4):
re, re_acc = None, None
if im_acc < 2 and (delta - im_acc >= prec - 4):
im, im_acc = None, None
return re, im, re_acc, im_acc
def check_target(expr, result, prec):
a = complex_accuracy(result)
if a < prec:
raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
"from zero. Try simplifying the input, using chop=True, or providing "
"a higher maxn for evalf" % (expr))
def get_integer_part(expr, no, options, return_ints=False):
"""
With no = 1, computes ceiling(expr)
With no = -1, computes floor(expr)
Note: this function either gives the exact result or signals failure.
"""
from sympy.functions.elementary.complexes import re, im
# The expression is likely less than 2^30 or so
assumed_size = 30
ire, iim, ire_acc, iim_acc = evalf(expr, assumed_size, options)
# We now know the size, so we can calculate how much extra precision
# (if any) is needed to get within the nearest integer
if ire and iim:
gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
elif ire:
gap = fastlog(ire) - ire_acc
elif iim:
gap = fastlog(iim) - iim_acc
else:
# ... or maybe the expression was exactly zero
if return_ints:
return 0, 0
else:
return None, None, None, None
margin = 10
if gap >= -margin:
prec = margin + assumed_size + gap
ire, iim, ire_acc, iim_acc = evalf(
expr, prec, options)
else:
prec = assumed_size
# We can now easily find the nearest integer, but to find floor/ceil, we
# must also calculate whether the difference to the nearest integer is
# positive or negative (which may fail if very close).
def calc_part(re_im, nexpr):
from sympy.core.add import Add
_, _, exponent, _ = nexpr
is_int = exponent == 0
nint = int(to_int(nexpr, rnd))
if is_int:
# make sure that we had enough precision to distinguish
# between nint and the re or im part (re_im) of expr that
# was passed to calc_part
ire, iim, ire_acc, iim_acc = evalf(
re_im - nint, 10, options) # don't need much precision
assert not iim
size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
if size > prec:
ire, iim, ire_acc, iim_acc = evalf(
re_im, size, options)
assert not iim
nexpr = ire
nint = int(to_int(nexpr, rnd))
_, _, new_exp, _ = ire
is_int = new_exp == 0
if not is_int:
# if there are subs and they all contain integer re/im parts
# then we can (hopefully) safely substitute them into the
# expression
s = options.get('subs', False)
if s:
doit = True
from sympy.core.compatibility import as_int
# use strict=False with as_int because we take
# 2.0 == 2
for v in s.values():
try:
as_int(v, strict=False)
except ValueError:
try:
[as_int(i, strict=False) for i in v.as_real_imag()]
continue
except (ValueError, AttributeError):
doit = False
break
if doit:
re_im = re_im.subs(s)
re_im = Add(re_im, -nint, evaluate=False)
x, _, x_acc, _ = evalf(re_im, 10, options)
try:
check_target(re_im, (x, None, x_acc, None), 3)
except PrecisionExhausted:
if not re_im.equals(0):
raise PrecisionExhausted
x = fzero
nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
nint = from_int(nint)
return nint, INF
re_, im_, re_acc, im_acc = None, None, None, None
if ire:
re_, re_acc = calc_part(re(expr, evaluate=False), ire)
if iim:
im_, im_acc = calc_part(im(expr, evaluate=False), iim)
if return_ints:
return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
return re_, im_, re_acc, im_acc
def evalf_ceiling(expr, prec, options):
return get_integer_part(expr.args[0], 1, options)
def evalf_floor(expr, prec, options):
return get_integer_part(expr.args[0], -1, options)
#----------------------------------------------------------------------------#
# #
# Arithmetic operations #
# #
#----------------------------------------------------------------------------#
def add_terms(terms, prec, target_prec):
"""
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
Returns
=======
- None, None if there are no non-zero terms;
- terms[0] if there is only 1 term;
- scaled_zero if the sum of the terms produces a zero by cancellation
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
special handling since they are not actually zero and they are purposely
malformed to ensure that they can't be used in anything but accuracy
calculations;
- a tuple that is scaled to target_prec that corresponds to the
sum of the terms.
The returned mpf tuple will be normalized to target_prec; the input
prec is used to define the working precision.
XXX explain why this is needed and why one can't just loop using mpf_add
"""
terms = [t for t in terms if not iszero(t[0])]
if not terms:
return None, None
elif len(terms) == 1:
return terms[0]
# see if any argument is NaN or oo and thus warrants a special return
special = []
from sympy.core.numbers import Float
for t in terms:
arg = Float._new(t[0], 1)
if arg is S.NaN or arg.is_infinite:
special.append(arg)
if special:
from sympy.core.add import Add
rv = evalf(Add(*special), prec + 4, {})
return rv[0], rv[2]
working_prec = 2*prec
sum_man, sum_exp, absolute_error = 0, 0, MINUS_INF
for x, accuracy in terms:
sign, man, exp, bc = x
if sign:
man = -man
absolute_error = max(absolute_error, bc + exp - accuracy)
delta = exp - sum_exp
if exp >= sum_exp:
# x much larger than existing sum?
# first: quick test
if ((delta > working_prec) and
((not sum_man) or
delta - bitcount(abs(sum_man)) > working_prec)):
sum_man = man
sum_exp = exp
else:
sum_man += (man << delta)
else:
delta = -delta
# x much smaller than existing sum?
if delta - bc > working_prec:
if not sum_man:
sum_man, sum_exp = man, exp
else:
sum_man = (sum_man << delta) + man
sum_exp = exp
if not sum_man:
return scaled_zero(absolute_error)
if sum_man < 0:
sum_sign = 1
sum_man = -sum_man
else:
sum_sign = 0
sum_bc = bitcount(sum_man)
sum_accuracy = sum_exp + sum_bc - absolute_error
r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
rnd), sum_accuracy
return r
def evalf_add(v, prec, options):
res = pure_complex(v)
if res:
h, c = res
re, _, re_acc, _ = evalf(h, prec, options)
im, _, im_acc, _ = evalf(c, prec, options)
return re, im, re_acc, im_acc
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
i = 0
target_prec = prec
while 1:
options['maxprec'] = min(oldmaxprec, 2*prec)
terms = [evalf(arg, prec + 10, options) for arg in v.args]
re, re_acc = add_terms(
[a[0::2] for a in terms if a[0]], prec, target_prec)
im, im_acc = add_terms(
[a[1::2] for a in terms if a[1]], prec, target_prec)
acc = complex_accuracy((re, im, re_acc, im_acc))
if acc >= target_prec:
if options.get('verbose'):
print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
break
else:
if (prec - target_prec) > options['maxprec']:
break
prec = prec + max(10 + 2**i, target_prec - acc)
i += 1
if options.get('verbose'):
print("ADD: restarting with prec", prec)
options['maxprec'] = oldmaxprec
if iszero(re, scaled=True):
re = scaled_zero(re)
if iszero(im, scaled=True):
im = scaled_zero(im)
return re, im, re_acc, im_acc
def evalf_mul(v, prec, options):
res = pure_complex(v)
if res:
# the only pure complex that is a mul is h*I
_, h = res
im, _, im_acc, _ = evalf(h, prec, options)
return None, im, None, im_acc
args = list(v.args)
# see if any argument is NaN or oo and thus warrants a special return
special = []
from sympy.core.numbers import Float
for arg in args:
arg = evalf(arg, prec, options)
if arg[0] is None:
continue
arg = Float._new(arg[0], 1)
if arg is S.NaN or arg.is_infinite:
special.append(arg)
if special:
from sympy.core.mul import Mul
special = Mul(*special)
return evalf(special, prec + 4, {})
# With guard digits, multiplication in the real case does not destroy
# accuracy. This is also true in the complex case when considering the
# total accuracy; however accuracy for the real or imaginary parts
# separately may be lower.
acc = prec
# XXX: big overestimate
working_prec = prec + len(args) + 5
# Empty product is 1
start = man, exp, bc = MPZ(1), 0, 1
# First, we multiply all pure real or pure imaginary numbers.
# direction tells us that the result should be multiplied by
# I**direction; all other numbers get put into complex_factors
# to be multiplied out after the first phase.
last = len(args)
direction = 0
args.append(S.One)
complex_factors = []
for i, arg in enumerate(args):
if i != last and pure_complex(arg):
args[-1] = (args[-1]*arg).expand()
continue
elif i == last and arg is S.One:
continue
re, im, re_acc, im_acc = evalf(arg, working_prec, options)
if re and im:
complex_factors.append((re, im, re_acc, im_acc))
continue
elif re:
(s, m, e, b), w_acc = re, re_acc
elif im:
(s, m, e, b), w_acc = im, im_acc
direction += 1
else:
return None, None, None, None
direction += 2*s
man *= m
exp += e
bc += b
if bc > 3*working_prec:
man >>= working_prec
exp += working_prec
acc = min(acc, w_acc)
sign = (direction & 2) >> 1
if not complex_factors:
v = normalize(sign, man, exp, bitcount(man), prec, rnd)
# multiply by i
if direction & 1:
return None, v, None, acc
else:
return v, None, acc, None
else:
# initialize with the first term
if (man, exp, bc) != start:
# there was a real part; give it an imaginary part
re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
i0 = 0
else:
# there is no real part to start (other than the starting 1)
wre, wim, wre_acc, wim_acc = complex_factors[0]
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
re = wre
im = wim
i0 = 1
for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
# acc is the overall accuracy of the product; we aren't
# computing exact accuracies of the product.
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
use_prec = working_prec
A = mpf_mul(re, wre, use_prec)
B = mpf_mul(mpf_neg(im), wim, use_prec)
C = mpf_mul(re, wim, use_prec)
D = mpf_mul(im, wre, use_prec)
re = mpf_add(A, B, use_prec)
im = mpf_add(C, D, use_prec)
if options.get('verbose'):
print("MUL: wanted", prec, "accurate bits, got", acc)
# multiply by I
if direction & 1:
re, im = mpf_neg(im), re
return re, im, acc, acc
def evalf_pow(v, prec, options):
target_prec = prec
base, exp = v.args
# We handle x**n separately. This has two purposes: 1) it is much
# faster, because we avoid calling evalf on the exponent, and 2) it
# allows better handling of real/imaginary parts that are exactly zero
if exp.is_Integer:
p = exp.p
# Exact
if not p:
return fone, None, prec, None
# Exponentiation by p magnifies relative error by |p|, so the
# base must be evaluated with increased precision if p is large
prec += int(math.log(abs(p), 2))
re, im, re_acc, im_acc = evalf(base, prec + 5, options)
# Real to integer power
if re and not im:
return mpf_pow_int(re, p, target_prec), None, target_prec, None
# (x*I)**n = I**n * x**n
if im and not re:
z = mpf_pow_int(im, p, target_prec)
case = p % 4
if case == 0:
return z, None, target_prec, None
if case == 1:
return None, z, None, target_prec
if case == 2:
return mpf_neg(z), None, target_prec, None
if case == 3:
return None, mpf_neg(z), None, target_prec
# Zero raised to an integer power
if not re:
return None, None, None, None
# General complex number to arbitrary integer power
re, im = libmp.mpc_pow_int((re, im), p, prec)
# Assumes full accuracy in input
return finalize_complex(re, im, target_prec)
# Pure square root
if exp is S.Half:
xre, xim, _, _ = evalf(base, prec + 5, options)
# General complex square root
if xim:
re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
return finalize_complex(re, im, prec)
if not xre:
return None, None, None, None
# Square root of a negative real number
if mpf_lt(xre, fzero):
return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
# Positive square root
return mpf_sqrt(xre, prec), None, prec, None
# We first evaluate the exponent to find its magnitude
# This determines the working precision that must be used
prec += 10
yre, yim, _, _ = evalf(exp, prec, options)
# Special cases: x**0
if not (yre or yim):
return fone, None, prec, None
ysize = fastlog(yre)
# Restart if too big
# XXX: prec + ysize might exceed maxprec
if ysize > 5:
prec += ysize
yre, yim, _, _ = evalf(exp, prec, options)
# Pure exponential function; no need to evalf the base
if base is S.Exp1:
if yim:
re, im = libmp.mpc_exp((yre or fzero, yim), prec)
return finalize_complex(re, im, target_prec)
return mpf_exp(yre, target_prec), None, target_prec, None
xre, xim, _, _ = evalf(base, prec + 5, options)
# 0**y
if not (xre or xim):
return None, None, None, None
# (real ** complex) or (complex ** complex)
if yim:
re, im = libmp.mpc_pow(
(xre or fzero, xim or fzero), (yre or fzero, yim),
target_prec)
return finalize_complex(re, im, target_prec)
# complex ** real
if xim:
re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
return finalize_complex(re, im, target_prec)
# negative ** real
elif mpf_lt(xre, fzero):
re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
return finalize_complex(re, im, target_prec)
# positive ** real
else:
return mpf_pow(xre, yre, target_prec), None, target_prec, None
#----------------------------------------------------------------------------#
# #
# Special functions #
# #
#----------------------------------------------------------------------------#
def evalf_trig(v, prec, options):
"""
This function handles sin and cos of complex arguments.
TODO: should also handle tan of complex arguments.
"""
from sympy import cos, sin
if isinstance(v, cos):
func = mpf_cos
elif isinstance(v, sin):
func = mpf_sin
else:
raise NotImplementedError
arg = v.args[0]
# 20 extra bits is possibly overkill. It does make the need
# to restart very unlikely
xprec = prec + 20
re, im, re_acc, im_acc = evalf(arg, xprec, options)
if im:
if 'subs' in options:
v = v.subs(options['subs'])
return evalf(v._eval_evalf(prec), prec, options)
if not re:
if isinstance(v, cos):
return fone, None, prec, None
elif isinstance(v, sin):
return None, None, None, None
else:
raise NotImplementedError
# For trigonometric functions, we are interested in the
# fixed-point (absolute) accuracy of the argument.
xsize = fastlog(re)
# Magnitude <= 1.0. OK to compute directly, because there is no
# danger of hitting the first root of cos (with sin, magnitude
# <= 2.0 would actually be ok)
if xsize < 1:
return func(re, prec, rnd), None, prec, None
# Very large
if xsize >= 10:
xprec = prec + xsize
re, im, re_acc, im_acc = evalf(arg, xprec, options)
# Need to repeat in case the argument is very close to a
# multiple of pi (or pi/2), hitting close to a root
while 1:
y = func(re, prec, rnd)
ysize = fastlog(y)
gap = -ysize
accuracy = (xprec - xsize) - gap
if accuracy < prec:
if options.get('verbose'):
print("SIN/COS", accuracy, "wanted", prec, "gap", gap)
print(to_str(y, 10))
if xprec > options.get('maxprec', DEFAULT_MAXPREC):
return y, None, accuracy, None
xprec += gap
re, im, re_acc, im_acc = evalf(arg, xprec, options)
continue
else:
return y, None, prec, None
def evalf_log(expr, prec, options):
from sympy import Abs, Add, log
if len(expr.args)>1:
expr = expr.doit()
return evalf(expr, prec, options)
arg = expr.args[0]
workprec = prec + 10
xre, xim, xacc, _ = evalf(arg, workprec, options)
if xim:
# XXX: use get_abs etc instead
re = evalf_log(
log(Abs(arg, evaluate=False), evaluate=False), prec, options)
im = mpf_atan2(xim, xre or fzero, prec)
return re[0], im, re[2], prec
imaginary_term = (mpf_cmp(xre, fzero) < 0)
re = mpf_log(mpf_abs(xre), prec, rnd)
size = fastlog(re)
if prec - size > workprec and re != fzero:
# We actually need to compute 1+x accurately, not x
arg = Add(S.NegativeOne, arg, evaluate=False)
xre, xim, _, _ = evalf_add(arg, prec, options)
prec2 = workprec - fastlog(xre)
# xre is now x - 1 so we add 1 back here to calculate x
re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
re_acc = prec
if imaginary_term:
return re, mpf_pi(prec), re_acc, prec
else:
return re, None, re_acc, None
def evalf_atan(v, prec, options):
arg = v.args[0]
xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
if xre is xim is None:
return (None,)*4
if xim:
raise NotImplementedError
return mpf_atan(xre, prec, rnd), None, prec, None
def evalf_subs(prec, subs):
""" Change all Float entries in `subs` to have precision prec. """
newsubs = {}
for a, b in subs.items():
b = S(b)
if b.is_Float:
b = b._eval_evalf(prec)
newsubs[a] = b
return newsubs
def evalf_piecewise(expr, prec, options):
from sympy import Float, Integer
if 'subs' in options:
expr = expr.subs(evalf_subs(prec, options['subs']))
newopts = options.copy()
del newopts['subs']
if hasattr(expr, 'func'):
return evalf(expr, prec, newopts)
if type(expr) == float:
return evalf(Float(expr), prec, newopts)
if type(expr) == int:
return evalf(Integer(expr), prec, newopts)
# We still have undefined symbols
raise NotImplementedError
def evalf_bernoulli(expr, prec, options):
arg = expr.args[0]
if not arg.is_Integer:
raise ValueError("Bernoulli number index must be an integer")
n = int(arg)
b = mpf_bernoulli(n, prec, rnd)
if b == fzero:
return None, None, None, None
return b, None, prec, None
#----------------------------------------------------------------------------#
# #
# High-level operations #
# #
#----------------------------------------------------------------------------#
def as_mpmath(x, prec, options):
from sympy.core.numbers import Infinity, NegativeInfinity, Zero
x = sympify(x)
if isinstance(x, Zero) or x == 0:
return mpf(0)
if isinstance(x, Infinity):
return mpf('inf')
if isinstance(x, NegativeInfinity):
return mpf('-inf')
# XXX
re, im, _, _ = evalf(x, prec, options)
if im:
return mpc(re or fzero, im)
return mpf(re)
def do_integral(expr, prec, options):
func = expr.args[0]
x, xlow, xhigh = expr.args[1]
if xlow == xhigh:
xlow = xhigh = 0
elif x not in func.free_symbols:
# only the difference in limits matters in this case
# so if there is a symbol in common that will cancel
# out when taking the difference, then use that
# difference
if xhigh.free_symbols & xlow.free_symbols:
diff = xhigh - xlow
if diff.is_number:
xlow, xhigh = 0, diff
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
options['maxprec'] = min(oldmaxprec, 2*prec)
with workprec(prec + 5):
xlow = as_mpmath(xlow, prec + 15, options)
xhigh = as_mpmath(xhigh, prec + 15, options)
# Integration is like summation, and we can phone home from
# the integrand function to update accuracy summation style
# Note that this accuracy is inaccurate, since it fails
# to account for the variable quadrature weights,
# but it is better than nothing
from sympy import cos, sin, Wild
have_part = [False, False]
max_real_term = [MINUS_INF]
max_imag_term = [MINUS_INF]
def f(t):
re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
have_part[0] = re or have_part[0]
have_part[1] = im or have_part[1]
max_real_term[0] = max(max_real_term[0], fastlog(re))
max_imag_term[0] = max(max_imag_term[0], fastlog(im))
if im:
return mpc(re or fzero, im)
return mpf(re or fzero)
if options.get('quad') == 'osc':
A = Wild('A', exclude=[x])
B = Wild('B', exclude=[x])
D = Wild('D')
m = func.match(cos(A*x + B)*D)
if not m:
m = func.match(sin(A*x + B)*D)
if not m:
raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
"or cos(A*x+B)*f(x) is required for oscillatory quadrature")
period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
result = quadosc(f, [xlow, xhigh], period=period)
# XXX: quadosc does not do error detection yet
quadrature_error = MINUS_INF
else:
result, quadrature_error = quadts(f, [xlow, xhigh], error=1)
quadrature_error = fastlog(quadrature_error._mpf_)
options['maxprec'] = oldmaxprec
if have_part[0]:
re = result.real._mpf_
if re == fzero:
re, re_acc = scaled_zero(
min(-prec, -max_real_term[0], -quadrature_error))
re = scaled_zero(re) # handled ok in evalf_integral
else:
re_acc = -max(max_real_term[0] - fastlog(re) -
prec, quadrature_error)
else:
re, re_acc = None, None
if have_part[1]:
im = result.imag._mpf_
if im == fzero:
im, im_acc = scaled_zero(
min(-prec, -max_imag_term[0], -quadrature_error))
im = scaled_zero(im) # handled ok in evalf_integral
else:
im_acc = -max(max_imag_term[0] - fastlog(im) -
prec, quadrature_error)
else:
im, im_acc = None, None
result = re, im, re_acc, im_acc
return result
def evalf_integral(expr, prec, options):
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
workprec = prec
i = 0
maxprec = options.get('maxprec', INF)
while 1:
result = do_integral(expr, workprec, options)
accuracy = complex_accuracy(result)
if accuracy >= prec: # achieved desired precision
break
if workprec >= maxprec: # can't increase accuracy any more
break
if accuracy == -1:
# maybe the answer really is zero and maybe we just haven't increased
# the precision enough. So increase by doubling to not take too long
# to get to maxprec.
workprec *= 2
else:
workprec += max(prec, 2**i)
workprec = min(workprec, maxprec)
i += 1
return result
def check_convergence(numer, denom, n):
"""
Returns
=======
(h, g, p) where
-- h is:
> 0 for convergence of rate 1/factorial(n)**h
< 0 for divergence of rate factorial(n)**(-h)
= 0 for geometric or polynomial convergence or divergence
-- abs(g) is:
> 1 for geometric convergence of rate 1/h**n
< 1 for geometric divergence of rate h**n
= 1 for polynomial convergence or divergence
(g < 0 indicates an alternating series)
-- p is:
> 1 for polynomial convergence of rate 1/n**h
<= 1 for polynomial divergence of rate n**(-h)
"""
from sympy import Poly
npol = Poly(numer, n)
dpol = Poly(denom, n)
p = npol.degree()
q = dpol.degree()
rate = q - p
if rate:
return rate, None, None
constant = dpol.LC() / npol.LC()
if abs(constant) != 1:
return rate, constant, None
if npol.degree() == dpol.degree() == 0:
return rate, constant, 0
pc = npol.all_coeffs()[1]
qc = dpol.all_coeffs()[1]
return rate, constant, (qc - pc)/dpol.LC()
def hypsum(expr, n, start, prec):
"""
Sum a rapidly convergent infinite hypergeometric series with
given general term, e.g. e = hypsum(1/factorial(n), n). The
quotient between successive terms must be a quotient of integer
polynomials.
"""
from sympy import Float, hypersimp, lambdify
if prec == float('inf'):
raise NotImplementedError('does not support inf prec')
if start:
expr = expr.subs(n, n + start)
hs = hypersimp(expr, n)
if hs is None:
raise NotImplementedError("a hypergeometric series is required")
num, den = hs.as_numer_denom()
func1 = lambdify(n, num)
func2 = lambdify(n, den)
h, g, p = check_convergence(num, den, n)
if h < 0:
raise ValueError("Sum diverges like (n!)^%i" % (-h))
term = expr.subs(n, 0)
if not term.is_Rational:
raise NotImplementedError("Non rational term functionality is not implemented.")
# Direct summation if geometric or faster
if h > 0 or (h == 0 and abs(g) > 1):
term = (MPZ(term.p) << prec) // term.q
s = term
k = 1
while abs(term) > 5:
term *= MPZ(func1(k - 1))
term //= MPZ(func2(k - 1))
s += term
k += 1
return from_man_exp(s, -prec)
else:
alt = g < 0
if abs(g) < 1:
raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
if p < 1 or (p == 1 and not alt):
raise ValueError("Sum diverges like n^%i" % (-p))
# We have polynomial convergence: use Richardson extrapolation
vold = None
ndig = prec_to_dps(prec)
while True:
# Need to use at least quad precision because a lot of cancellation
# might occur in the extrapolation process; we check the answer to
# make sure that the desired precision has been reached, too.
prec2 = 4*prec
term0 = (MPZ(term.p) << prec2) // term.q
def summand(k, _term=[term0]):
if k:
k = int(k)
_term[0] *= MPZ(func1(k - 1))
_term[0] //= MPZ(func2(k - 1))
return make_mpf(from_man_exp(_term[0], -prec2))
with workprec(prec):
v = nsum(summand, [0, mpmath_inf], method='richardson')
vf = Float(v, ndig)
if vold is not None and vold == vf:
break
prec += prec # double precision each time
vold = vf
return v._mpf_
def evalf_prod(expr, prec, options):
from sympy import Sum
if all((l[1] - l[2]).is_Integer for l in expr.limits):
re, im, re_acc, im_acc = evalf(expr.doit(), prec=prec, options=options)
else:
re, im, re_acc, im_acc = evalf(expr.rewrite(Sum), prec=prec, options=options)
return re, im, re_acc, im_acc
def evalf_sum(expr, prec, options):
from sympy import Float
if 'subs' in options:
expr = expr.subs(options['subs'])
func = expr.function
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
if func.is_zero:
return None, None, prec, None
prec2 = prec + 10
try:
n, a, b = limits[0]
if b != S.Infinity or a != int(a):
raise NotImplementedError
# Use fast hypergeometric summation if possible
v = hypsum(func, n, int(a), prec2)
delta = prec - fastlog(v)
if fastlog(v) < -10:
v = hypsum(func, n, int(a), delta)
return v, None, min(prec, delta), None
except NotImplementedError:
# Euler-Maclaurin summation for general series
eps = Float(2.0)**(-prec)
for i in range(1, 5):
m = n = 2**i * prec
s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
eval_integral=False)
err = err.evalf()
if err <= eps:
break
err = fastlog(evalf(abs(err), 20, options)[0])
re, im, re_acc, im_acc = evalf(s, prec2, options)
if re_acc is None:
re_acc = -err
if im_acc is None:
im_acc = -err
return re, im, re_acc, im_acc
#----------------------------------------------------------------------------#
# #
# Symbolic interface #
# #
#----------------------------------------------------------------------------#
def evalf_symbol(x, prec, options):
val = options['subs'][x]
if isinstance(val, mpf):
if not val:
return None, None, None, None
return val._mpf_, None, prec, None
else:
if not '_cache' in options:
options['_cache'] = {}
cache = options['_cache']
cached, cached_prec = cache.get(x, (None, MINUS_INF))
if cached_prec >= prec:
return cached
v = evalf(sympify(val), prec, options)
cache[x] = (v, prec)
return v
evalf_table = None
def _create_evalf_table():
global evalf_table
from sympy.functions.combinatorial.numbers import bernoulli
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, Zero
from sympy.core.power import Pow
from sympy.core.symbol import Dummy, Symbol
from sympy.functions.elementary.complexes import Abs, im, re
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import atan, cos, sin
from sympy.integrals.integrals import Integral
evalf_table = {
Symbol: evalf_symbol,
Dummy: evalf_symbol,
Float: lambda x, prec, options: (x._mpf_, None, prec, None),
Rational: lambda x, prec, options: (from_rational(x.p, x.q, prec), None, prec, None),
Integer: lambda x, prec, options: (from_int(x.p, prec), None, prec, None),
Zero: lambda x, prec, options: (None, None, prec, None),
One: lambda x, prec, options: (fone, None, prec, None),
Half: lambda x, prec, options: (fhalf, None, prec, None),
Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
NaN: lambda x, prec, options: (fnan, None, prec, None),
exp: lambda x, prec, options: evalf_pow(
Pow(S.Exp1, x.args[0], evaluate=False), prec, options),
cos: evalf_trig,
sin: evalf_trig,
Add: evalf_add,
Mul: evalf_mul,
Pow: evalf_pow,
log: evalf_log,
atan: evalf_atan,
Abs: evalf_abs,
re: evalf_re,
im: evalf_im,
floor: evalf_floor,
ceiling: evalf_ceiling,
Integral: evalf_integral,
Sum: evalf_sum,
Product: evalf_prod,
Piecewise: evalf_piecewise,
bernoulli: evalf_bernoulli,
}
def evalf(x, prec, options):
from sympy import re as re_, im as im_
try:
rf = evalf_table[x.func]
r = rf(x, prec, options)
except KeyError:
# Fall back to ordinary evalf if possible
if 'subs' in options:
x = x.subs(evalf_subs(prec, options['subs']))
xe = x._eval_evalf(prec)
if xe is None:
raise NotImplementedError
as_real_imag = getattr(xe, "as_real_imag", None)
if as_real_imag is None:
raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
re, im = as_real_imag()
if re.has(re_) or im.has(im_):
raise NotImplementedError
if re == 0:
re = None
reprec = None
elif re.is_number:
re = re._to_mpmath(prec, allow_ints=False)._mpf_
reprec = prec
else:
raise NotImplementedError
if im == 0:
im = None
imprec = None
elif im.is_number:
im = im._to_mpmath(prec, allow_ints=False)._mpf_
imprec = prec
else:
raise NotImplementedError
r = re, im, reprec, imprec
if options.get("verbose"):
print("### input", x)
print("### output", to_str(r[0] or fzero, 50))
print("### raw", r) # r[0], r[2]
print()
chop = options.get('chop', False)
if chop:
if chop is True:
chop_prec = prec
else:
# convert (approximately) from given tolerance;
# the formula here will will make 1e-i rounds to 0 for
# i in the range +/-27 while 2e-i will not be chopped
chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
if chop_prec == 3:
chop_prec -= 1
r = chop_parts(r, chop_prec)
if options.get("strict"):
check_target(x, r, prec)
return r
class EvalfMixin:
"""Mixin class adding evalf capabililty."""
__slots__ = () # type: Tuple[str, ...]
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
"""
Evaluate the given formula to an accuracy of *n* digits.
Parameters
==========
subs : dict, optional
Substitute numerical values for symbols, e.g.
``subs={x:3, y:1+pi}``. The substitutions must be given as a
dictionary.
maxn : int, optional
Allow a maximum temporary working precision of maxn digits.
chop : bool or number, optional
Specifies how to replace tiny real or imaginary parts in
subresults by exact zeros.
When ``True`` the chop value defaults to standard precision.
Otherwise the chop value is used to determine the
magnitude of "small" for purposes of chopping.
>>> from sympy import N
>>> x = 1e-4
>>> N(x, chop=True)
0.000100000000000000
>>> N(x, chop=1e-5)
0.000100000000000000
>>> N(x, chop=1e-4)
0
strict : bool, optional
Raise ``PrecisionExhausted`` if any subresult fails to
evaluate to full accuracy, given the available maxprec.
quad : str, optional
Choose algorithm for numerical quadrature. By default,
tanh-sinh quadrature is used. For oscillatory
integrals on an infinite interval, try ``quad='osc'``.
verbose : bool, optional
Print debug information.
Notes
=====
When Floats are naively substituted into an expression,
precision errors may adversely affect the result. For example,
adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
then subtracted, the result will be 0.
That is exactly what happens in the following:
>>> from sympy.abc import x, y, z
>>> values = {x: 1e16, y: 1, z: 1e16}
>>> (x + y - z).subs(values)
0
Using the subs argument for evalf is the accurate way to
evaluate such an expression:
>>> (x + y - z).evalf(subs=values)
1.00000000000000
"""
from sympy import Float, Number
n = n if n is not None else 15
if subs and is_sequence(subs):
raise TypeError('subs must be given as a dictionary')
# for sake of sage that doesn't like evalf(1)
if n == 1 and isinstance(self, Number):
from sympy.core.expr import _mag
rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
m = _mag(rv)
rv = rv.round(1 - m)
return rv
if not evalf_table:
_create_evalf_table()
prec = dps_to_prec(n)
options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
'strict': strict, 'verbose': verbose}
if subs is not None:
options['subs'] = subs
if quad is not None:
options['quad'] = quad
try:
result = evalf(self, prec + 4, options)
except NotImplementedError:
# Fall back to the ordinary evalf
if hasattr(self, 'subs') and subs is not None: # issue 20291
v = self.subs(subs)._eval_evalf(prec)
else:
v = self._eval_evalf(prec)
if v is None:
return self
elif not v.is_number:
return v
try:
# If the result is numerical, normalize it
result = evalf(v, prec, options)
except NotImplementedError:
# Probably contains symbols or unknown functions
return v
re, im, re_acc, im_acc = result
if re:
p = max(min(prec, re_acc), 1)
re = Float._new(re, p)
else:
re = S.Zero
if im:
p = max(min(prec, im_acc), 1)
im = Float._new(im, p)
return re + im*S.ImaginaryUnit
else:
return re
n = evalf
def _evalf(self, prec):
"""Helper for evalf. Does the same thing but takes binary precision"""
r = self._eval_evalf(prec)
if r is None:
r = self
return r
def _eval_evalf(self, prec):
return
def _to_mpmath(self, prec, allow_ints=True):
# mpmath functions accept ints as input
errmsg = "cannot convert to mpmath number"
if allow_ints and self.is_Integer:
return self.p
if hasattr(self, '_as_mpf_val'):
return make_mpf(self._as_mpf_val(prec))
try:
re, im, _, _ = evalf(self, prec, {})
if im:
if not re:
re = fzero
return make_mpc((re, im))
elif re:
return make_mpf(re)
else:
return make_mpf(fzero)
except NotImplementedError:
v = self._eval_evalf(prec)
if v is None:
raise ValueError(errmsg)
if v.is_Float:
return make_mpf(v._mpf_)
# Number + Number*I is also fine
re, im = v.as_real_imag()
if allow_ints and re.is_Integer:
re = from_int(re.p)
elif re.is_Float:
re = re._mpf_
else:
raise ValueError(errmsg)
if allow_ints and im.is_Integer:
im = from_int(im.p)
elif im.is_Float:
im = im._mpf_
else:
raise ValueError(errmsg)
return make_mpc((re, im))
def N(x, n=15, **options):
r"""
Calls x.evalf(n, \*\*options).
Explanations
============
Both .n() and N() are equivalent to .evalf(); use the one that you like better.
See also the docstring of .evalf() for information on the options.
Examples
========
>>> from sympy import Sum, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
"""
# by using rational=True, any evaluation of a string
# will be done using exact values for the Floats
return sympify(x, rational=True).evalf(n, **options)
|
99524209bb9c5e930871b11693af3bb11060f1482c7446c156658ce6383da614 | from collections import defaultdict
from functools import cmp_to_key, reduce
import operator
from .sympify import sympify
from .basic import Basic
from .singleton import S
from .operations import AssocOp, AssocOpDispatcher
from .cache import cacheit
from .logic import fuzzy_not, _fuzzy_group
from .expr import Expr
from .parameters import global_parameters
from .kind import KindDispatcher
# internal marker to indicate:
# "there are still non-commutative objects -- don't forget to process them"
class NC_Marker:
is_Order = False
is_Mul = False
is_Number = False
is_Poly = False
is_commutative = False
# Key for sorting commutative args in canonical order
_args_sortkey = cmp_to_key(Basic.compare)
def _mulsort(args):
# in-place sorting of args
args.sort(key=_args_sortkey)
def _unevaluated_Mul(*args):
"""Return a well-formed unevaluated Mul: Numbers are collected and
put in slot 0, any arguments that are Muls will be flattened, and args
are sorted. Use this when args have changed but you still want to return
an unevaluated Mul.
Examples
========
>>> from sympy.core.mul import _unevaluated_Mul as uMul
>>> from sympy import S, sqrt, Mul
>>> from sympy.abc import x
>>> a = uMul(*[S(3.0), x, S(2)])
>>> a.args[0]
6.00000000000000
>>> a.args[1]
x
Two unevaluated Muls with the same arguments will
always compare as equal during testing:
>>> m = uMul(sqrt(2), sqrt(3))
>>> m == uMul(sqrt(3), sqrt(2))
True
>>> u = Mul(sqrt(3), sqrt(2), evaluate=False)
>>> m == uMul(u)
True
>>> m == Mul(*m.args)
False
"""
args = list(args)
newargs = []
ncargs = []
co = S.One
while args:
a = args.pop()
if a.is_Mul:
c, nc = a.args_cnc()
args.extend(c)
if nc:
ncargs.append(Mul._from_args(nc))
elif a.is_Number:
co *= a
else:
newargs.append(a)
_mulsort(newargs)
if co is not S.One:
newargs.insert(0, co)
if ncargs:
newargs.append(Mul._from_args(ncargs))
return Mul._from_args(newargs)
class Mul(Expr, AssocOp):
"""
Expression representing multiplication operation for algebraic field.
Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*``
on most scalar objects in SymPy calls this class.
Another use of ``Mul()`` is to represent the structure of abstract
multiplication so that its arguments can be substituted to return
different class. Refer to examples section for this.
``Mul()`` evaluates the argument unless ``evaluate=False`` is passed.
The evaluation logic includes:
1. Flattening
``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)``
2. Identity removing
``Mul(x, 1, y)`` -> ``Mul(x, y)``
3. Exponent collecting by ``.as_base_exp()``
``Mul(x, x**2)`` -> ``Pow(x, 3)``
4. Term sorting
``Mul(y, x, 2)`` -> ``Mul(2, x, y)``
Since multiplication can be vector space operation, arguments may
have the different :obj:`sympy.core.kind.Kind()`. Kind of the
resulting object is automatically inferred.
Examples
========
>>> from sympy import Mul
>>> from sympy.abc import x, y
>>> Mul(x, 1)
x
>>> Mul(x, x)
x**2
If ``evaluate=False`` is passed, result is not evaluated.
>>> Mul(1, 2, evaluate=False)
1*2
>>> Mul(x, x, evaluate=False)
x*x
``Mul()`` also represents the general structure of multiplication
operation.
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 2,2)
>>> expr = Mul(x,y).subs({y:A})
>>> expr
x*A
>>> type(expr)
<class 'sympy.matrices.expressions.matmul.MatMul'>
See Also
========
MatMul
"""
__slots__ = ()
is_Mul = True
_args_type = Expr
_kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True)
@property
def kind(self):
arg_kinds = (a.kind for a in self.args)
return self._kind_dispatcher(*arg_kinds)
def __neg__(self):
c, args = self.as_coeff_mul()
c = -c
if c is not S.One:
if args[0].is_Number:
args = list(args)
if c is S.NegativeOne:
args[0] = -args[0]
else:
args[0] *= c
else:
args = (c,) + args
return self._from_args(args, self.is_commutative)
@classmethod
def flatten(cls, seq):
"""Return commutative, noncommutative and order arguments by
combining related terms.
Notes
=====
* In an expression like ``a*b*c``, python process this through sympy
as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.
- Sometimes terms are not combined as one would like:
{c.f. https://github.com/sympy/sympy/issues/4596}
>>> from sympy import Mul, sqrt
>>> from sympy.abc import x, y, z
>>> 2*(x + 1) # this is the 2-arg Mul behavior
2*x + 2
>>> y*(x + 1)*2
2*y*(x + 1)
>>> 2*(x + 1)*y # 2-arg result will be obtained first
y*(2*x + 2)
>>> Mul(2, x + 1, y) # all 3 args simultaneously processed
2*y*(x + 1)
>>> 2*((x + 1)*y) # parentheses can control this behavior
2*y*(x + 1)
Powers with compound bases may not find a single base to
combine with unless all arguments are processed at once.
Post-processing may be necessary in such cases.
{c.f. https://github.com/sympy/sympy/issues/5728}
>>> a = sqrt(x*sqrt(y))
>>> a**3
(x*sqrt(y))**(3/2)
>>> Mul(a,a,a)
(x*sqrt(y))**(3/2)
>>> a*a*a
x*sqrt(y)*sqrt(x*sqrt(y))
>>> _.subs(a.base, z).subs(z, a.base)
(x*sqrt(y))**(3/2)
- If more than two terms are being multiplied then all the
previous terms will be re-processed for each new argument.
So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
expression, then ``a*b*c`` (or building up the product
with ``*=``) will process all the arguments of ``a`` and
``b`` twice: once when ``a*b`` is computed and again when
``c`` is multiplied.
Using ``Mul(a, b, c)`` will process all arguments once.
* The results of Mul are cached according to arguments, so flatten
will only be called once for ``Mul(a, b, c)``. If you can
structure a calculation so the arguments are most likely to be
repeats then this can save time in computing the answer. For
example, say you had a Mul, M, that you wished to divide by ``d[i]``
and multiply by ``n[i]`` and you suspect there are many repeats
in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
product, ``M*n[i]`` will be returned without flattening -- the
cached value will be returned. If you divide by the ``d[i]``
first (and those are more unique than the ``n[i]``) then that will
create a new Mul, ``M/d[i]`` the args of which will be traversed
again when it is multiplied by ``n[i]``.
{c.f. https://github.com/sympy/sympy/issues/5706}
This consideration is moot if the cache is turned off.
NB
--
The validity of the above notes depends on the implementation
details of Mul and flatten which may change at any time. Therefore,
you should only consider them when your code is highly performance
sensitive.
Removal of 1 from the sequence is already handled by AssocOp.__new__.
"""
from sympy.calculus.util import AccumBounds
from sympy.matrices.expressions import MatrixExpr
rv = None
if len(seq) == 2:
a, b = seq
if b.is_Rational:
a, b = b, a
seq = [a, b]
assert not a is S.One
if not a.is_zero and a.is_Rational:
r, b = b.as_coeff_Mul()
if b.is_Add:
if r is not S.One: # 2-arg hack
# leave the Mul as a Mul?
ar = a*r
if ar is S.One:
arb = b
else:
arb = cls(a*r, b, evaluate=False)
rv = [arb], [], None
elif global_parameters.distribute and b.is_commutative:
r, b = b.as_coeff_Add()
bargs = [_keep_coeff(a, bi) for bi in Add.make_args(b)]
_addsort(bargs)
ar = a*r
if ar:
bargs.insert(0, ar)
bargs = [Add._from_args(bargs)]
rv = bargs, [], None
if rv:
return rv
# apply associativity, separate commutative part of seq
c_part = [] # out: commutative factors
nc_part = [] # out: non-commutative factors
nc_seq = []
coeff = S.One # standalone term
# e.g. 3 * ...
c_powers = [] # (base,exp) n
# e.g. (x,n) for x
num_exp = [] # (num-base, exp) y
# e.g. (3, y) for ... * 3 * ...
neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I
pnum_rat = {} # (num-base, Rat-exp) 1/2
# e.g. (3, 1/2) for ... * 3 * ...
order_symbols = None
# --- PART 1 ---
#
# "collect powers and coeff":
#
# o coeff
# o c_powers
# o num_exp
# o neg1e
# o pnum_rat
#
# NOTE: this is optimized for all-objects-are-commutative case
for o in seq:
# O(x)
if o.is_Order:
o, order_symbols = o.as_expr_variables(order_symbols)
# Mul([...])
if o.is_Mul:
if o.is_commutative:
seq.extend(o.args) # XXX zerocopy?
else:
# NCMul can have commutative parts as well
for q in o.args:
if q.is_commutative:
seq.append(q)
else:
nc_seq.append(q)
# append non-commutative marker, so we don't forget to
# process scheduled non-commutative objects
seq.append(NC_Marker)
continue
# 3
elif o.is_Number:
if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero:
# we know for sure the result will be nan
return [S.NaN], [], None
elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo
coeff *= o
if coeff is S.NaN:
# we know for sure the result will be nan
return [S.NaN], [], None
continue
elif isinstance(o, AccumBounds):
coeff = o.__mul__(coeff)
continue
elif o is S.ComplexInfinity:
if not coeff:
# 0 * zoo = NaN
return [S.NaN], [], None
coeff = S.ComplexInfinity
continue
elif o is S.ImaginaryUnit:
neg1e += S.Half
continue
elif o.is_commutative:
# e
# o = b
b, e = o.as_base_exp()
# y
# 3
if o.is_Pow:
if b.is_Number:
# get all the factors with numeric base so they can be
# combined below, but don't combine negatives unless
# the exponent is an integer
if e.is_Rational:
if e.is_Integer:
coeff *= Pow(b, e) # it is an unevaluated power
continue
elif e.is_negative: # also a sign of an unevaluated power
seq.append(Pow(b, e))
continue
elif b.is_negative:
neg1e += e
b = -b
if b is not S.One:
pnum_rat.setdefault(b, []).append(e)
continue
elif b.is_positive or e.is_integer:
num_exp.append((b, e))
continue
c_powers.append((b, e))
# NON-COMMUTATIVE
# TODO: Make non-commutative exponents not combine automatically
else:
if o is not NC_Marker:
nc_seq.append(o)
# process nc_seq (if any)
while nc_seq:
o = nc_seq.pop(0)
if not nc_part:
nc_part.append(o)
continue
# b c b+c
# try to combine last terms: a * a -> a
o1 = nc_part.pop()
b1, e1 = o1.as_base_exp()
b2, e2 = o.as_base_exp()
new_exp = e1 + e2
# Only allow powers to combine if the new exponent is
# not an Add. This allow things like a**2*b**3 == a**5
# if a.is_commutative == False, but prohibits
# a**x*a**y and x**a*x**b from combining (x,y commute).
if b1 == b2 and (not new_exp.is_Add):
o12 = b1 ** new_exp
# now o12 could be a commutative object
if o12.is_commutative:
seq.append(o12)
continue
else:
nc_seq.insert(0, o12)
else:
nc_part.append(o1)
nc_part.append(o)
# We do want a combined exponent if it would not be an Add, such as
# y 2y 3y
# x * x -> x
# We determine if two exponents have the same term by using
# as_coeff_Mul.
#
# Unfortunately, this isn't smart enough to consider combining into
# exponents that might already be adds, so things like:
# z - y y
# x * x will be left alone. This is because checking every possible
# combination can slow things down.
# gather exponents of common bases...
def _gather(c_powers):
common_b = {} # b:e
for b, e in c_powers:
co = e.as_coeff_Mul()
common_b.setdefault(b, {}).setdefault(
co[1], []).append(co[0])
for b, d in common_b.items():
for di, li in d.items():
d[di] = Add(*li)
new_c_powers = []
for b, e in common_b.items():
new_c_powers.extend([(b, c*t) for t, c in e.items()])
return new_c_powers
# in c_powers
c_powers = _gather(c_powers)
# and in num_exp
num_exp = _gather(num_exp)
# --- PART 2 ---
#
# o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
# o combine collected powers (2**x * 3**x -> 6**x)
# with numeric base
# ................................
# now we have:
# - coeff:
# - c_powers: (b, e)
# - num_exp: (2, e)
# - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
# 0 1
# x -> 1 x -> x
# this should only need to run twice; if it fails because
# it needs to be run more times, perhaps this should be
# changed to a "while True" loop -- the only reason it
# isn't such now is to allow a less-than-perfect result to
# be obtained rather than raising an error or entering an
# infinite loop
for i in range(2):
new_c_powers = []
changed = False
for b, e in c_powers:
if e.is_zero:
# canceling out infinities yields NaN
if (b.is_Add or b.is_Mul) and any(infty in b.args
for infty in (S.ComplexInfinity, S.Infinity,
S.NegativeInfinity)):
return [S.NaN], [], None
continue
if e is S.One:
if b.is_Number:
coeff *= b
continue
p = b
if e is not S.One:
p = Pow(b, e)
# check to make sure that the base doesn't change
# after exponentiation; to allow for unevaluated
# Pow, we only do so if b is not already a Pow
if p.is_Pow and not b.is_Pow:
bi = b
b, e = p.as_base_exp()
if b != bi:
changed = True
c_part.append(p)
new_c_powers.append((b, e))
# there might have been a change, but unless the base
# matches some other base, there is nothing to do
if changed and len({
b for b, e in new_c_powers}) != len(new_c_powers):
# start over again
c_part = []
c_powers = _gather(new_c_powers)
else:
break
# x x x
# 2 * 3 -> 6
inv_exp_dict = {} # exp:Mul(num-bases) x x
# e.g. x:6 for ... * 2 * 3 * ...
for b, e in num_exp:
inv_exp_dict.setdefault(e, []).append(b)
for e, b in inv_exp_dict.items():
inv_exp_dict[e] = cls(*b)
c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
# b, e -> e' = sum(e), b
# {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
comb_e = {}
for b, e in pnum_rat.items():
comb_e.setdefault(Add(*e), []).append(b)
del pnum_rat
# process them, reducing exponents to values less than 1
# and updating coeff if necessary else adding them to
# num_rat for further processing
num_rat = []
for e, b in comb_e.items():
b = cls(*b)
if e.q == 1:
coeff *= Pow(b, e)
continue
if e.p > e.q:
e_i, ep = divmod(e.p, e.q)
coeff *= Pow(b, e_i)
e = Rational(ep, e.q)
num_rat.append((b, e))
del comb_e
# extract gcd of bases in num_rat
# 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
pnew = defaultdict(list)
i = 0 # steps through num_rat which may grow
while i < len(num_rat):
bi, ei = num_rat[i]
grow = []
for j in range(i + 1, len(num_rat)):
bj, ej = num_rat[j]
g = bi.gcd(bj)
if g is not S.One:
# 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
# this might have a gcd with something else
e = ei + ej
if e.q == 1:
coeff *= Pow(g, e)
else:
if e.p > e.q:
e_i, ep = divmod(e.p, e.q) # change e in place
coeff *= Pow(g, e_i)
e = Rational(ep, e.q)
grow.append((g, e))
# update the jth item
num_rat[j] = (bj/g, ej)
# update bi that we are checking with
bi = bi/g
if bi is S.One:
break
if bi is not S.One:
obj = Pow(bi, ei)
if obj.is_Number:
coeff *= obj
else:
# changes like sqrt(12) -> 2*sqrt(3)
for obj in Mul.make_args(obj):
if obj.is_Number:
coeff *= obj
else:
assert obj.is_Pow
bi, ei = obj.args
pnew[ei].append(bi)
num_rat.extend(grow)
i += 1
# combine bases of the new powers
for e, b in pnew.items():
pnew[e] = cls(*b)
# handle -1 and I
if neg1e:
# treat I as (-1)**(1/2) and compute -1's total exponent
p, q = neg1e.as_numer_denom()
# if the integer part is odd, extract -1
n, p = divmod(p, q)
if n % 2:
coeff = -coeff
# if it's a multiple of 1/2 extract I
if q == 2:
c_part.append(S.ImaginaryUnit)
elif p:
# see if there is any positive base this power of
# -1 can join
neg1e = Rational(p, q)
for e, b in pnew.items():
if e == neg1e and b.is_positive:
pnew[e] = -b
break
else:
# keep it separate; we've already evaluated it as
# much as possible so evaluate=False
c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
# add all the pnew powers
c_part.extend([Pow(b, e) for e, b in pnew.items()])
# oo, -oo
if (coeff is S.Infinity) or (coeff is S.NegativeInfinity):
def _handle_for_oo(c_part, coeff_sign):
new_c_part = []
for t in c_part:
if t.is_extended_positive:
continue
if t.is_extended_negative:
coeff_sign *= -1
continue
new_c_part.append(t)
return new_c_part, coeff_sign
c_part, coeff_sign = _handle_for_oo(c_part, 1)
nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
coeff *= coeff_sign
# zoo
if coeff is S.ComplexInfinity:
# zoo might be
# infinite_real + bounded_im
# bounded_real + infinite_im
# infinite_real + infinite_im
# and non-zero real or imaginary will not change that status.
c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
c.is_extended_real is not None)]
nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
c.is_extended_real is not None)]
# 0
elif coeff.is_zero:
# we know for sure the result will be 0 except the multiplicand
# is infinity or a matrix
if any(isinstance(c, MatrixExpr) for c in nc_part):
return [coeff], nc_part, order_symbols
if any(c.is_finite == False for c in c_part):
return [S.NaN], [], order_symbols
return [coeff], [], order_symbols
# check for straggling Numbers that were produced
_new = []
for i in c_part:
if i.is_Number:
coeff *= i
else:
_new.append(i)
c_part = _new
# order commutative part canonically
_mulsort(c_part)
# current code expects coeff to be always in slot-0
if coeff is not S.One:
c_part.insert(0, coeff)
# we are done
if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
# 2*(1+a) -> 2 + 2 * a
coeff = c_part[0]
c_part = [Add(*[coeff*f for f in c_part[1].args])]
return c_part, nc_part, order_symbols
def _eval_power(self, e):
# don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
cargs, nc = self.args_cnc(split_1=False)
if e.is_Integer:
return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
Pow(Mul._from_args(nc), e, evaluate=False)
if e.is_Rational and e.q == 2:
from sympy.core.power import integer_nthroot
from sympy.functions.elementary.complexes import sign
if self.is_imaginary:
a = self.as_real_imag()[1]
if a.is_Rational:
n, d = abs(a/2).as_numer_denom()
n, t = integer_nthroot(n, 2)
if t:
d, t = integer_nthroot(d, 2)
if t:
r = sympify(n)/d
return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
p = Pow(self, e, evaluate=False)
if e.is_Rational or e.is_Float:
return p._eval_expand_power_base()
return p
@classmethod
def class_key(cls):
return 3, 0, cls.__name__
def _eval_evalf(self, prec):
c, m = self.as_coeff_Mul()
if c is S.NegativeOne:
if m.is_Mul:
rv = -AssocOp._eval_evalf(m, prec)
else:
mnew = m._eval_evalf(prec)
if mnew is not None:
m = mnew
rv = -m
else:
rv = AssocOp._eval_evalf(self, prec)
if rv.is_number:
return rv.expand()
return rv
@property
def _mpc_(self):
"""
Convert self to an mpmath mpc if possible
"""
from sympy.core.numbers import I, Float
im_part, imag_unit = self.as_coeff_Mul()
if not imag_unit == I:
# ValueError may seem more reasonable but since it's a @property,
# we need to use AttributeError to keep from confusing things like
# hasattr.
raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
return (Float(0)._mpf_, Float(im_part)._mpf_)
@cacheit
def as_two_terms(self):
"""Return head and tail of self.
This is the most efficient way to get the head and tail of an
expression.
- if you want only the head, use self.args[0];
- if you want to process the arguments of the tail then use
self.as_coef_mul() which gives the head and a tuple containing
the arguments of the tail when treated as a Mul.
- if you want the coefficient when self is treated as an Add
then use self.as_coeff_add()[0]
Examples
========
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
"""
args = self.args
if len(args) == 1:
return S.One, self
elif len(args) == 2:
return args
else:
return args[0], self._new_rawargs(*args[1:])
@cacheit
def as_coefficients_dict(self):
"""Return a dictionary mapping terms to their coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. The dictionary
is considered to have a single term.
Examples
========
>>> from sympy.abc import a, x
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
>>> _[a]
0
"""
d = defaultdict(int)
args = self.args
if len(args) == 1 or not args[0].is_Number:
d[self] = S.One
else:
d[self._new_rawargs(*args[1:])] = args[0]
return d
@cacheit
def as_coeff_mul(self, *deps, rational=True, **kwargs):
if deps:
from sympy.utilities.iterables import sift
l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
return self._new_rawargs(*l2), tuple(l1)
args = self.args
if args[0].is_Number:
if not rational or args[0].is_Rational:
return args[0], args[1:]
elif args[0].is_extended_negative:
return S.NegativeOne, (-args[0],) + args[1:]
return S.One, args
def as_coeff_Mul(self, rational=False):
"""
Efficiently extract the coefficient of a product.
"""
coeff, args = self.args[0], self.args[1:]
if coeff.is_Number:
if not rational or coeff.is_Rational:
if len(args) == 1:
return coeff, args[0]
else:
return coeff, self._new_rawargs(*args)
elif coeff.is_extended_negative:
return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
return S.One, self
def as_real_imag(self, deep=True, **hints):
from sympy import Abs, expand_mul, im, re
other = []
coeffr = []
coeffi = []
addterms = S.One
for a in self.args:
r, i = a.as_real_imag()
if i.is_zero:
coeffr.append(r)
elif r.is_zero:
coeffi.append(i*S.ImaginaryUnit)
elif a.is_commutative:
# search for complex conjugate pairs:
for i, x in enumerate(other):
if x == a.conjugate():
coeffr.append(Abs(x)**2)
del other[i]
break
else:
if a.is_Add:
addterms *= a
else:
other.append(a)
else:
other.append(a)
m = self.func(*other)
if hints.get('ignore') == m:
return
if len(coeffi) % 2:
imco = im(coeffi.pop(0))
# all other pairs make a real factor; they will be
# put into reco below
else:
imco = S.Zero
reco = self.func(*(coeffr + coeffi))
r, i = (reco*re(m), reco*im(m))
if addterms == 1:
if m == 1:
if imco.is_zero:
return (reco, S.Zero)
else:
return (S.Zero, reco*imco)
if imco is S.Zero:
return (r, i)
return (-imco*i, imco*r)
addre, addim = expand_mul(addterms, deep=False).as_real_imag()
if imco is S.Zero:
return (r*addre - i*addim, i*addre + r*addim)
else:
r, i = -imco*i, imco*r
return (r*addre - i*addim, r*addim + i*addre)
@staticmethod
def _expandsums(sums):
"""
Helper function for _eval_expand_mul.
sums must be a list of instances of Basic.
"""
L = len(sums)
if L == 1:
return sums[0].args
terms = []
left = Mul._expandsums(sums[:L//2])
right = Mul._expandsums(sums[L//2:])
terms = [Mul(a, b) for a in left for b in right]
added = Add(*terms)
return Add.make_args(added) # it may have collapsed down to one term
def _eval_expand_mul(self, **hints):
from sympy import fraction
# Handle things like 1/(x*(x + 1)), which are automatically converted
# to 1/x*1/(x + 1)
expr = self
n, d = fraction(expr)
if d.is_Mul:
n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
for i in (n, d)]
expr = n/d
if not expr.is_Mul:
return expr
plain, sums, rewrite = [], [], False
for factor in expr.args:
if factor.is_Add:
sums.append(factor)
rewrite = True
else:
if factor.is_commutative:
plain.append(factor)
else:
sums.append(Basic(factor)) # Wrapper
if not rewrite:
return expr
else:
plain = self.func(*plain)
if sums:
deep = hints.get("deep", False)
terms = self.func._expandsums(sums)
args = []
for term in terms:
t = self.func(plain, term)
if t.is_Mul and any(a.is_Add for a in t.args) and deep:
t = t._eval_expand_mul()
args.append(t)
return Add(*args)
else:
return plain
@cacheit
def _eval_derivative(self, s):
args = list(self.args)
terms = []
for i in range(len(args)):
d = args[i].diff(s)
if d:
# Note: reduce is used in step of Mul as Mul is unable to
# handle subtypes and operation priority:
terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
return Add.fromiter(terms)
@cacheit
def _eval_derivative_n_times(self, s, n):
from sympy import Integer, factorial, prod, Sum, Max
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
from .function import AppliedUndef
from .symbol import Symbol, symbols, Dummy
if not isinstance(s, AppliedUndef) and not isinstance(s, Symbol):
# other types of s may not be well behaved, e.g.
# (cos(x)*sin(y)).diff([[x, y, z]])
return super()._eval_derivative_n_times(s, n)
args = self.args
m = len(args)
if isinstance(n, (int, Integer)):
# https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
terms = []
for kvals, c in multinomial_coefficients_iterator(m, n):
p = prod([arg.diff((s, k)) for k, arg in zip(kvals, args)])
terms.append(c * p)
return Add(*terms)
kvals = symbols("k1:%i" % m, cls=Dummy)
klast = n - sum(kvals)
nfact = factorial(n)
e, l = (# better to use the multinomial?
nfact/prod(map(factorial, kvals))/factorial(klast)*\
prod([args[t].diff((s, kvals[t])) for t in range(m-1)])*\
args[-1].diff((s, Max(0, klast))),
[(k, 0, n) for k in kvals])
return Sum(e, *l)
def _eval_difference_delta(self, n, step):
from sympy.series.limitseq import difference_delta as dd
arg0 = self.args[0]
rest = Mul(*self.args[1:])
return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
rest)
def _matches_simple(self, expr, repl_dict):
# handle (w*3).matches('x*5') -> {w: x*5/3}
coeff, terms = self.as_coeff_Mul()
terms = Mul.make_args(terms)
if len(terms) == 1:
newexpr = self.__class__._combine_inverse(expr, coeff)
return terms[0].matches(newexpr, repl_dict)
return
def matches(self, expr, repl_dict={}, old=False):
expr = sympify(expr)
repl_dict = repl_dict.copy()
if self.is_commutative and expr.is_commutative:
return self._matches_commutative(expr, repl_dict, old)
elif self.is_commutative is not expr.is_commutative:
return None
# Proceed only if both both expressions are non-commutative
c1, nc1 = self.args_cnc()
c2, nc2 = expr.args_cnc()
c1, c2 = [c or [1] for c in [c1, c2]]
# TODO: Should these be self.func?
comm_mul_self = Mul(*c1)
comm_mul_expr = Mul(*c2)
repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
# If the commutative arguments didn't match and aren't equal, then
# then the expression as a whole doesn't match
if repl_dict is None and c1 != c2:
return None
# Now match the non-commutative arguments, expanding powers to
# multiplications
nc1 = Mul._matches_expand_pows(nc1)
nc2 = Mul._matches_expand_pows(nc2)
repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
return repl_dict or None
@staticmethod
def _matches_expand_pows(arg_list):
new_args = []
for arg in arg_list:
if arg.is_Pow and arg.exp > 0:
new_args.extend([arg.base] * arg.exp)
else:
new_args.append(arg)
return new_args
@staticmethod
def _matches_noncomm(nodes, targets, repl_dict={}):
"""Non-commutative multiplication matcher.
`nodes` is a list of symbols within the matcher multiplication
expression, while `targets` is a list of arguments in the
multiplication expression being matched against.
"""
repl_dict = repl_dict.copy()
# List of possible future states to be considered
agenda = []
# The current matching state, storing index in nodes and targets
state = (0, 0)
node_ind, target_ind = state
# Mapping between wildcard indices and the index ranges they match
wildcard_dict = {}
repl_dict = repl_dict.copy()
while target_ind < len(targets) and node_ind < len(nodes):
node = nodes[node_ind]
if node.is_Wild:
Mul._matches_add_wildcard(wildcard_dict, state)
states_matches = Mul._matches_new_states(wildcard_dict, state,
nodes, targets)
if states_matches:
new_states, new_matches = states_matches
agenda.extend(new_states)
if new_matches:
for match in new_matches:
repl_dict[match] = new_matches[match]
if not agenda:
return None
else:
state = agenda.pop()
node_ind, target_ind = state
return repl_dict
@staticmethod
def _matches_add_wildcard(dictionary, state):
node_ind, target_ind = state
if node_ind in dictionary:
begin, end = dictionary[node_ind]
dictionary[node_ind] = (begin, target_ind)
else:
dictionary[node_ind] = (target_ind, target_ind)
@staticmethod
def _matches_new_states(dictionary, state, nodes, targets):
node_ind, target_ind = state
node = nodes[node_ind]
target = targets[target_ind]
# Don't advance at all if we've exhausted the targets but not the nodes
if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
return None
if node.is_Wild:
match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
nodes, targets)
if match_attempt:
# If the same node has been matched before, don't return
# anything if the current match is diverging from the previous
# match
other_node_inds = Mul._matches_get_other_nodes(dictionary,
nodes, node_ind)
for ind in other_node_inds:
other_begin, other_end = dictionary[ind]
curr_begin, curr_end = dictionary[node_ind]
other_targets = targets[other_begin:other_end + 1]
current_targets = targets[curr_begin:curr_end + 1]
for curr, other in zip(current_targets, other_targets):
if curr != other:
return None
# A wildcard node can match more than one target, so only the
# target index is advanced
new_state = [(node_ind, target_ind + 1)]
# Only move on to the next node if there is one
if node_ind < len(nodes) - 1:
new_state.append((node_ind + 1, target_ind + 1))
return new_state, match_attempt
else:
# If we're not at a wildcard, then make sure we haven't exhausted
# nodes but not targets, since in this case one node can only match
# one target
if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
return None
match_attempt = node.matches(target)
if match_attempt:
return [(node_ind + 1, target_ind + 1)], match_attempt
elif node == target:
return [(node_ind + 1, target_ind + 1)], None
else:
return None
@staticmethod
def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
"""Determine matches of a wildcard with sub-expression in `target`."""
wildcard = nodes[wildcard_ind]
begin, end = dictionary[wildcard_ind]
terms = targets[begin:end + 1]
# TODO: Should this be self.func?
mul = Mul(*terms) if len(terms) > 1 else terms[0]
return wildcard.matches(mul)
@staticmethod
def _matches_get_other_nodes(dictionary, nodes, node_ind):
"""Find other wildcards that may have already been matched."""
other_node_inds = []
for ind in dictionary:
if nodes[ind] == nodes[node_ind]:
other_node_inds.append(ind)
return other_node_inds
@staticmethod
def _combine_inverse(lhs, rhs):
"""
Returns lhs/rhs, but treats arguments like symbols, so things
like oo/oo return 1 (instead of a nan) and ``I`` behaves like
a symbol instead of sqrt(-1).
"""
from sympy.simplify.simplify import signsimp
from .symbol import Dummy
if lhs == rhs:
return S.One
def check(l, r):
if l.is_Float and r.is_comparable:
# if both objects are added to 0 they will share the same "normalization"
# and are more likely to compare the same. Since Add(foo, 0) will not allow
# the 0 to pass, we use __add__ directly.
return l.__add__(0) == r.evalf().__add__(0)
return False
if check(lhs, rhs) or check(rhs, lhs):
return S.One
if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
# gruntz and limit wants a literal I to not combine
# with a power of -1
d = Dummy('I')
_i = {S.ImaginaryUnit: d}
i_ = {d: S.ImaginaryUnit}
a = lhs.xreplace(_i).as_powers_dict()
b = rhs.xreplace(_i).as_powers_dict()
blen = len(b)
for bi in tuple(b.keys()):
if bi in a:
a[bi] -= b.pop(bi)
if not a[bi]:
a.pop(bi)
if len(b) != blen:
lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
return signsimp(lhs/rhs)
def as_powers_dict(self):
d = defaultdict(int)
for term in self.args:
for b, e in term.as_powers_dict().items():
d[b] += e
return d
def as_numer_denom(self):
# don't use _from_args to rebuild the numerators and denominators
# as the order is not guaranteed to be the same once they have
# been separated from each other
numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
return self.func(*numers), self.func(*denoms)
def as_base_exp(self):
e1 = None
bases = []
nc = 0
for m in self.args:
b, e = m.as_base_exp()
if not b.is_commutative:
nc += 1
if e1 is None:
e1 = e
elif e != e1 or nc > 1:
return self, S.One
bases.append(b)
return self.func(*bases), e1
def _eval_is_polynomial(self, syms):
return all(term._eval_is_polynomial(syms) for term in self.args)
def _eval_is_rational_function(self, syms):
return all(term._eval_is_rational_function(syms) for term in self.args)
def _eval_is_meromorphic(self, x, a):
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
quick_exit=True)
def _eval_is_algebraic_expr(self, syms):
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
_eval_is_commutative = lambda self: _fuzzy_group(
a.is_commutative for a in self.args)
def _eval_is_complex(self):
comp = _fuzzy_group(a.is_complex for a in self.args)
if comp is False:
if any(a.is_infinite for a in self.args):
if any(a.is_zero is not False for a in self.args):
return None
return False
return comp
def _eval_is_finite(self):
if all(a.is_finite for a in self.args):
return True
if any(a.is_infinite for a in self.args):
if all(a.is_zero is False for a in self.args):
return False
def _eval_is_infinite(self):
if any(a.is_infinite for a in self.args):
if any(a.is_zero for a in self.args):
return S.NaN.is_infinite
if any(a.is_zero is None for a in self.args):
return None
return True
def _eval_is_rational(self):
r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
if r:
return r
elif r is False:
return self.is_zero
def _eval_is_algebraic(self):
r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
if r:
return r
elif r is False:
return self.is_zero
def _eval_is_zero(self):
zero = infinite = False
for a in self.args:
z = a.is_zero
if z:
if infinite:
return # 0*oo is nan and nan.is_zero is None
zero = True
else:
if not a.is_finite:
if zero:
return # 0*oo is nan and nan.is_zero is None
infinite = True
if zero is False and z is None: # trap None
zero = None
return zero
# without involving odd/even checks this code would suffice:
#_eval_is_integer = lambda self: _fuzzy_group(
# (a.is_integer for a in self.args), quick_exit=True)
def _eval_is_integer(self):
is_rational = self._eval_is_rational()
if is_rational is False:
return False
numerators = []
denominators = []
for a in self.args:
if a.is_integer:
numerators.append(a)
elif a.is_Rational:
n, d = a.as_numer_denom()
numerators.append(n)
denominators.append(d)
elif a.is_Pow:
b, e = a.as_base_exp()
if not b.is_integer or not e.is_integer: return
if e.is_negative:
denominators.append(b)
else:
# for integer b and positive integer e: a = b**e would be integer
assert not e.is_positive
# for self being rational and e equal to zero: a = b**e would be 1
assert not e.is_zero
return # sign of e unknown -> self.is_integer cannot be decided
else:
return
if not denominators:
return True
odd = lambda ints: all(i.is_odd for i in ints)
even = lambda ints: any(i.is_even for i in ints)
if odd(numerators) and even(denominators):
return False
elif even(numerators) and denominators == [2]:
return True
def _eval_is_polar(self):
has_polar = any(arg.is_polar for arg in self.args)
return has_polar and \
all(arg.is_polar or arg.is_positive for arg in self.args)
def _eval_is_extended_real(self):
return self._eval_real_imag(True)
def _eval_real_imag(self, real):
zero = False
t_not_re_im = None
for t in self.args:
if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
return False
elif t.is_imaginary: # I
real = not real
elif t.is_extended_real: # 2
if not zero:
z = t.is_zero
if not z and zero is False:
zero = z
elif z:
if all(a.is_finite for a in self.args):
return True
return
elif t.is_extended_real is False:
# symbolic or literal like `2 + I` or symbolic imaginary
if t_not_re_im:
return # complex terms might cancel
t_not_re_im = t
elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
if t_not_re_im:
return # complex terms might cancel
t_not_re_im = t
else:
return
if t_not_re_im:
if t_not_re_im.is_extended_real is False:
if real: # like 3
return zero # 3*(smthng like 2 + I or i) is not real
if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
if not real: # like I
return zero # I*(smthng like 2 or 2 + I) is not real
elif zero is False:
return real # can't be trumped by 0
elif real:
return real # doesn't matter what zero is
def _eval_is_imaginary(self):
z = self.is_zero
if z:
return False
if self.is_finite is False:
return False
elif z is False and self.is_finite is True:
return self._eval_real_imag(False)
def _eval_is_hermitian(self):
return self._eval_herm_antiherm(True)
def _eval_herm_antiherm(self, real):
one_nc = zero = one_neither = False
for t in self.args:
if not t.is_commutative:
if one_nc:
return
one_nc = True
if t.is_antihermitian:
real = not real
elif t.is_hermitian:
if not zero:
z = t.is_zero
if not z and zero is False:
zero = z
elif z:
if all(a.is_finite for a in self.args):
return True
return
elif t.is_hermitian is False:
if one_neither:
return
one_neither = True
else:
return
if one_neither:
if real:
return zero
elif zero is False or real:
return real
def _eval_is_antihermitian(self):
z = self.is_zero
if z:
return False
elif z is False:
return self._eval_herm_antiherm(False)
def _eval_is_irrational(self):
for t in self.args:
a = t.is_irrational
if a:
others = list(self.args)
others.remove(t)
if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
return True
return
if a is None:
return
if all(x.is_real for x in self.args):
return False
def _eval_is_extended_positive(self):
"""Return True if self is positive, False if not, and None if it
cannot be determined.
Explanation
===========
This algorithm is non-recursive and works by keeping track of the
sign which changes when a negative or nonpositive is encountered.
Whether a nonpositive or nonnegative is seen is also tracked since
the presence of these makes it impossible to return True, but
possible to return False if the end result is nonpositive. e.g.
pos * neg * nonpositive -> pos or zero -> None is returned
pos * neg * nonnegative -> neg or zero -> False is returned
"""
return self._eval_pos_neg(1)
def _eval_pos_neg(self, sign):
saw_NON = saw_NOT = False
for t in self.args:
if t.is_extended_positive:
continue
elif t.is_extended_negative:
sign = -sign
elif t.is_zero:
if all(a.is_finite for a in self.args):
return False
return
elif t.is_extended_nonpositive:
sign = -sign
saw_NON = True
elif t.is_extended_nonnegative:
saw_NON = True
# FIXME: is_positive/is_negative is False doesn't take account of
# Symbol('x', infinite=True, extended_real=True) which has
# e.g. is_positive is False but has uncertain sign.
elif t.is_positive is False:
sign = -sign
if saw_NOT:
return
saw_NOT = True
elif t.is_negative is False:
if saw_NOT:
return
saw_NOT = True
else:
return
if sign == 1 and saw_NON is False and saw_NOT is False:
return True
if sign < 0:
return False
def _eval_is_extended_negative(self):
return self._eval_pos_neg(-1)
def _eval_is_odd(self):
is_integer = self.is_integer
if is_integer:
r, acc = True, 1
for t in self.args:
if not t.is_integer:
return None
elif t.is_even:
r = False
elif t.is_integer:
if r is False:
pass
elif acc != 1 and (acc + t).is_odd:
r = False
elif t.is_odd is None:
r = None
acc = t
return r
# !integer -> !odd
elif is_integer is False:
return False
def _eval_is_even(self):
is_integer = self.is_integer
if is_integer:
return fuzzy_not(self.is_odd)
elif is_integer is False:
return False
def _eval_is_composite(self):
"""
Here we count the number of arguments that have a minimum value
greater than two.
If there are more than one of such a symbol then the result is composite.
Else, the result cannot be determined.
"""
number_of_args = 0 # count of symbols with minimum value greater than one
for arg in self.args:
if not (arg.is_integer and arg.is_positive):
return None
if (arg-1).is_positive:
number_of_args += 1
if number_of_args > 1:
return True
def _eval_subs(self, old, new):
from sympy.functions.elementary.complexes import sign
from sympy.ntheory.factor_ import multiplicity
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import fraction
if not old.is_Mul:
return None
# try keep replacement literal so -2*x doesn't replace 4*x
if old.args[0].is_Number and old.args[0] < 0:
if self.args[0].is_Number:
if self.args[0] < 0:
return self._subs(-old, -new)
return None
def base_exp(a):
# if I and -1 are in a Mul, they get both end up with
# a -1 base (see issue 6421); all we want here are the
# true Pow or exp separated into base and exponent
from sympy import exp
if a.is_Pow or isinstance(a, exp):
return a.as_base_exp()
return a, S.One
def breakup(eq):
"""break up powers of eq when treated as a Mul:
b**(Rational*e) -> b**e, Rational
commutatives come back as a dictionary {b**e: Rational}
noncommutatives come back as a list [(b**e, Rational)]
"""
(c, nc) = (defaultdict(int), list())
for a in Mul.make_args(eq):
a = powdenest(a)
(b, e) = base_exp(a)
if e is not S.One:
(co, _) = e.as_coeff_mul()
b = Pow(b, e/co)
e = co
if a.is_commutative:
c[b] += e
else:
nc.append([b, e])
return (c, nc)
def rejoin(b, co):
"""
Put rational back with exponent; in general this is not ok, but
since we took it from the exponent for analysis, it's ok to put
it back.
"""
(b, e) = base_exp(b)
return Pow(b, e*co)
def ndiv(a, b):
"""if b divides a in an extractive way (like 1/4 divides 1/2
but not vice versa, and 2/5 does not divide 1/3) then return
the integer number of times it divides, else return 0.
"""
if not b.q % a.q or not a.q % b.q:
return int(a/b)
return 0
# give Muls in the denominator a chance to be changed (see issue 5651)
# rv will be the default return value
rv = None
n, d = fraction(self)
self2 = self
if d is not S.One:
self2 = n._subs(old, new)/d._subs(old, new)
if not self2.is_Mul:
return self2._subs(old, new)
if self2 != self:
rv = self2
# Now continue with regular substitution.
# handle the leading coefficient and use it to decide if anything
# should even be started; we always know where to find the Rational
# so it's a quick test
co_self = self2.args[0]
co_old = old.args[0]
co_xmul = None
if co_old.is_Rational and co_self.is_Rational:
# if coeffs are the same there will be no updating to do
# below after breakup() step; so skip (and keep co_xmul=None)
if co_old != co_self:
co_xmul = co_self.extract_multiplicatively(co_old)
elif co_old.is_Rational:
return rv
# break self and old into factors
(c, nc) = breakup(self2)
(old_c, old_nc) = breakup(old)
# update the coefficients if we had an extraction
# e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
# then co_self in c is replaced by (3/5)**2 and co_residual
# is 2*(1/7)**2
if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
mult = S(multiplicity(abs(co_old), co_self))
c.pop(co_self)
if co_old in c:
c[co_old] += mult
else:
c[co_old] = mult
co_residual = co_self/co_old**mult
else:
co_residual = 1
# do quick tests to see if we can't succeed
ok = True
if len(old_nc) > len(nc):
# more non-commutative terms
ok = False
elif len(old_c) > len(c):
# more commutative terms
ok = False
elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
# unmatched non-commutative bases
ok = False
elif set(old_c).difference(set(c)):
# unmatched commutative terms
ok = False
elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
# differences in sign
ok = False
if not ok:
return rv
if not old_c:
cdid = None
else:
rat = []
for (b, old_e) in old_c.items():
c_e = c[b]
rat.append(ndiv(c_e, old_e))
if not rat[-1]:
return rv
cdid = min(rat)
if not old_nc:
ncdid = None
for i in range(len(nc)):
nc[i] = rejoin(*nc[i])
else:
ncdid = 0 # number of nc replacements we did
take = len(old_nc) # how much to look at each time
limit = cdid or S.Infinity # max number that we can take
failed = [] # failed terms will need subs if other terms pass
i = 0
while limit and i + take <= len(nc):
hit = False
# the bases must be equivalent in succession, and
# the powers must be extractively compatible on the
# first and last factor but equal in between.
rat = []
for j in range(take):
if nc[i + j][0] != old_nc[j][0]:
break
elif j == 0:
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
elif j == take - 1:
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
elif nc[i + j][1] != old_nc[j][1]:
break
else:
rat.append(1)
j += 1
else:
ndo = min(rat)
if ndo:
if take == 1:
if cdid:
ndo = min(cdid, ndo)
nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
nc[i][1] - ndo*old_nc[0][1])
else:
ndo = 1
# the left residual
l = rejoin(nc[i][0], nc[i][1] - ndo*
old_nc[0][1])
# eliminate all middle terms
mid = new
# the right residual (which may be the same as the middle if take == 2)
ir = i + take - 1
r = (nc[ir][0], nc[ir][1] - ndo*
old_nc[-1][1])
if r[1]:
if i + take < len(nc):
nc[i:i + take] = [l*mid, r]
else:
r = rejoin(*r)
nc[i:i + take] = [l*mid*r]
else:
# there was nothing left on the right
nc[i:i + take] = [l*mid]
limit -= ndo
ncdid += ndo
hit = True
if not hit:
# do the subs on this failing factor
failed.append(i)
i += 1
else:
if not ncdid:
return rv
# although we didn't fail, certain nc terms may have
# failed so we rebuild them after attempting a partial
# subs on them
failed.extend(range(i, len(nc)))
for i in failed:
nc[i] = rejoin(*nc[i]).subs(old, new)
# rebuild the expression
if cdid is None:
do = ncdid
elif ncdid is None:
do = cdid
else:
do = min(ncdid, cdid)
margs = []
for b in c:
if b in old_c:
# calculate the new exponent
e = c[b] - old_c[b]*do
margs.append(rejoin(b, e))
else:
margs.append(rejoin(b.subs(old, new), c[b]))
if cdid and not ncdid:
# in case we are replacing commutative with non-commutative,
# we want the new term to come at the front just like the
# rest of this routine
margs = [Pow(new, cdid)] + margs
return co_residual*self2.func(*margs)*self2.func(*nc)
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy import degree, Mul, Order, ceiling, powsimp, PolynomialError
from itertools import product
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
ords = []
try:
for t in self.args:
coeff, exp = t.leadterm(x)
if not coeff.has(x):
ords.append((t, exp))
else:
raise ValueError
n0 = sum(t[1] for t in ords)
facs = []
for t, m in ords:
n1 = ceiling(n - n0 + m)
s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
ns = s.getn()
if ns is not None:
if ns < n1: # less than expected
n -= n1 - ns # reduce n
facs.append(s.removeO())
except (ValueError, NotImplementedError, TypeError, AttributeError):
facs = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
if res.has(Order):
res += Order(x**n, x)
return res
res = 0
ords2 = [Add.make_args(factor) for factor in facs]
for fac in product(*ords2):
ords3 = [coeff_exp(term, x) for term in fac]
coeffs, powers = zip(*ords3)
power = sum(powers)
if power < n:
res += Mul(*coeffs)*(x**power)
if self.is_polynomial(x):
try:
if degree(self, x) != degree(res, x):
res += Order(x**n, x)
except PolynomialError:
pass
else:
return res
for i in (1, 2, 3):
if (res - self).subs(x, i) is not S.Zero:
res += Order(x**n, x)
break
return res
def _eval_as_leading_term(self, x, cdir=0):
return self.func(*[t.as_leading_term(x, cdir=cdir) for t in self.args])
def _eval_conjugate(self):
return self.func(*[t.conjugate() for t in self.args])
def _eval_transpose(self):
return self.func(*[t.transpose() for t in self.args[::-1]])
def _eval_adjoint(self):
return self.func(*[t.adjoint() for t in self.args[::-1]])
def _sage_(self):
s = 1
for x in self.args:
s *= x._sage_()
return s
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import sqrt
>>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
(6, -sqrt(2)*(1 - sqrt(2)))
See docstring of Expr.as_content_primitive for more examples.
"""
coef = S.One
args = []
for i, a in enumerate(self.args):
c, p = a.as_content_primitive(radical=radical, clear=clear)
coef *= c
if p is not S.One:
args.append(p)
# don't use self._from_args here to reconstruct args
# since there may be identical args now that should be combined
# e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
return coef, self.func(*args)
def as_ordered_factors(self, order=None):
"""Transform an expression into an ordered list of factors.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
"""
cpart, ncpart = self.args_cnc()
cpart.sort(key=lambda expr: expr.sort_key(order=order))
return cpart + ncpart
@property
def _sorted_args(self):
return tuple(self.as_ordered_factors())
mul = AssocOpDispatcher('mul')
def prod(a, start=1):
"""Return product of elements of a. Start with int 1 so if only
ints are included then an int result is returned.
Examples
========
>>> from sympy import prod, S
>>> prod(range(3))
0
>>> type(_) is int
True
>>> prod([S(2), 3])
6
>>> _.is_Integer
True
You can start the product at something other than 1:
>>> prod([1, 2], 3)
6
"""
return reduce(operator.mul, a, start)
def _keep_coeff(coeff, factors, clear=True, sign=False):
"""Return ``coeff*factors`` unevaluated if necessary.
If ``clear`` is False, do not keep the coefficient as a factor
if it can be distributed on a single factor such that one or
more terms will still have integer coefficients.
If ``sign`` is True, allow a coefficient of -1 to remain factored out.
Examples
========
>>> from sympy.core.mul import _keep_coeff
>>> from sympy.abc import x, y
>>> from sympy import S
>>> _keep_coeff(S.Half, x + 2)
(x + 2)/2
>>> _keep_coeff(S.Half, x + 2, clear=False)
x/2 + 1
>>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
y*(x + 2)/2
>>> _keep_coeff(S(-1), x + y)
-x - y
>>> _keep_coeff(S(-1), x + y, sign=True)
-(x + y)
"""
if not coeff.is_Number:
if factors.is_Number:
factors, coeff = coeff, factors
else:
return coeff*factors
if coeff is S.One:
return factors
elif coeff is S.NegativeOne and not sign:
return -factors
elif factors.is_Add:
if not clear and coeff.is_Rational and coeff.q != 1:
q = S(coeff.q)
for i in factors.args:
c, t = i.as_coeff_Mul()
r = c/q
if r == int(r):
return coeff*factors
return Mul(coeff, factors, evaluate=False)
elif factors.is_Mul:
margs = list(factors.args)
if margs[0].is_Number:
margs[0] *= coeff
if margs[0] == 1:
margs.pop(0)
else:
margs.insert(0, coeff)
return Mul._from_args(margs)
else:
return coeff*factors
def expand_2arg(e):
from sympy.simplify.simplify import bottom_up
def do(e):
if e.is_Mul:
c, r = e.as_coeff_Mul()
if c.is_Number and r.is_Add:
return _unevaluated_Add(*[c*ri for ri in r.args])
return e
return bottom_up(e, do)
from .numbers import Rational
from .power import Pow
from .add import Add, _addsort, _unevaluated_Add
|
23c05785f1bb626f7fefe669f35d98d1d026dc7c03ee2268019067c093051529 | """py.test hacks to support XFAIL/XPASS"""
import sys
import functools
import os
import contextlib
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None)
try:
import pytest
USE_PYTEST = getattr(sys, '_running_pytest', False)
except ImportError:
USE_PYTEST = False
if USE_PYTEST:
raises = pytest.raises
warns = pytest.warns
skip = pytest.skip
XFAIL = pytest.mark.xfail
SKIP = pytest.mark.skip
slow = pytest.mark.slow
nocache_fail = pytest.mark.nocache_fail
from _pytest.outcomes import Failed
else:
# Not using pytest so define the things that would have been imported from
# there.
# _pytest._code.code.ExceptionInfo
class ExceptionInfo:
def __init__(self, value):
self.value = value
def __repr__(self):
return "<ExceptionInfo {!r}>".format(self.value)
def raises(expectedException, code=None):
"""
Tests that ``code`` raises the exception ``expectedException``.
``code`` may be a callable, such as a lambda expression or function
name.
If ``code`` is not given or None, ``raises`` will return a context
manager for use in ``with`` statements; the code to execute then
comes from the scope of the ``with``.
``raises()`` does nothing if the callable raises the expected exception,
otherwise it raises an AssertionError.
Examples
========
>>> from sympy.testing.pytest import raises
>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ZeroDivisionError(...)>
>>> raises(ZeroDivisionError, lambda: 1/2)
Traceback (most recent call last):
...
Failed: DID NOT RAISE
>>> with raises(ZeroDivisionError):
... n = 1/0
>>> with raises(ZeroDivisionError):
... n = 1/2
Traceback (most recent call last):
...
Failed: DID NOT RAISE
Note that you cannot test multiple statements via
``with raises``:
>>> with raises(ZeroDivisionError):
... n = 1/0 # will execute and raise, aborting the ``with``
... n = 9999/0 # never executed
This is just what ``with`` is supposed to do: abort the
contained statement sequence at the first exception and let
the context manager deal with the exception.
To test multiple statements, you'll need a separate ``with``
for each:
>>> with raises(ZeroDivisionError):
... n = 1/0 # will execute and raise
>>> with raises(ZeroDivisionError):
... n = 9999/0 # will also execute and raise
"""
if code is None:
return RaisesContext(expectedException)
elif callable(code):
try:
code()
except expectedException as e:
return ExceptionInfo(e)
raise Failed("DID NOT RAISE")
elif isinstance(code, str):
raise TypeError(
'\'raises(xxx, "code")\' has been phased out; '
'change \'raises(xxx, "expression")\' '
'to \'raises(xxx, lambda: expression)\', '
'\'raises(xxx, "statement")\' '
'to \'with raises(xxx): statement\'')
else:
raise TypeError(
'raises() expects a callable for the 2nd argument.')
class RaisesContext:
def __init__(self, expectedException):
self.expectedException = expectedException
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
raise Failed("DID NOT RAISE")
return issubclass(exc_type, self.expectedException)
class XFail(Exception):
pass
class XPass(Exception):
pass
class Skipped(Exception):
pass
class Failed(Exception): # type: ignore
pass
def XFAIL(func):
def wrapper():
try:
func()
except Exception as e:
message = str(e)
if message != "Timeout":
raise XFail(func.__name__)
else:
raise Skipped("Timeout")
raise XPass(func.__name__)
wrapper = functools.update_wrapper(wrapper, func)
return wrapper
def skip(str):
raise Skipped(str)
def SKIP(reason):
"""Similar to ``skip()``, but this is a decorator. """
def wrapper(func):
def func_wrapper():
raise Skipped(reason)
func_wrapper = functools.update_wrapper(func_wrapper, func)
return func_wrapper
return wrapper
def slow(func):
func._slow = True
def func_wrapper():
func()
func_wrapper = functools.update_wrapper(func_wrapper, func)
func_wrapper.__wrapped__ = func
return func_wrapper
def nocache_fail(func):
"Dummy decorator for marking tests that fail when cache is disabled"
return func
@contextlib.contextmanager
def warns(warningcls, *, match=''):
'''Like raises but tests that warnings are emitted.
>>> from sympy.testing.pytest import warns
>>> import warnings
>>> with warns(UserWarning):
... warnings.warn('deprecated', UserWarning)
>>> with warns(UserWarning):
... pass
Traceback (most recent call last):
...
Failed: DID NOT WARN. No warnings of type UserWarning\
was emitted. The list of emitted warnings is: [].
'''
# Absorbs all warnings in warnrec
with warnings.catch_warnings(record=True) as warnrec:
# Hide all warnings but make sure that our warning is emitted
warnings.simplefilter("ignore")
warnings.filterwarnings("always", match, warningcls)
# Now run the test
yield
# Raise if expected warning not found
if not any(issubclass(w.category, warningcls) for w in warnrec):
msg = ('Failed: DID NOT WARN.'
' No warnings of type %s was emitted.'
' The list of emitted warnings is: %s.'
) % (warningcls, [w.message for w in warnrec])
raise Failed(msg)
def _both_exp_pow(func):
"""
Decorator used to run the test twice: the first time `e^x` is represented
as ``Pow(E, x)``, the second time as ``exp(x)`` (exponential object is not
a power).
This is a temporary trick helping to manage the elimination of the class
``exp`` in favor of a replacement by ``Pow(E, ...)``.
"""
from sympy.core.parameters import _exp_is_pow
def func_wrap():
with _exp_is_pow(True):
func()
with _exp_is_pow(False):
func()
wrapper = functools.update_wrapper(func_wrap, func)
return wrapper
@contextlib.contextmanager
def warns_deprecated_sympy():
'''Shorthand for ``warns(SymPyDeprecationWarning)``
This is the recommended way to test that ``SymPyDeprecationWarning`` is
emitted for deprecated features in SymPy. To test for other warnings use
``warns``. To suppress warnings without asserting that they are emitted
use ``ignore_warnings``.
>>> from sympy.testing.pytest import warns_deprecated_sympy
>>> from sympy.utilities.exceptions import SymPyDeprecationWarning
>>> with warns_deprecated_sympy():
... SymPyDeprecationWarning("Don't use", feature="old thing",
... deprecated_since_version="1.0", issue=123).warn()
>>> with warns_deprecated_sympy():
... pass
Traceback (most recent call last):
...
Failed: DID NOT WARN. No warnings of type \
SymPyDeprecationWarning was emitted. The list of emitted warnings is: [].
'''
with warns(SymPyDeprecationWarning):
yield
@contextlib.contextmanager
def ignore_warnings(warningcls):
'''Context manager to suppress warnings during tests.
This function is useful for suppressing warnings during tests. The warns
function should be used to assert that a warning is raised. The
ignore_warnings function is useful in situation when the warning is not
guaranteed to be raised (e.g. on importing a module) or if the warning
comes from third-party code.
When the warning is coming (reliably) from SymPy the warns function should
be preferred to ignore_warnings.
>>> from sympy.testing.pytest import ignore_warnings
>>> import warnings
Here's a warning:
>>> with warnings.catch_warnings(): # reset warnings in doctest
... warnings.simplefilter('error')
... warnings.warn('deprecated', UserWarning)
Traceback (most recent call last):
...
UserWarning: deprecated
Let's suppress it with ignore_warnings:
>>> with warnings.catch_warnings(): # reset warnings in doctest
... warnings.simplefilter('error')
... with ignore_warnings(UserWarning):
... warnings.warn('deprecated', UserWarning)
(No warning emitted)
'''
# Absorbs all warnings in warnrec
with warnings.catch_warnings(record=True) as warnrec:
# Make sure our warning doesn't get filtered
warnings.simplefilter("always", warningcls)
# Now run the test
yield
# Reissue any warnings that we aren't testing for
for w in warnrec:
if not issubclass(w.category, warningcls):
warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
|
54c35709149aca28104fa6b772f7f933f33ec1d57e2928a5fc96c098772e5107 | """A module to manipulate symbolic objects with indices including tensors
"""
from .indexed import IndexedBase, Idx, Indexed
from .index_methods import get_contraction_structure, get_indices
from .functions import shape
from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray,
MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct,
tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array,
DenseNDimArray, SparseNDimArray,)
__all__ = [
'IndexedBase', 'Idx', 'Indexed',
'get_contraction_structure', 'get_indices',
'shape',
'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims',
'Array', 'DenseNDimArray', 'SparseNDimArray',
]
|
114d63d29c42aa84f2cf9881eaa11f4e688cc56eb17ca028ba9649e08c7a4c8b | from collections.abc import Iterable
from functools import singledispatch
from sympy import Expr, S, Mul, sympify
from sympy.core.parameters import global_parameters
class TensorProduct(Expr):
"""
Generic class for tensor products.
"""
is_number = False
def __new__(cls, *args, **kwargs):
from sympy.tensor.array import NDimArray, tensorproduct, Array
from sympy import MatrixBase, MatrixExpr
from sympy.strategies import flatten
args = [sympify(arg) for arg in args]
evaluate = kwargs.get("evaluate", global_parameters.evaluate)
if not evaluate:
obj = Expr.__new__(cls, *args)
return obj
arrays = []
other = []
scalar = S.One
for arg in args:
if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
arrays.append(Array(arg))
elif isinstance(arg, (MatrixExpr,)):
other.append(arg)
else:
scalar *= arg
coeff = scalar*tensorproduct(*arrays)
if len(other) == 0:
return coeff
if coeff != 1:
newargs = [coeff] + other
else:
newargs = other
obj = Expr.__new__(cls, *newargs, **kwargs)
return flatten(obj)
def rank(self):
return len(self.shape)
def _get_args_shapes(self):
from sympy import Array
return [i.shape if hasattr(i, "shape") else Array(i).shape for i in self.args]
@property
def shape(self):
shape_list = self._get_args_shapes()
return sum(shape_list, ())
def __getitem__(self, index):
index = iter(index)
return Mul.fromiter(
arg.__getitem__(tuple(next(index) for i in shp))
for arg, shp in zip(self.args, self._get_args_shapes())
)
@singledispatch
def shape(expr):
"""
Return the shape of the *expr* as a tuple. *expr* should represent
suitable object such as matrix or array.
Parameters
==========
expr : SymPy object having ``MatrixKind`` or ``ArrayKind``.
Raises
======
NoShapeError : Raised when object with wrong kind is passed.
Examples
========
This function returns the shape of any object representing matrix or array.
>>> from sympy import shape, Array, Matrix, Integral
>>> from sympy.abc import x
>>> A = Array([1, 2])
>>> shape(A)
(2,)
>>> shape(Integral(A, x))
(2,)
>>> M = Matrix([1, 2])
>>> shape(M)
(2, 1)
>>> shape(Integral(M, x))
(2, 1)
You can support new type by dispatching.
>>> from sympy import Expr
>>> class NewExpr(Expr):
... pass
>>> @shape.register(NewExpr)
... def _(expr):
... return shape(expr.args[0])
>>> shape(NewExpr(M))
(2, 1)
If unsuitable expression is passed, ``NoShapeError()`` will be raised.
>>> shape(Integral(x, x))
Traceback (most recent call last):
...
sympy.tensor.functions.NoShapeError: shape() called on non-array object: Integral(x, x)
Notes
=====
Array-like classes (such as ``Matrix`` or ``NDimArray``) has ``shape``
property which returns its shape, but it cannot be used for non-array
classes containing array. This function returns the shape of any
registered object representing array.
"""
if hasattr(expr, "shape"):
return expr.shape
raise NoShapeError(
"%s does not have shape, or its type is not registered to shape()." % expr)
class NoShapeError(Exception):
"""
Raised when ``shape()`` is called on non-array object.
This error can be imported from ``sympy.tensor.functions``.
Examples
========
>>> from sympy import shape
>>> from sympy.abc import x
>>> shape(x)
Traceback (most recent call last):
...
sympy.tensor.functions.NoShapeError: shape() called on non-array object: x
"""
pass
|
58a9771e3bb6a906aae1fdbca40bfba85277c25d7a3dd5f1c02d0de8888ce5e6 | """
Boolean algebra module for SymPy
"""
from collections import defaultdict
from itertools import chain, combinations, product
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.compatibility import ordered, as_int
from sympy.core.decorators import sympify_method_args, sympify_return
from sympy.core.function import Application, Derivative
from sympy.core.numbers import Number
from sympy.core.operations import LatticeOp
from sympy.core.singleton import Singleton, S
from sympy.core.sympify import converter, _sympify, sympify
from sympy.core.kind import BooleanKind
from sympy.utilities.iterables import sift, ibin
from sympy.utilities.misc import filldedent
def as_Boolean(e):
"""Like bool, return the Boolean value of an expression, e,
which can be any instance of Boolean or bool.
Examples
========
>>> from sympy import true, false, nan
>>> from sympy.logic.boolalg import as_Boolean
>>> from sympy.abc import x
>>> as_Boolean(0) is false
True
>>> as_Boolean(1) is true
True
>>> as_Boolean(x)
x
>>> as_Boolean(2)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `2`.
>>> as_Boolean(nan)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `nan`.
"""
from sympy.core.symbol import Symbol
if e == True:
return S.true
if e == False:
return S.false
if isinstance(e, Symbol):
z = e.is_zero
if z is None:
return e
return S.false if z else S.true
if isinstance(e, Boolean):
return e
raise TypeError('expecting bool or Boolean, not `%s`.' % e)
@sympify_method_args
class Boolean(Basic):
"""A boolean object is an object for which logic operations make sense."""
__slots__ = ()
kind = BooleanKind
@sympify_return([('other', 'Boolean')], NotImplemented)
def __and__(self, other):
return And(self, other)
__rand__ = __and__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __or__(self, other):
return Or(self, other)
__ror__ = __or__
def __invert__(self):
"""Overloading for ~"""
return Not(self)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __rshift__(self, other):
return Implies(self, other)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __lshift__(self, other):
return Implies(other, self)
__rrshift__ = __lshift__
__rlshift__ = __rshift__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __xor__(self, other):
return Xor(self, other)
__rxor__ = __xor__
def equals(self, other):
"""
Returns True if the given formulas have the same truth table.
For two formulas to be equal they must have the same literals.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.boolalg import And, Or, Not
>>> (A >> B).equals(~B >> ~A)
True
>>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C)))
False
>>> Not(And(A, Not(A))).equals(Or(B, Not(B)))
False
"""
from sympy.logic.inference import satisfiable
from sympy.core.relational import Relational
if self.has(Relational) or other.has(Relational):
raise NotImplementedError('handling of relationals')
return self.atoms() == other.atoms() and \
not satisfiable(Not(Equivalent(self, other)))
def to_nnf(self, simplify=True):
# override where necessary
return self
def as_set(self):
"""
Rewrites Boolean expression in terms of real sets.
Examples
========
>>> from sympy import Symbol, Eq, Or, And
>>> x = Symbol('x', real=True)
>>> Eq(x, 0).as_set()
FiniteSet(0)
>>> (x > 0).as_set()
Interval.open(0, oo)
>>> And(-2 < x, x < 2).as_set()
Interval.open(-2, 2)
>>> Or(x < -2, 2 < x).as_set()
Union(Interval.open(-oo, -2), Interval.open(2, oo))
"""
from sympy.calculus.util import periodicity
from sympy.core.relational import Relational
free = self.free_symbols
if len(free) == 1:
x = free.pop()
reps = {}
for r in self.atoms(Relational):
if periodicity(r, x) not in (0, None):
s = r._eval_as_set()
if s in (S.EmptySet, S.UniversalSet, S.Reals):
reps[r] = s.as_relational(x)
continue
raise NotImplementedError(filldedent('''
as_set is not implemented for relationals
with periodic solutions
'''))
return self.subs(reps)._eval_as_set()
else:
raise NotImplementedError("Sorry, as_set has not yet been"
" implemented for multivariate"
" expressions")
@property
def binary_symbols(self):
from sympy.core.relational import Eq, Ne
return set().union(*[i.binary_symbols for i in self.args
if i.is_Boolean or i.is_Symbol
or isinstance(i, (Eq, Ne))])
def _eval_refine(self, assumptions):
from sympy.assumptions import ask
return ask(self, assumptions)
class BooleanAtom(Boolean):
"""
Base class of BooleanTrue and BooleanFalse.
"""
is_Boolean = True
is_Atom = True
_op_priority = 11 # higher than Expr
def simplify(self, *a, **kw):
return self
def expand(self, *a, **kw):
return self
@property
def canonical(self):
return self
def _noop(self, other=None):
raise TypeError('BooleanAtom not allowed in this context.')
__add__ = _noop
__radd__ = _noop
__sub__ = _noop
__rsub__ = _noop
__mul__ = _noop
__rmul__ = _noop
__pow__ = _noop
__rpow__ = _noop
__truediv__ = _noop
__rtruediv__ = _noop
__mod__ = _noop
__rmod__ = _noop
_eval_power = _noop
# /// drop when Py2 is no longer supported
def __lt__(self, other):
from sympy.utilities.misc import filldedent
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__gt__ = __lt__
__ge__ = __lt__
# \\\
class BooleanTrue(BooleanAtom, metaclass=Singleton):
"""
SymPy version of True, a singleton that can be accessed via S.true.
This is the SymPy version of True, for use in the logic module. The
primary advantage of using true instead of True is that shorthand boolean
operations like ~ and >> will work as expected on this class, whereas with
True they act bitwise on 1. Functions in the logic module will return this
class when they evaluate to true.
Notes
=====
There is liable to be some confusion as to when ``True`` should
be used and when ``S.true`` should be used in various contexts
throughout SymPy. An important thing to remember is that
``sympify(True)`` returns ``S.true``. This means that for the most
part, you can just use ``True`` and it will automatically be converted
to ``S.true`` when necessary, similar to how you can generally use 1
instead of ``S.One``.
The rule of thumb is:
"If the boolean in question can be replaced by an arbitrary symbolic
``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``.
Otherwise, use ``True``"
In other words, use ``S.true`` only on those contexts where the
boolean is being used as a symbolic representation of truth.
For example, if the object ends up in the ``.args`` of any expression,
then it must necessarily be ``S.true`` instead of ``True``, as
elements of ``.args`` must be ``Basic``. On the other hand,
``==`` is not a symbolic operation in SymPy, since it always returns
``True`` or ``False``, and does so in terms of structural equality
rather than mathematical, so it should return ``True``. The assumptions
system should use ``True`` and ``False``. Aside from not satisfying
the above rule of thumb, the assumptions system uses a three-valued logic
(``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false``
represent a two-valued logic. When in doubt, use ``True``.
"``S.true == True is True``."
While "``S.true is True``" is ``False``, "``S.true == True``"
is ``True``, so if there is any doubt over whether a function or
expression will return ``S.true`` or ``True``, just use ``==``
instead of ``is`` to do the comparison, and it will work in either
case. Finally, for boolean flags, it's better to just use ``if x``
instead of ``if x is True``. To quote PEP 8:
Don't compare boolean values to ``True`` or ``False``
using ``==``.
* Yes: ``if greeting:``
* No: ``if greeting == True:``
* Worse: ``if greeting is True:``
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(True)
True
>>> _ is True, _ is true
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanFalse
"""
def __bool__(self):
return True
def __hash__(self):
return hash(True)
@property
def negated(self):
return S.false
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import true
>>> true.as_set()
UniversalSet
"""
return S.UniversalSet
class BooleanFalse(BooleanAtom, metaclass=Singleton):
"""
SymPy version of False, a singleton that can be accessed via S.false.
This is the SymPy version of False, for use in the logic module. The
primary advantage of using false instead of False is that shorthand boolean
operations like ~ and >> will work as expected on this class, whereas with
False they act bitwise on 0. Functions in the logic module will return this
class when they evaluate to false.
Notes
======
See note in :py:class`sympy.logic.boolalg.BooleanTrue`
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(False)
False
>>> _ is False, _ is false
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for false but a
bitwise result for False
>>> ~false, ~False
(True, -1)
>>> false >> false, False >> False
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanTrue
"""
def __bool__(self):
return False
def __hash__(self):
return hash(False)
@property
def negated(self):
return S.true
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import false
>>> false.as_set()
EmptySet
"""
return S.EmptySet
true = BooleanTrue()
false = BooleanFalse()
# We want S.true and S.false to work, rather than S.BooleanTrue and
# S.BooleanFalse, but making the class and instance names the same causes some
# major issues (like the inability to import the class directly from this
# file).
S.true = true
S.false = false
converter[bool] = lambda x: S.true if x else S.false
class BooleanFunction(Application, Boolean):
"""Boolean function is a function that lives in a boolean space
It is used as base class for And, Or, Not, etc.
"""
is_Boolean = True
def _eval_simplify(self, **kwargs):
rv = self.func(*[
a._eval_simplify(**kwargs) for a in self.args])
return simplify_logic(rv)
def simplify(self, **kwargs):
from sympy.simplify.simplify import simplify
return simplify(self, **kwargs)
def __lt__(self, other):
from sympy.utilities.misc import filldedent
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__ge__ = __lt__
__gt__ = __lt__
@classmethod
def binary_check_and_simplify(self, *args):
from sympy.core.relational import Relational, Eq, Ne
args = [as_Boolean(i) for i in args]
bin = set().union(*[i.binary_symbols for i in args])
rel = set().union(*[i.atoms(Relational) for i in args])
reps = {}
for x in bin:
for r in rel:
if x in bin and x in r.free_symbols:
if isinstance(r, (Eq, Ne)):
if not (
S.true in r.args or
S.false in r.args):
reps[r] = S.false
else:
raise TypeError(filldedent('''
Incompatible use of binary symbol `%s` as a
real variable in `%s`
''' % (x, r)))
return [i.subs(reps) for i in args]
def to_nnf(self, simplify=True):
return self._to_nnf(*self.args, simplify=simplify)
def to_anf(self, deep=True):
return self._to_anf(*self.args, deep=deep)
@classmethod
def _to_nnf(cls, *args, **kwargs):
simplify = kwargs.get('simplify', True)
argset = set()
for arg in args:
if not is_literal(arg):
arg = arg.to_nnf(simplify)
if simplify:
if isinstance(arg, cls):
arg = arg.args
else:
arg = (arg,)
for a in arg:
if Not(a) in argset:
return cls.zero
argset.add(a)
else:
argset.add(arg)
return cls(*argset)
@classmethod
def _to_anf(cls, *args, **kwargs):
deep = kwargs.get('deep', True)
argset = set()
for arg in args:
if deep:
if not is_literal(arg) or isinstance(arg, Not):
arg = arg.to_anf(deep=deep)
argset.add(arg)
else:
argset.add(arg)
return cls(*argset, remove_true=False)
# the diff method below is copied from Expr class
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return Derivative(self, *symbols, **assumptions)
def _eval_derivative(self, x):
from sympy.core.relational import Eq
from sympy.functions.elementary.piecewise import Piecewise
if x in self.binary_symbols:
return Piecewise(
(0, Eq(self.subs(x, 0), self.subs(x, 1))),
(1, True))
elif x in self.free_symbols:
# not implemented, see https://www.encyclopediaofmath.org/
# index.php/Boolean_differential_calculus
pass
else:
return S.Zero
def _apply_patternbased_simplification(self, rv, patterns, measure,
dominatingvalue,
replacementvalue=None):
"""
Replace patterns of Relational
Parameters
==========
rv : Expr
Boolean expression
patterns : tuple
Tuple of tuples, with (pattern to simplify, simplified pattern)
measure : function
Simplification measure
dominatingvalue : boolean or None
The dominating value for the function of consideration.
For example, for And S.false is dominating. As soon as one
expression is S.false in And, the whole expression is S.false.
replacementvalue : boolean or None, optional
The resulting value for the whole expression if one argument
evaluates to dominatingvalue.
For example, for Nand S.false is dominating, but in this case
the resulting value is S.true. Default is None. If replacementvalue
is None and dominatingvalue is not None,
replacementvalue = dominatingvalue
"""
from sympy.core.relational import Relational, _canonical
if replacementvalue is None and dominatingvalue is not None:
replacementvalue = dominatingvalue
# Use replacement patterns for Relationals
changed = True
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if len(Rel) <= 1:
return rv
Rel, nonRealRel = sift(Rel, lambda i: all(s.is_real is not False
for s in i.free_symbols),
binary=True)
Rel = [i.canonical for i in Rel]
while changed and len(Rel) >= 2:
changed = False
# Sort based on ordered
Rel = list(ordered(Rel))
# Create a list of possible replacements
results = []
# Try all combinations
for ((i, pi), (j, pj)) in combinations(enumerate(Rel), 2):
for k, (pattern, simp) in enumerate(patterns):
res = []
# use SymPy matching
oldexpr = rv.func(pi, pj)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing first relational
# This and the rest should not be required with a better
# canonical
oldexpr = rv.func(pi.reversed, pj)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing second relational
oldexpr = rv.func(pi, pj.reversed)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing both relationals
oldexpr = rv.func(pi.reversed, pj.reversed)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
if res:
for tmpres, oldexpr in res:
# we have a matching, compute replacement
np = simp.subs(tmpres)
if np == dominatingvalue:
# if dominatingvalue, the whole expression
# will be replacementvalue
return replacementvalue
# add replacement
if not isinstance(np, ITE):
# We only want to use ITE replacements if
# they simplify to a relational
costsaving = measure(oldexpr) - measure(np)
if costsaving > 0:
results.append((costsaving, (i, j, np)))
if results:
# Sort results based on complexity
results = list(reversed(sorted(results,
key=lambda pair: pair[0])))
# Replace the one providing most simplification
cost, replacement = results[0]
i, j, newrel = replacement
# Remove the old relationals
del Rel[j]
del Rel[i]
if dominatingvalue is None or newrel != ~dominatingvalue:
# Insert the new one (no need to insert a value that will
# not affect the result)
Rel.append(newrel)
# We did change something so try again
changed = True
rv = rv.func(*([_canonical(i) for i in ordered(Rel)]
+ nonRel + nonRealRel))
return rv
class And(LatticeOp, BooleanFunction):
"""
Logical AND function.
It evaluates its arguments in order, giving False immediately
if any of them are False, and True if they are all True.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.logic.boolalg import And
>>> x & y
x & y
Notes
=====
The ``&`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
and. Hence, ``And(a, b)`` and ``a & b`` will return different things if
``a`` and ``b`` are integers.
>>> And(x, y).subs(x, 1)
y
"""
zero = false
identity = true
nargs = None
@classmethod
def _new_args_filter(cls, args):
args = BooleanFunction.binary_check_and_simplify(*args)
args = LatticeOp._new_args_filter(args, And)
newargs = []
rel = set()
for x in ordered(args):
if x.is_Relational:
c = x.canonical
if c in rel:
continue
elif c.negated.canonical in rel:
return [S.false]
else:
rel.add(c)
newargs.append(x)
return newargs
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == False:
return S.false
elif i != True:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
return self.func(*args)
def _eval_simplify(self, **kwargs):
from sympy.core.relational import Equality, Relational
from sympy.solvers.solveset import linear_coeffs
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, And):
return rv
# simplify args that are equalities involving
# symbols so x == 0 & x == y -> x==0 & y == 0
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if not Rel:
return rv
eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True)
if not eqs:
return rv
measure, ratio = kwargs['measure'], kwargs['ratio']
reps = {}
sifted = {}
if eqs:
# group by length of free symbols
sifted = sift(ordered([
(i.free_symbols, i) for i in eqs]),
lambda x: len(x[0]))
eqs = []
while 1 in sifted:
for free, e in sifted.pop(1):
x = free.pop()
if e.lhs != x or x in e.rhs.free_symbols:
try:
m, b = linear_coeffs(
e.rewrite(Add, evaluate=False), x)
enew = e.func(x, -b/m)
if measure(enew) <= ratio*measure(e):
e = enew
else:
eqs.append(e)
continue
except ValueError:
pass
if x in reps:
eqs.append(e.func(e.rhs, reps[x]))
else:
reps[x] = e.rhs
eqs.append(e)
resifted = defaultdict(list)
for k in sifted:
for f, e in sifted[k]:
e = e.subs(reps)
f = e.free_symbols
resifted[len(f)].append((f, e))
sifted = resifted
for k in sifted:
eqs.extend([e for f, e in sifted[k]])
other = [ei.subs(reps) for ei in other]
rv = rv.func(*([i.canonical for i in (eqs + other)] + nonRel))
patterns = simplify_patterns_and()
return self._apply_patternbased_simplification(rv, patterns,
measure, False)
def _eval_as_set(self):
from sympy.sets.sets import Intersection
return Intersection(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nor(self, *args, **kwargs):
return Nor(*[Not(arg) for arg in self.args])
def to_anf(self, deep=True):
if deep:
result = And._to_anf(*self.args, deep=deep)
return distribute_xor_over_and(result)
return self
class Or(LatticeOp, BooleanFunction):
"""
Logical OR function
It evaluates its arguments in order, giving True immediately
if any of them are True, and False if they are all False.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.logic.boolalg import Or
>>> x | y
x | y
Notes
=====
The ``|`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if
``a`` and ``b`` are integers.
>>> Or(x, y).subs(x, 0)
y
"""
zero = true
identity = false
@classmethod
def _new_args_filter(cls, args):
newargs = []
rel = []
args = BooleanFunction.binary_check_and_simplify(*args)
for x in args:
if x.is_Relational:
c = x.canonical
if c in rel:
continue
nc = c.negated.canonical
if any(r == nc for r in rel):
return [S.true]
rel.append(c)
newargs.append(x)
return LatticeOp._new_args_filter(newargs, Or)
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == True:
return S.true
elif i != False:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
return self.func(*args)
def _eval_as_set(self):
from sympy.sets.sets import Union
return Union(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nand(self, *args, **kwargs):
return Nand(*[Not(arg) for arg in self.args])
def _eval_simplify(self, **kwargs):
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, Or):
return rv
patterns = simplify_patterns_or()
return self._apply_patternbased_simplification(rv, patterns,
kwargs['measure'], S.true)
def to_anf(self, deep=True):
args = range(1, len(self.args) + 1)
args = (combinations(self.args, j) for j in args)
args = chain.from_iterable(args) # powerset
args = (And(*arg) for arg in args)
args = map(lambda x: to_anf(x, deep=deep) if deep else x, args)
return Xor(*list(args), remove_true=False)
class Not(BooleanFunction):
"""
Logical Not function (negation)
Returns True if the statement is False
Returns False if the statement is True
Examples
========
>>> from sympy.logic.boolalg import Not, And, Or
>>> from sympy.abc import x, A, B
>>> Not(True)
False
>>> Not(False)
True
>>> Not(And(True, False))
True
>>> Not(Or(True, False))
False
>>> Not(And(And(True, x), Or(x, False)))
~x
>>> ~x
~x
>>> Not(And(Or(A, B), Or(~A, ~B)))
~((A | B) & (~A | ~B))
Notes
=====
- The ``~`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is
an integer. Furthermore, since bools in Python subclass from ``int``,
``~True`` is the same as ``~1`` which is ``-2``, which has a boolean
value of True. To avoid this issue, use the SymPy boolean types
``true`` and ``false``.
>>> from sympy import true
>>> ~True
-2
>>> ~true
False
"""
is_Not = True
@classmethod
def eval(cls, arg):
from sympy import (
Equality, GreaterThan, LessThan,
StrictGreaterThan, StrictLessThan, Unequality)
if isinstance(arg, Number) or arg in (True, False):
return false if arg else true
if arg.is_Not:
return arg.args[0]
# Simplify Relational objects.
if isinstance(arg, Equality):
return Unequality(*arg.args)
if isinstance(arg, Unequality):
return Equality(*arg.args)
if isinstance(arg, StrictLessThan):
return GreaterThan(*arg.args)
if isinstance(arg, StrictGreaterThan):
return LessThan(*arg.args)
if isinstance(arg, LessThan):
return StrictGreaterThan(*arg.args)
if isinstance(arg, GreaterThan):
return StrictLessThan(*arg.args)
def _eval_as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import Not, Symbol
>>> x = Symbol('x')
>>> Not(x > 0).as_set()
Interval(-oo, 0)
"""
return self.args[0].as_set().complement(S.Reals)
def to_nnf(self, simplify=True):
if is_literal(self):
return self
expr = self.args[0]
func, args = expr.func, expr.args
if func == And:
return Or._to_nnf(*[~arg for arg in args], simplify=simplify)
if func == Or:
return And._to_nnf(*[~arg for arg in args], simplify=simplify)
if func == Implies:
a, b = args
return And._to_nnf(a, ~b, simplify=simplify)
if func == Equivalent:
return And._to_nnf(Or(*args), Or(*[~arg for arg in args]),
simplify=simplify)
if func == Xor:
result = []
for i in range(1, len(args)+1, 2):
for neg in combinations(args, i):
clause = [~s if s in neg else s for s in args]
result.append(Or(*clause))
return And._to_nnf(*result, simplify=simplify)
if func == ITE:
a, b, c = args
return And._to_nnf(Or(a, ~c), Or(~a, ~b), simplify=simplify)
raise ValueError("Illegal operator %s in expression" % func)
def to_anf(self, deep=True):
return Xor._to_anf(true, self.args[0], deep=deep)
class Xor(BooleanFunction):
"""
Logical XOR (exclusive OR) function.
Returns True if an odd number of the arguments are True and the rest are
False.
Returns False if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xor(True, False)
True
>>> Xor(True, True)
False
>>> Xor(True, False, True, True, False)
True
>>> Xor(True, False, True, False)
False
>>> x ^ y
x ^ y
Notes
=====
The ``^`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise xor. In
particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and
``b`` are integers.
>>> Xor(x, y).subs(y, 0)
x
"""
def __new__(cls, *args, remove_true=True, **kwargs):
argset = set()
obj = super().__new__(cls, *args, **kwargs)
for arg in obj._args:
if isinstance(arg, Number) or arg in (True, False):
if arg:
arg = true
else:
continue
if isinstance(arg, Xor):
for a in arg.args:
argset.remove(a) if a in argset else argset.add(a)
elif arg in argset:
argset.remove(arg)
else:
argset.add(arg)
rel = [(r, r.canonical, r.negated.canonical)
for r in argset if r.is_Relational]
odd = False # is number of complimentary pairs odd? start 0 -> False
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
odd = ~odd
break
elif cj == c:
break
else:
continue
remove.append((r, rj))
if odd:
argset.remove(true) if true in argset else argset.add(true)
for a, b in remove:
argset.remove(a)
argset.remove(b)
if len(argset) == 0:
return false
elif len(argset) == 1:
return argset.pop()
elif True in argset and remove_true:
argset.remove(True)
return Not(Xor(*argset))
else:
obj._args = tuple(ordered(argset))
obj._argset = frozenset(argset)
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for i in range(0, len(self.args)+1, 2):
for neg in combinations(self.args, i):
clause = [~s if s in neg else s for s in self.args]
args.append(Or(*clause))
return And._to_nnf(*args, simplify=simplify)
def _eval_rewrite_as_Or(self, *args, **kwargs):
a = self.args
return Or(*[_convert_to_varsSOP(x, self.args)
for x in _get_odd_parity_terms(len(a))])
def _eval_rewrite_as_And(self, *args, **kwargs):
a = self.args
return And(*[_convert_to_varsPOS(x, self.args)
for x in _get_even_parity_terms(len(a))])
def _eval_simplify(self, **kwargs):
# as standard simplify uses simplify_logic which writes things as
# And and Or, we only simplify the partial expressions before using
# patterns
rv = self.func(*[a._eval_simplify(**kwargs) for a in self.args])
if not isinstance(rv, Xor): # This shouldn't really happen here
return rv
patterns = simplify_patterns_xor()
return self._apply_patternbased_simplification(rv, patterns,
kwargs['measure'], None)
class Nand(BooleanFunction):
"""
Logical NAND function.
It evaluates its arguments in order, giving True immediately if any
of them are False, and False if they are all True.
Returns True if any of the arguments are False
Returns False if all arguments are True
Examples
========
>>> from sympy.logic.boolalg import Nand
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nand(False, True)
True
>>> Nand(True, True)
False
>>> Nand(x, y)
~(x & y)
"""
@classmethod
def eval(cls, *args):
return Not(And(*args))
class Nor(BooleanFunction):
"""
Logical NOR function.
It evaluates its arguments in order, giving False immediately if any
of them are True, and True if they are all False.
Returns False if any argument is True
Returns True if all arguments are False
Examples
========
>>> from sympy.logic.boolalg import Nor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nor(True, False)
False
>>> Nor(True, True)
False
>>> Nor(False, True)
False
>>> Nor(False, False)
True
>>> Nor(x, y)
~(x | y)
"""
@classmethod
def eval(cls, *args):
return Not(Or(*args))
class Xnor(BooleanFunction):
"""
Logical XNOR function.
Returns False if an odd number of the arguments are True and the rest are
False.
Returns True if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xnor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xnor(True, False)
False
>>> Xnor(True, True)
True
>>> Xnor(True, False, True, True, False)
False
>>> Xnor(True, False, True, False)
True
"""
@classmethod
def eval(cls, *args):
return Not(Xor(*args))
class Implies(BooleanFunction):
"""
Logical implication.
A implies B is equivalent to !A v B
Accepts two Boolean arguments; A and B.
Returns False if A is True and B is False
Returns True otherwise.
Examples
========
>>> from sympy.logic.boolalg import Implies
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Implies(True, False)
False
>>> Implies(False, False)
True
>>> Implies(True, True)
True
>>> Implies(False, True)
True
>>> x >> y
Implies(x, y)
>>> y << x
Implies(x, y)
Notes
=====
The ``>>`` and ``<<`` operators are provided as a convenience, but note
that their use here is different from their normal use in Python, which is
bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different
things if ``a`` and ``b`` are integers. In particular, since Python
considers ``True`` and ``False`` to be integers, ``True >> True`` will be
the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To
avoid this issue, use the SymPy objects ``true`` and ``false``.
>>> from sympy import true, false
>>> True >> False
1
>>> true >> false
False
"""
@classmethod
def eval(cls, *args):
try:
newargs = []
for x in args:
if isinstance(x, Number) or x in (0, 1):
newargs.append(True if x else False)
else:
newargs.append(x)
A, B = newargs
except ValueError:
raise ValueError(
"%d operand(s) used for an Implies "
"(pairs are required): %s" % (len(args), str(args)))
if A == True or A == False or B == True or B == False:
return Or(Not(A), B)
elif A == B:
return S.true
elif A.is_Relational and B.is_Relational:
if A.canonical == B.canonical:
return S.true
if A.negated.canonical == B.canonical:
return B
else:
return Basic.__new__(cls, *args)
def to_nnf(self, simplify=True):
a, b = self.args
return Or._to_nnf(~a, b, simplify=simplify)
def to_anf(self, deep=True):
a, b = self.args
return Xor._to_anf(true, a, And(a, b), deep=deep)
class Equivalent(BooleanFunction):
"""
Equivalence relation.
Equivalent(A, B) is True iff A and B are both True or both False
Returns True if all of the arguments are logically equivalent.
Returns False otherwise.
Examples
========
>>> from sympy.logic.boolalg import Equivalent, And
>>> from sympy.abc import x
>>> Equivalent(False, False, False)
True
>>> Equivalent(True, False, False)
False
>>> Equivalent(x, And(x, True))
True
"""
def __new__(cls, *args, **options):
from sympy.core.relational import Relational
args = [_sympify(arg) for arg in args]
argset = set(args)
for x in args:
if isinstance(x, Number) or x in [True, False]: # Includes 0, 1
argset.discard(x)
argset.add(True if x else False)
rel = []
for r in argset:
if isinstance(r, Relational):
rel.append((r, r.canonical, r.negated.canonical))
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
return false
elif cj == c:
remove.append((r, rj))
break
for a, b in remove:
argset.remove(a)
argset.remove(b)
argset.add(True)
if len(argset) <= 1:
return true
if True in argset:
argset.discard(True)
return And(*argset)
if False in argset:
argset.discard(False)
return And(*[~arg for arg in argset])
_args = frozenset(argset)
obj = super().__new__(cls, _args)
obj._argset = _args
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for a, b in zip(self.args, self.args[1:]):
args.append(Or(~a, b))
args.append(Or(~self.args[-1], self.args[0]))
return And._to_nnf(*args, simplify=simplify)
def to_anf(self, deep=True):
a = And(*self.args)
b = And(*[to_anf(Not(arg), deep=False) for arg in self.args])
b = distribute_xor_over_and(b)
return Xor._to_anf(a, b, deep=deep)
class ITE(BooleanFunction):
"""
If then else clause.
ITE(A, B, C) evaluates and returns the result of B if A is true
else it returns the result of C. All args must be Booleans.
Examples
========
>>> from sympy.logic.boolalg import ITE, And, Xor, Or
>>> from sympy.abc import x, y, z
>>> ITE(True, False, True)
False
>>> ITE(Or(True, False), And(True, True), Xor(True, True))
True
>>> ITE(x, y, z)
ITE(x, y, z)
>>> ITE(True, x, y)
x
>>> ITE(False, x, y)
y
>>> ITE(x, y, y)
y
Trying to use non-Boolean args will generate a TypeError:
>>> ITE(True, [], ())
Traceback (most recent call last):
...
TypeError: expecting bool, Boolean or ITE, not `[]`
"""
def __new__(cls, *args, **kwargs):
from sympy.core.relational import Eq, Ne
if len(args) != 3:
raise ValueError('expecting exactly 3 args')
a, b, c = args
# check use of binary symbols
if isinstance(a, (Eq, Ne)):
# in this context, we can evaluate the Eq/Ne
# if one arg is a binary symbol and the other
# is true/false
b, c = map(as_Boolean, (b, c))
bin = set().union(*[i.binary_symbols for i in (b, c)])
if len(set(a.args) - bin) == 1:
# one arg is a binary_symbols
_a = a
if a.lhs is S.true:
a = a.rhs
elif a.rhs is S.true:
a = a.lhs
elif a.lhs is S.false:
a = ~a.rhs
elif a.rhs is S.false:
a = ~a.lhs
else:
# binary can only equal True or False
a = S.false
if isinstance(_a, Ne):
a = ~a
else:
a, b, c = BooleanFunction.binary_check_and_simplify(
a, b, c)
rv = None
if kwargs.get('evaluate', True):
rv = cls.eval(a, b, c)
if rv is None:
rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False)
return rv
@classmethod
def eval(cls, *args):
from sympy.core.relational import Eq, Ne
# do the args give a singular result?
a, b, c = args
if isinstance(a, (Ne, Eq)):
_a = a
if S.true in a.args:
a = a.lhs if a.rhs is S.true else a.rhs
elif S.false in a.args:
a = ~a.lhs if a.rhs is S.false else ~a.rhs
else:
_a = None
if _a is not None and isinstance(_a, Ne):
a = ~a
if a is S.true:
return b
if a is S.false:
return c
if b == c:
return b
else:
# or maybe the results allow the answer to be expressed
# in terms of the condition
if b is S.true and c is S.false:
return a
if b is S.false and c is S.true:
return Not(a)
if [a, b, c] != args:
return cls(a, b, c, evaluate=False)
def to_nnf(self, simplify=True):
a, b, c = self.args
return And._to_nnf(Or(~a, b), Or(a, c), simplify=simplify)
def _eval_as_set(self):
return self.to_nnf().as_set()
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
from sympy.functions import Piecewise
return Piecewise((args[1], args[0]), (args[2], True))
# end class definitions. Some useful methods
def conjuncts(expr):
"""Return a list of the conjuncts in the expr s.
Examples
========
>>> from sympy.logic.boolalg import conjuncts
>>> from sympy.abc import A, B
>>> conjuncts(A & B)
frozenset({A, B})
>>> conjuncts(A | B)
frozenset({A | B})
"""
return And.make_args(expr)
def disjuncts(expr):
"""Return a list of the disjuncts in the sentence s.
Examples
========
>>> from sympy.logic.boolalg import disjuncts
>>> from sympy.abc import A, B
>>> disjuncts(A | B)
frozenset({A, B})
>>> disjuncts(A & B)
frozenset({A & B})
"""
return Or.make_args(expr)
def distribute_and_over_or(expr):
"""
Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
Examples
========
>>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_and_over_or(Or(A, And(Not(B), Not(C))))
(A | ~B) & (A | ~C)
"""
return _distribute((expr, And, Or))
def distribute_or_over_and(expr):
"""
Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in DNF.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_or_over_and(And(Or(Not(A), B), C))
(B & C) | (C & ~A)
"""
return _distribute((expr, Or, And))
def distribute_xor_over_and(expr):
"""
Given a sentence s consisting of conjunction and
exclusive disjunctions of literals, return an
equivalent exclusive disjunction.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not
>>> from sympy.abc import A, B, C
>>> distribute_xor_over_and(And(Xor(Not(A), B), C))
(B & C) ^ (C & ~A)
"""
return _distribute((expr, Xor, And))
def _distribute(info):
"""
Distributes info[1] over info[2] with respect to info[0].
"""
if isinstance(info[0], info[2]):
for arg in info[0].args:
if isinstance(arg, info[1]):
conj = arg
break
else:
return info[0]
rest = info[2](*[a for a in info[0].args if a is not conj])
return info[1](*list(map(_distribute,
[(info[2](c, rest), info[1], info[2])
for c in conj.args])), remove_true=False)
elif isinstance(info[0], info[1]):
return info[1](*list(map(_distribute,
[(x, info[1], info[2])
for x in info[0].args])),
remove_true=False)
else:
return info[0]
def to_anf(expr, deep=True):
r"""
Converts expr to Algebraic Normal Form (ANF).
ANF is a canonical normal form, which means that two
equivalent formulas will convert to the same ANF.
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it can be:
- purely true,
- purely false,
- conjunction of variables,
- exclusive disjunction.
The exclusive disjunction can only contain true, variables
or conjunction of variables. No negations are permitted.
If ``deep`` is ``False``, arguments of the boolean
expression are considered variables, i.e. only the
top-level expression is converted to ANF.
Examples
========
>>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent
>>> from sympy.logic.boolalg import to_anf
>>> from sympy.abc import A, B, C
>>> to_anf(Not(A))
A ^ True
>>> to_anf(And(Or(A, B), Not(C)))
A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C)
>>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False)
True ^ ~A ^ (~A & (Equivalent(B, C)))
"""
expr = sympify(expr)
if is_anf(expr):
return expr
return expr.to_anf(deep=deep)
def to_nnf(expr, simplify=True):
"""
Converts expr to Negation Normal Form.
A logical expression is in Negation Normal Form (NNF) if it
contains only And, Or and Not, and Not is applied only to literals.
If simplify is True, the result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C, D
>>> from sympy.logic.boolalg import Not, Equivalent, to_nnf
>>> to_nnf(Not((~A & ~B) | (C & D)))
(A | B) & (~C | ~D)
>>> to_nnf(Equivalent(A >> B, B >> A))
(A | ~B | (A & ~B)) & (B | ~A | (B & ~A))
"""
if is_nnf(expr, simplify):
return expr
return expr.to_nnf(simplify)
def to_cnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence s to conjunctive normal
form: ((A | ~B | ...) & (B | C | ...) & ...).
If simplify is True, the expr is evaluated to its simplest CNF
form using the Quine-McCluskey algorithm; this may take a long
time if there are more than 8 variables and requires that the
``force`` flag be set to True (default is False).
Examples
========
>>> from sympy.logic.boolalg import to_cnf
>>> from sympy.abc import A, B, D
>>> to_cnf(~(A | B) | D)
(D | ~A) & (D | ~B)
>>> to_cnf((A | B) & (A | ~A), True)
A | B
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'cnf', True, force=force)
# Don't convert unless we have to
if is_cnf(expr):
return expr
expr = eliminate_implications(expr)
res = distribute_and_over_or(expr)
return res
def to_dnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence s to disjunctive normal
form: ((A & ~B & ...) | (B & C & ...) | ...).
If simplify is True, the expr is evaluated to its simplest DNF form using
the Quine-McCluskey algorithm; this may take a long
time if there are more than 8 variables and requires that the
``force`` flag be set to True (default is False).
Examples
========
>>> from sympy.logic.boolalg import to_dnf
>>> from sympy.abc import A, B, C
>>> to_dnf(B & (A | C))
(A & B) | (B & C)
>>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True)
A | C
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'dnf', True, force=force)
# Don't convert unless we have to
if is_dnf(expr):
return expr
expr = eliminate_implications(expr)
return distribute_or_over_and(expr)
def is_anf(expr):
r"""
Checks if expr is in Algebraic Normal Form (ANF).
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it is purely true, purely false, conjunction of
variables or exclusive disjunction. The exclusive
disjunction can only contain true, variables or
conjunction of variables. No negations are permitted.
Examples
========
>>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf
>>> from sympy.abc import A, B, C
>>> is_anf(true)
True
>>> is_anf(A)
True
>>> is_anf(And(A, B, C))
True
>>> is_anf(Xor(A, Not(B)))
False
"""
expr = sympify(expr)
if is_literal(expr) and not isinstance(expr, Not):
return True
if isinstance(expr, And):
for arg in expr.args:
if not arg.is_Symbol:
return False
return True
elif isinstance(expr, Xor):
for arg in expr.args:
if isinstance(arg, And):
for a in arg.args:
if not a.is_Symbol:
return False
elif is_literal(arg):
if isinstance(arg, Not):
return False
else:
return False
return True
else:
return False
def is_nnf(expr, simplified=True):
"""
Checks if expr is in Negation Normal Form.
A logical expression is in Negation Normal Form (NNF) if it
contains only And, Or and Not, and Not is applied only to literals.
If simplified is True, checks if result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.boolalg import Not, is_nnf
>>> is_nnf(A & B | ~C)
True
>>> is_nnf((A | ~A) & (B | C))
False
>>> is_nnf((A | ~A) & (B | C), False)
True
>>> is_nnf(Not(A & B) | C)
False
>>> is_nnf((A >> B) & (B >> A))
False
"""
expr = sympify(expr)
if is_literal(expr):
return True
stack = [expr]
while stack:
expr = stack.pop()
if expr.func in (And, Or):
if simplified:
args = expr.args
for arg in args:
if Not(arg) in args:
return False
stack.extend(expr.args)
elif not is_literal(expr):
return False
return True
def is_cnf(expr):
"""
Test whether or not an expression is in conjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_cnf
>>> from sympy.abc import A, B, C
>>> is_cnf(A | B | C)
True
>>> is_cnf(A & B & C)
True
>>> is_cnf((A & B) | C)
False
"""
return _is_form(expr, And, Or)
def is_dnf(expr):
"""
Test whether or not an expression is in disjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_dnf
>>> from sympy.abc import A, B, C
>>> is_dnf(A | B | C)
True
>>> is_dnf(A & B & C)
True
>>> is_dnf((A & B) | C)
True
>>> is_dnf(A & (B | C))
False
"""
return _is_form(expr, Or, And)
def _is_form(expr, function1, function2):
"""
Test whether or not an expression is of the required form.
"""
expr = sympify(expr)
vals = function1.make_args(expr) if isinstance(expr, function1) else [expr]
for lit in vals:
if isinstance(lit, function2):
vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit]
for l in vals2:
if is_literal(l) is False:
return False
elif is_literal(lit) is False:
return False
return True
def eliminate_implications(expr):
"""
Change >>, <<, and Equivalent into &, |, and ~. That is, return an
expression that is equivalent to s, but has only &, |, and ~ as logical
operators.
Examples
========
>>> from sympy.logic.boolalg import Implies, Equivalent, \
eliminate_implications
>>> from sympy.abc import A, B, C
>>> eliminate_implications(Implies(A, B))
B | ~A
>>> eliminate_implications(Equivalent(A, B))
(A | ~B) & (B | ~A)
>>> eliminate_implications(Equivalent(A, B, C))
(A | ~C) & (B | ~A) & (C | ~B)
"""
return to_nnf(expr, simplify=False)
def is_literal(expr):
"""
Returns True if expr is a literal, else False.
Examples
========
>>> from sympy import Or, Q
>>> from sympy.abc import A, B
>>> from sympy.logic.boolalg import is_literal
>>> is_literal(A)
True
>>> is_literal(~A)
True
>>> is_literal(Q.zero(A))
True
>>> is_literal(A + B)
True
>>> is_literal(Or(A, B))
False
"""
if isinstance(expr, Not):
return is_literal(expr.args[0])
elif expr in (True, False) or expr.is_Atom:
return True
elif not isinstance(expr, BooleanFunction) and all(
a.is_Atom for a in expr.args):
return True
return False
def to_int_repr(clauses, symbols):
"""
Takes clauses in CNF format and puts them into an integer representation.
Examples
========
>>> from sympy.logic.boolalg import to_int_repr
>>> from sympy.abc import x, y
>>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}]
True
"""
# Convert the symbol list into a dict
symbols = dict(list(zip(symbols, list(range(1, len(symbols) + 1)))))
def append_symbol(arg, symbols):
if isinstance(arg, Not):
return -symbols[arg.args[0]]
else:
return symbols[arg]
return [{append_symbol(arg, symbols) for arg in Or.make_args(c)}
for c in clauses]
def term_to_integer(term):
"""
Return an integer corresponding to the base-2 digits given by ``term``.
Parameters
==========
term : a string or list of ones and zeros
Examples
========
>>> from sympy.logic.boolalg import term_to_integer
>>> term_to_integer([1, 0, 0])
4
>>> term_to_integer('100')
4
"""
return int(''.join(list(map(str, list(term)))), 2)
def integer_to_term(k, n_bits=None):
"""
Return a list of the base-2 digits in the integer, ``k``.
Parameters
==========
k : int
n_bits : int
If ``n_bits`` is given and the number of digits in the binary
representation of ``k`` is smaller than ``n_bits`` then left-pad the
list with 0s.
Examples
========
>>> from sympy.logic.boolalg import integer_to_term
>>> integer_to_term(4)
[1, 0, 0]
>>> integer_to_term(4, 6)
[0, 0, 0, 1, 0, 0]
"""
s = '{0:0{1}b}'.format(abs(as_int(k)), as_int(abs(n_bits or 0)))
return list(map(int, s))
def truth_table(expr, variables, input=True):
"""
Return a generator of all possible configurations of the input variables,
and the result of the boolean expression for those values.
Parameters
==========
expr : string or boolean expression
variables : list of variables
input : boolean (default True)
indicates whether to return the input combinations.
Examples
========
>>> from sympy.logic.boolalg import truth_table
>>> from sympy.abc import x,y
>>> table = truth_table(x >> y, [x, y])
>>> for t in table:
... print('{0} -> {1}'.format(*t))
[0, 0] -> True
[0, 1] -> True
[1, 0] -> False
[1, 1] -> True
>>> table = truth_table(x | y, [x, y])
>>> list(table)
[([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)]
If input is false, truth_table returns only a list of truth values.
In this case, the corresponding input values of variables can be
deduced from the index of a given output.
>>> from sympy.logic.boolalg import integer_to_term
>>> vars = [y, x]
>>> values = truth_table(x >> y, vars, input=False)
>>> values = list(values)
>>> values
[True, False, True, True]
>>> for i, value in enumerate(values):
... print('{0} -> {1}'.format(list(zip(
... vars, integer_to_term(i, len(vars)))), value))
[(y, 0), (x, 0)] -> True
[(y, 0), (x, 1)] -> False
[(y, 1), (x, 0)] -> True
[(y, 1), (x, 1)] -> True
"""
variables = [sympify(v) for v in variables]
expr = sympify(expr)
if not isinstance(expr, BooleanFunction) and not is_literal(expr):
return
table = product([0, 1], repeat=len(variables))
for term in table:
term = list(term)
value = expr.xreplace(dict(zip(variables, term)))
if input:
yield term, value
else:
yield value
def _check_pair(minterm1, minterm2):
"""
Checks if a pair of minterms differs by only one bit. If yes, returns
index, else returns -1.
"""
# Early termination seems to be faster than list comprehension,
# at least for large examples.
index = -1
for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower
if i != minterm2[x]:
if index == -1:
index = x
else:
return -1
return index
def _convert_to_varsSOP(minterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for SOP).
"""
temp = [variables[n] if val == 1 else Not(variables[n])
for n, val in enumerate(minterm) if val != 3]
return And(*temp)
def _convert_to_varsPOS(maxterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for POS).
"""
temp = [variables[n] if val == 0 else Not(variables[n])
for n, val in enumerate(maxterm) if val != 3]
return Or(*temp)
def _convert_to_varsANF(term, variables):
"""
Converts a term in the expansion of a function from binary to it's
variable form (for ANF).
Parameters
==========
term : list of 1's and 0's (complementation patter)
variables : list of variables
"""
temp = [variables[n] for n, t in enumerate(term) if t == 1]
if not temp:
return true
return And(*temp)
def _get_odd_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an odd number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1]
def _get_even_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an even number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0]
def _simplified_pairs(terms):
"""
Reduces a set of minterms, if possible, to a simplified set of minterms
with one less variable in the terms using QM method.
"""
if not terms:
return []
simplified_terms = []
todo = list(range(len(terms)))
# Count number of ones as _check_pair can only potentially match if there
# is at most a difference of a single one
def ones_count(term):
return sum([1 for t in term if t == 1])
termdict = defaultdict(list)
for n, term in enumerate(terms):
ones = ones_count(term)
termdict[ones].append(n)
variables = len(terms[0])
for k in range(variables):
for i in termdict[k]:
for j in termdict[k+1]:
index = _check_pair(terms[i], terms[j])
if index != -1:
# Mark terms handled
todo[i] = todo[j] = None
# Copy old term
newterm = terms[i][:]
# Set differing position to don't care
newterm[index] = 3
# Add if not already there
if newterm not in simplified_terms:
simplified_terms.append(newterm)
if simplified_terms:
# Further simplifications only among the new terms
simplified_terms = _simplified_pairs(simplified_terms)
# Add remaining, non-simplified, terms
simplified_terms.extend(
[terms[i] for i in [_ for _ in todo if _ is not None]])
return simplified_terms
def _compare_term(minterm, term):
"""
Return True if a binary term is satisfied by the given term. Used
for recognizing prime implicants.
"""
for m, t in zip(minterm, term):
if t != 3 and m != t:
return False
return True
def _rem_redundancy(l1, terms):
"""
After the truth table has been sufficiently simplified, use the prime
implicant table method to recognize and eliminate redundant pairs,
and return the essential arguments.
"""
if not terms:
return []
nterms = len(terms)
nl1 = len(l1)
# Create dominating matrix
dommatrix = [[0]*nl1 for n in range(nterms)]
for primei, prime in enumerate(l1):
for termi, term in enumerate(terms):
if _compare_term(term, prime):
dommatrix[termi][primei] = 1
# Non-dominated prime implicants, dominated to be removed
ndprimeimplicants = set(range(nl1))
# Non-dominated terms, dominated to be removed
ndterms = set(range(nterms))
# Keep track if anything changed
anythingchanged = True
# Then, go again
while anythingchanged:
anythingchanged = False
# Make copy for iteration
oldndterms = ndterms.copy()
# Filter matrix to only get non-dominated items
filteredrows = [[dommatrix[rowi][i] for i in list(ndprimeimplicants)]
for rowi in oldndterms]
for n, rowi in enumerate(oldndterms):
# Still non-dominated?
if rowi in ndterms:
row = filteredrows[n]
for n2, row2i in enumerate(oldndterms):
# Still non-dominated?
if n != n2 and row2i in ndterms:
if all(a >= b for (a, b) in zip(filteredrows[n2], row)):
# row2 dominating row, remove row2
ndterms.remove(row2i)
anythingchanged = True
# Make copy for iteration
oldndprimeimplicants = ndprimeimplicants.copy()
# Filter matrix to only get non-dominated items
filteredcols = [[dommatrix[i][coli] for i in list(ndterms)]
for coli in oldndprimeimplicants]
for n, coli in enumerate(oldndprimeimplicants):
# Still non-dominated?
if coli in ndprimeimplicants:
col = filteredcols[n]
for n2, col2i in enumerate(oldndprimeimplicants):
# Still non-dominated?
if coli != col2i and col2i in ndprimeimplicants:
if all(a >= b for (a, b) in zip(col, filteredcols[n2])):
# col dominating col2, remove col2
ndprimeimplicants.remove(col2i)
anythingchanged = True
return [l1[i] for i in ndprimeimplicants]
def _input_to_binlist(inputlist, variables):
binlist = []
bits = len(variables)
for val in inputlist:
if isinstance(val, int):
binlist.append(ibin(val, bits))
elif isinstance(val, dict):
nonspecvars = list(variables)
for key in val.keys():
nonspecvars.remove(key)
for t in product([0, 1], repeat=len(nonspecvars)):
d = dict(zip(nonspecvars, t))
d.update(val)
binlist.append([d[v] for v in variables])
elif isinstance(val, (list, tuple)):
if len(val) != bits:
raise ValueError("Each term must contain {} bits as there are"
"\n{} variables (or be an integer)."
"".format(bits, bits))
binlist.append(list(val))
else:
raise TypeError("A term list can only contain lists,"
" ints or dicts.")
return binlist
def SOPform(variables, minterms, dontcares=None):
"""
The SOPform function uses simplified_pairs and a redundant group-
eliminating algorithm to convert the list of all input combos that
generate '1' (the minterms) into the smallest Sum of Products form.
The variables must be given as the first argument.
Return a logical Or function (i.e., the "sum of products" or "SOP"
form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import SOPform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1],
... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> SOPform([w, x, y, z], minterms)
(x & ~w) | (y & z & ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(w & y & z) | (~w & ~y) | (x & z & ~w)
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
"""
variables = [sympify(v) for v in variables]
if minterms == []:
return false
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
new = _simplified_pairs(minterms + dontcares)
essential = _rem_redundancy(new, minterms)
return Or(*[_convert_to_varsSOP(x, variables) for x in essential])
def POSform(variables, minterms, dontcares=None):
"""
The POSform function uses simplified_pairs and a redundant-group
eliminating algorithm to convert the list of all input combinations
that generate '1' (the minterms) into the smallest Product of Sums form.
The variables must be given as the first argument.
Return a logical And function (i.e., the "product of sums" or "POS"
form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import POSform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1],
... [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> POSform([w, x, y, z], minterms)
(x | y) & (x | z) & (~w | ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
(w | x) & (y | ~w) & (z | ~y)
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
"""
variables = [sympify(v) for v in variables]
if minterms == []:
return false
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
maxterms = []
for t in product([0, 1], repeat=len(variables)):
t = list(t)
if (t not in minterms) and (t not in dontcares):
maxterms.append(t)
new = _simplified_pairs(maxterms + dontcares)
essential = _rem_redundancy(new, maxterms)
return And(*[_convert_to_varsPOS(x, variables) for x in essential])
def ANFform(variables, truthvalues):
"""
The ANFform function converts the list of truth values to
Algebraic Normal Form (ANF).
The variables must be given as the first argument.
Return True, False, logical And funciton (i.e., the
"Zhegalkin monomial") or logical Xor function (i.e.,
the "Zhegalkin polynomial"). When True and False
are represented by 1 and 0, respectively, then
And is multiplication and Xor is addition.
Formally a "Zhegalkin monomial" is the product (logical
And) of a finite set of distinct variables, including
the empty set whose product is denoted 1 (True).
A "Zhegalkin polynomial" is the sum (logical Xor) of a
set of Zhegalkin monomials, with the empty set denoted
by 0 (False).
Parameters
==========
variables : list of variables
truthvalues : list of 1's and 0's (result column of truth table)
Examples
========
>>> from sympy.logic.boolalg import ANFform
>>> from sympy.abc import x, y
>>> ANFform([x], [1, 0])
x ^ True
>>> ANFform([x, y], [0, 1, 1, 1])
x ^ y ^ (x & y)
References
==========
.. [2] https://en.wikipedia.org/wiki/Zhegalkin_polynomial
"""
n_vars = len(variables)
n_values = len(truthvalues)
if n_values != 2 ** n_vars:
raise ValueError("The number of truth values must be equal to 2^%d, "
"got %d" % (n_vars, n_values))
variables = [sympify(v) for v in variables]
coeffs = anf_coeffs(truthvalues)
terms = []
for i, t in enumerate(product([0, 1], repeat=n_vars)):
if coeffs[i] == 1:
terms.append(t)
return Xor(*[_convert_to_varsANF(x, variables) for x in terms],
remove_true=False)
def anf_coeffs(truthvalues):
"""
Convert a list of truth values of some boolean expression
to the list of coefficients of the polynomial mod 2 (exclusive
disjunction) representing the boolean expression in ANF
(i.e., the "Zhegalkin polynomial").
There are 2^n possible Zhegalkin monomials in n variables, since
each monomial is fully specified by the presence or absence of
each variable.
We can enumerate all the monomials. For example, boolean
function with four variables (a, b, c, d) can contain
up to 2^4 = 16 monomials. The 13-th monomial is the
product a & b & d, because 13 in binary is 1, 1, 0, 1.
A given monomial's presence or absence in a polynomial corresponds
to that monomial's coefficient being 1 or 0 respectively.
Examples
========
>>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor
>>> from sympy.abc import a, b, c
>>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1]
>>> coeffs = anf_coeffs(truthvalues)
>>> coeffs
[0, 1, 1, 0, 0, 0, 1, 0]
>>> polynomial = Xor(*[
... bool_monomial(k, [a, b, c])
... for k, coeff in enumerate(coeffs) if coeff == 1
... ])
>>> polynomial
b ^ c ^ (a & b)
"""
s = '{:b}'.format(len(truthvalues))
n = len(s) - 1
if len(truthvalues) != 2**n:
raise ValueError("The number of truth values must be a power of two, "
"got %d" % len(truthvalues))
coeffs = [[v] for v in truthvalues]
for i in range(n):
tmp = []
for j in range(2 ** (n-i-1)):
tmp.append(coeffs[2*j] +
list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1])))
coeffs = tmp
return coeffs[0]
def bool_minterm(k, variables):
"""
Return the k-th minterm.
Minterms are numbered by a binary encoding of the complementation
pattern of the variables. This convention assigns the value 1 to
the direct form and 0 to the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation patter)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_minterm
>>> from sympy.abc import x, y, z
>>> bool_minterm([1, 0, 1], [x, y, z])
x & z & ~y
>>> bool_minterm(6, [x, y, z])
x & y & ~z
References
==========
.. [3] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsSOP(k, variables)
def bool_maxterm(k, variables):
"""
Return the k-th maxterm.
Each maxterm is assigned an index based on the opposite
conventional binary encoding used for minterms. The maxterm
convention assigns the value 0 to the direct form and 1 to
the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation pattern)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_maxterm
>>> from sympy.abc import x, y, z
>>> bool_maxterm([1, 0, 1], [x, y, z])
y | ~x | ~z
>>> bool_maxterm(6, [x, y, z])
z | ~x | ~y
References
==========
.. [4] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsPOS(k, variables)
def bool_monomial(k, variables):
"""
Return the k-th monomial.
Monomials are numbered by a binary encoding of the presence and
absences of the variables. This convention assigns the value
1 to the presence of variable and 0 to the absence of variable.
Each boolean function can be uniquely represented by a
Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin
Polynomial of the boolean function with n variables can contain
up to 2^n monomials. We can enumarate all the monomials.
Each monomial is fully specified by the presence or absence
of each variable.
For example, boolean function with four variables (a, b, c, d)
can contain up to 2^4 = 16 monomials. The 13-th monomial is the
product a & b & d, because 13 in binary is 1, 1, 0, 1.
Parameters
==========
k : int or list of 1's and 0's
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_monomial
>>> from sympy.abc import x, y, z
>>> bool_monomial([1, 0, 1], [x, y, z])
x & z
>>> bool_monomial(6, [x, y, z])
x & y
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsANF(k, variables)
def _find_predicates(expr):
"""Helper to find logical predicates in BooleanFunctions.
A logical predicate is defined here as anything within a BooleanFunction
that is not a BooleanFunction itself.
"""
if not isinstance(expr, BooleanFunction):
return {expr}
return set().union(*(_find_predicates(i) for i in expr.args))
def simplify_logic(expr, form=None, deep=True, force=False):
"""
This function simplifies a boolean function to its simplified version
in SOP or POS form. The return type is an Or or And object in SymPy.
Parameters
==========
expr : string or boolean expression
form : string ('cnf' or 'dnf') or None (default).
If 'cnf' or 'dnf', the simplest expression in the corresponding
normal form is returned; if None, the answer is returned
according to the form with fewest args (in CNF by default).
deep : boolean (default True)
Indicates whether to recursively simplify any
non-boolean functions contained within the input.
force : boolean (default False)
As the simplifications require exponential time in the number
of variables, there is by default a limit on expressions with
8 variables. When the expression has more than 8 variables
only symbolical simplification (controlled by ``deep``) is
made. By setting force to ``True``, this limit is removed. Be
aware that this can lead to very long simplification times.
Examples
========
>>> from sympy.logic import simplify_logic
>>> from sympy.abc import x, y, z
>>> from sympy import S
>>> b = (~x & ~y & ~z) | ( ~x & ~y & z)
>>> simplify_logic(b)
~x & ~y
>>> S(b)
(z & ~x & ~y) | (~x & ~y & ~z)
>>> simplify_logic(_)
~x & ~y
"""
if form not in (None, 'cnf', 'dnf'):
raise ValueError("form can be cnf or dnf only")
expr = sympify(expr)
# check for quick exit: right form and all args are
# literal and do not involve Not
isc = is_cnf(expr)
isd = is_dnf(expr)
form_ok = (
isc and form == 'cnf' or
isd and form == 'dnf')
if form_ok and all(is_literal(a)
for a in expr.args):
return expr
if deep:
variables = _find_predicates(expr)
from sympy.simplify.simplify import simplify
s = [simplify(v) for v in variables]
expr = expr.xreplace(dict(zip(variables, s)))
if not isinstance(expr, BooleanFunction):
return expr
# get variables in case not deep or after doing
# deep simplification since they may have changed
variables = _find_predicates(expr)
if not force and len(variables) > 8:
return expr
# group into constants and variable values
c, v = sift(variables, lambda x: x in (True, False), binary=True)
variables = c + v
truthtable = []
# standardize constants to be 1 or 0 in keeping with truthtable
c = [1 if i == True else 0 for i in c]
for t in product([0, 1], repeat=len(v)):
if expr.xreplace(dict(zip(v, t))) == True:
truthtable.append(c + list(t))
big = len(truthtable) >= (2 ** (len(variables) - 1))
if form == 'dnf' or form is None and big:
return SOPform(variables, truthtable)
return POSform(variables, truthtable)
def _finger(eq):
"""
Assign a 5-item fingerprint to each symbol in the equation:
[
# of times it appeared as a Symbol;
# of times it appeared as a Not(symbol);
# of times it appeared as a Symbol in an And or Or;
# of times it appeared as a Not(Symbol) in an And or Or;
a sorted tuple of tuples, (i, j, k), where i is the number of arguments
in an And or Or with which it appeared as a Symbol, and j is
the number of arguments that were Not(Symbol); k is the number
of times that (i, j) was seen.
]
Examples
========
>>> from sympy.logic.boolalg import _finger as finger
>>> from sympy import And, Or, Not, Xor, to_cnf, symbols
>>> from sympy.abc import a, b, x, y
>>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))
>>> dict(finger(eq))
{(0, 0, 1, 0, ((2, 0, 1),)): [x],
(0, 0, 1, 0, ((2, 1, 1),)): [a, b],
(0, 0, 1, 2, ((2, 0, 1),)): [y]}
>>> dict(finger(x & ~y))
{(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}
In the following, the (5, 2, 6) means that there were 6 Or
functions in which a symbol appeared as itself amongst 5 arguments in
which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``
is counted once for a0, a1 and a2.
>>> dict(finger(to_cnf(Xor(*symbols('a:5')))))
{(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}
The equation must not have more than one level of nesting:
>>> dict(finger(And(Or(x, y), y)))
{(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}
>>> dict(finger(And(Or(x, And(a, x)), y)))
Traceback (most recent call last):
...
NotImplementedError: unexpected level of nesting
So y and x have unique fingerprints, but a and b do not.
"""
f = eq.free_symbols
d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))
for a in eq.args:
if a.is_Symbol:
d[a][0] += 1
elif a.is_Not:
d[a.args[0]][1] += 1
else:
o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)
for ai in a.args:
if ai.is_Symbol:
d[ai][2] += 1
d[ai][-1][o] += 1
elif ai.is_Not:
d[ai.args[0]][3] += 1
else:
raise NotImplementedError('unexpected level of nesting')
inv = defaultdict(list)
for k, v in ordered(iter(d.items())):
v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))
inv[tuple(v)].append(k)
return inv
def bool_map(bool1, bool2):
"""
Return the simplified version of bool1, and the mapping of variables
that makes the two expressions bool1 and bool2 represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned.
For example, And(x, y) is logically equivalent to And(a, b) for
the mapping {x: a, y:b} or {x: b, y:a}.
If no such mapping exists, return False.
Examples
========
>>> from sympy import SOPform, bool_map, Or, And, Not, Xor
>>> from sympy.abc import w, x, y, z, a, b, c, d
>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
>>> bool_map(function1, function2)
(y & ~z, {y: a, z: b})
The results are not necessarily unique, but they are canonical. Here,
``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y))
>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
>>> bool_map(eq, eq2)
((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
>>> eq = And(Xor(a, b), c, And(c,d))
>>> bool_map(eq, eq.subs(c, x))
(c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x})
"""
def match(function1, function2):
"""Return the mapping that equates variables between two
simplified boolean expressions if possible.
By "simplified" we mean that a function has been denested
and is either an And (or an Or) whose arguments are either
symbols (x), negated symbols (Not(x)), or Or (or an And) whose
arguments are only symbols or negated symbols. For example,
And(x, Not(y), Or(w, Not(z))).
Basic.match is not robust enough (see issue 4835) so this is
a workaround that is valid for simplified boolean expressions
"""
# do some quick checks
if function1.__class__ != function2.__class__:
return None # maybe simplification makes them the same?
if len(function1.args) != len(function2.args):
return None # maybe simplification makes them the same?
if function1.is_Symbol:
return {function1: function2}
# get the fingerprint dictionaries
f1 = _finger(function1)
f2 = _finger(function2)
# more quick checks
if len(f1) != len(f2):
return False
# assemble the match dictionary if possible
matchdict = {}
for k in f1.keys():
if k not in f2:
return False
if len(f1[k]) != len(f2[k]):
return False
for i, x in enumerate(f1[k]):
matchdict[x] = f2[k][i]
return matchdict
a = simplify_logic(bool1)
b = simplify_logic(bool2)
m = match(a, b)
if m:
return a, m
return m
def simplify_patterns_and():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
# With a better canonical fewer results are required
_matchers_and = ((And(Eq(a, b), Ge(a, b)), Eq(a, b)),
(And(Eq(a, b), Gt(a, b)), S.false),
(And(Eq(a, b), Le(a, b)), Eq(a, b)),
(And(Eq(a, b), Lt(a, b)), S.false),
(And(Ge(a, b), Gt(a, b)), Gt(a, b)),
(And(Ge(a, b), Le(a, b)), Eq(a, b)),
(And(Ge(a, b), Lt(a, b)), S.false),
(And(Ge(a, b), Ne(a, b)), Gt(a, b)),
(And(Gt(a, b), Le(a, b)), S.false),
(And(Gt(a, b), Lt(a, b)), S.false),
(And(Gt(a, b), Ne(a, b)), Gt(a, b)),
(And(Le(a, b), Lt(a, b)), Lt(a, b)),
(And(Le(a, b), Ne(a, b)), Lt(a, b)),
(And(Lt(a, b), Ne(a, b)), Lt(a, b)),
# Min/max
(And(Ge(a, b), Ge(a, c)), Ge(a, Max(b, c))),
(And(Ge(a, b), Gt(a, c)), ITE(b > c, Ge(a, b), Gt(a, c))),
(And(Gt(a, b), Gt(a, c)), Gt(a, Max(b, c))),
(And(Le(a, b), Le(a, c)), Le(a, Min(b, c))),
(And(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))),
(And(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))),
# Sign
(And(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))),
)
return _matchers_and
def simplify_patterns_or():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
_matchers_or = ((Or(Eq(a, b), Ge(a, b)), Ge(a, b)),
(Or(Eq(a, b), Gt(a, b)), Ge(a, b)),
(Or(Eq(a, b), Le(a, b)), Le(a, b)),
(Or(Eq(a, b), Lt(a, b)), Le(a, b)),
(Or(Ge(a, b), Gt(a, b)), Ge(a, b)),
(Or(Ge(a, b), Le(a, b)), S.true),
(Or(Ge(a, b), Lt(a, b)), S.true),
(Or(Ge(a, b), Ne(a, b)), S.true),
(Or(Gt(a, b), Le(a, b)), S.true),
(Or(Gt(a, b), Lt(a, b)), Ne(a, b)),
(Or(Gt(a, b), Ne(a, b)), Ne(a, b)),
(Or(Le(a, b), Lt(a, b)), Le(a, b)),
(Or(Le(a, b), Ne(a, b)), S.true),
(Or(Lt(a, b), Ne(a, b)), Ne(a, b)),
# Min/max
(Or(Ge(a, b), Ge(a, c)), Ge(a, Min(b, c))),
(Or(Ge(a, b), Gt(a, c)), ITE(b > c, Gt(a, c), Ge(a, b))),
(Or(Gt(a, b), Gt(a, c)), Gt(a, Min(b, c))),
(Or(Le(a, b), Le(a, c)), Le(a, Max(b, c))),
(Or(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))),
(Or(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))),
)
return _matchers_or
def simplify_patterns_xor():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
_matchers_xor = ((Xor(Eq(a, b), Ge(a, b)), Gt(a, b)),
(Xor(Eq(a, b), Gt(a, b)), Ge(a, b)),
(Xor(Eq(a, b), Le(a, b)), Lt(a, b)),
(Xor(Eq(a, b), Lt(a, b)), Le(a, b)),
(Xor(Ge(a, b), Gt(a, b)), Eq(a, b)),
(Xor(Ge(a, b), Le(a, b)), Ne(a, b)),
(Xor(Ge(a, b), Lt(a, b)), S.true),
(Xor(Ge(a, b), Ne(a, b)), Le(a, b)),
(Xor(Gt(a, b), Le(a, b)), S.true),
(Xor(Gt(a, b), Lt(a, b)), Ne(a, b)),
(Xor(Gt(a, b), Ne(a, b)), Lt(a, b)),
(Xor(Le(a, b), Lt(a, b)), Eq(a, b)),
(Xor(Le(a, b), Ne(a, b)), Ge(a, b)),
(Xor(Lt(a, b), Ne(a, b)), Gt(a, b)),
# Min/max
(Xor(Ge(a, b), Ge(a, c)),
And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))),
(Xor(Ge(a, b), Gt(a, c)),
ITE(b > c, And(Gt(a, c), Lt(a, b)),
And(Ge(a, b), Le(a, c)))),
(Xor(Gt(a, b), Gt(a, c)),
And(Gt(a, Min(b, c)), Le(a, Max(b, c)))),
(Xor(Le(a, b), Le(a, c)),
And(Le(a, Max(b, c)), Gt(a, Min(b, c)))),
(Xor(Le(a, b), Lt(a, c)),
ITE(b < c, And(Lt(a, c), Gt(a, b)),
And(Le(a, b), Ge(a, c)))),
(Xor(Lt(a, b), Lt(a, c)),
And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))),
)
return _matchers_xor
|
ebf93e020d83fd710e7e35c6f5e8405f67fa23392873dbbd9e36b70e1bad8dba | import copy
from sympy.core.function import expand_mul
from sympy.functions.elementary.miscellaneous import Min, sqrt
from sympy.functions.elementary.complexes import sign
from .common import NonSquareMatrixError, NonPositiveDefiniteMatrixError
from .utilities import _get_intermediate_simp, _iszero
from .determinant import _find_reasonable_pivot_naive
def _rank_decomposition(M, iszerofunc=_iszero, simplify=False):
r"""Returns a pair of matrices (`C`, `F`) with matching rank
such that `A = C F`.
Parameters
==========
iszerofunc : Function, optional
A function used for detecting whether an element can
act as a pivot. ``lambda x: x.is_zero`` is used by default.
simplify : Bool or Function, optional
A function used to simplify elements when looking for a
pivot. By default SymPy's ``simplify`` is used.
Returns
=======
(C, F) : Matrices
`C` and `F` are full-rank matrices with rank as same as `A`,
whose product gives `A`.
See Notes for additional mathematical details.
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([
... [1, 3, 1, 4],
... [2, 7, 3, 9],
... [1, 5, 3, 1],
... [1, 2, 0, 8]
... ])
>>> C, F = A.rank_decomposition()
>>> C
Matrix([
[1, 3, 4],
[2, 7, 9],
[1, 5, 1],
[1, 2, 8]])
>>> F
Matrix([
[1, 0, -2, 0],
[0, 1, 1, 0],
[0, 0, 0, 1]])
>>> C * F == A
True
Notes
=====
Obtaining `F`, an RREF of `A`, is equivalent to creating a
product
.. math::
E_n E_{n-1} ... E_1 A = F
where `E_n, E_{n-1}, ... , E_1` are the elimination matrices or
permutation matrices equivalent to each row-reduction step.
The inverse of the same product of elimination matrices gives
`C`:
.. math::
C = (E_n E_{n-1} ... E_1)^{-1}
It is not necessary, however, to actually compute the inverse:
the columns of `C` are those from the original matrix with the
same column indices as the indices of the pivot columns of `F`.
References
==========
.. [1] https://en.wikipedia.org/wiki/Rank_factorization
.. [2] Piziak, R.; Odell, P. L. (1 June 1999).
"Full Rank Factorization of Matrices".
Mathematics Magazine. 72 (3): 193. doi:10.2307/2690882
See Also
========
rref
"""
F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc,
pivots=True)
rank = len(pivot_cols)
C = M.extract(range(M.rows), pivot_cols)
F = F[:rank, :]
return C, F
def _liupc(M):
"""Liu's algorithm, for pre-determination of the Elimination Tree of
the given matrix, used in row-based symbolic Cholesky factorization.
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> S = SparseMatrix([
... [1, 0, 3, 2],
... [0, 0, 1, 0],
... [4, 0, 0, 5],
... [0, 6, 7, 0]])
>>> S.liupc()
([[0], [], [0], [1, 2]], [4, 3, 4, 4])
References
==========
Symbolic Sparse Cholesky Factorization using Elimination Trees,
Jeroen Van Grondelle (1999)
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582
"""
# Algorithm 2.4, p 17 of reference
# get the indices of the elements that are non-zero on or below diag
R = [[] for r in range(M.rows)]
for r, c, _ in M.row_list():
if c <= r:
R[r].append(c)
inf = len(R) # nothing will be this large
parent = [inf]*M.rows
virtual = [inf]*M.rows
for r in range(M.rows):
for c in R[r][:-1]:
while virtual[c] < r:
t = virtual[c]
virtual[c] = r
c = t
if virtual[c] == inf:
parent[c] = virtual[c] = r
return R, parent
def _row_structure_symbolic_cholesky(M):
"""Symbolic cholesky factorization, for pre-determination of the
non-zero structure of the Cholesky factororization.
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> S = SparseMatrix([
... [1, 0, 3, 2],
... [0, 0, 1, 0],
... [4, 0, 0, 5],
... [0, 6, 7, 0]])
>>> S.row_structure_symbolic_cholesky()
[[0], [], [0], [1, 2]]
References
==========
Symbolic Sparse Cholesky Factorization using Elimination Trees,
Jeroen Van Grondelle (1999)
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582
"""
R, parent = M.liupc()
inf = len(R) # this acts as infinity
Lrow = copy.deepcopy(R)
for k in range(M.rows):
for j in R[k]:
while j != inf and j != k:
Lrow[k].append(j)
j = parent[j]
Lrow[k] = list(sorted(set(Lrow[k])))
return Lrow
def _cholesky(M, hermitian=True):
"""Returns the Cholesky-type decomposition L of a matrix A
such that L * L.H == A if hermitian flag is True,
or L * L.T == A if hermitian is False.
A must be a Hermitian positive-definite matrix if hermitian is True,
or a symmetric matrix if it is False.
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
>>> A.cholesky()
Matrix([
[ 5, 0, 0],
[ 3, 3, 0],
[-1, 1, 3]])
>>> A.cholesky() * A.cholesky().T
Matrix([
[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]])
The matrix can have complex entries:
>>> from sympy import I
>>> A = Matrix(((9, 3*I), (-3*I, 5)))
>>> A.cholesky()
Matrix([
[ 3, 0],
[-I, 2]])
>>> A.cholesky() * A.cholesky().H
Matrix([
[ 9, 3*I],
[-3*I, 5]])
Non-hermitian Cholesky-type decomposition may be useful when the
matrix is not positive-definite.
>>> A = Matrix([[1, 2], [2, 1]])
>>> L = A.cholesky(hermitian=False)
>>> L
Matrix([
[1, 0],
[2, sqrt(3)*I]])
>>> L*L.T == A
True
See Also
========
sympy.matrices.dense.DenseMatrix.LDLdecomposition
sympy.matrices.matrices.MatrixBase.LUdecomposition
QRdecomposition
"""
from .dense import MutableDenseMatrix
if not M.is_square:
raise NonSquareMatrixError("Matrix must be square.")
if hermitian and not M.is_hermitian:
raise ValueError("Matrix must be Hermitian.")
if not hermitian and not M.is_symmetric():
raise ValueError("Matrix must be symmetric.")
L = MutableDenseMatrix.zeros(M.rows, M.rows)
if hermitian:
for i in range(M.rows):
for j in range(i):
L[i, j] = ((1 / L[j, j])*(M[i, j] -
sum(L[i, k]*L[j, k].conjugate() for k in range(j))))
Lii2 = (M[i, i] -
sum(L[i, k]*L[i, k].conjugate() for k in range(i)))
if Lii2.is_positive is False:
raise NonPositiveDefiniteMatrixError(
"Matrix must be positive-definite")
L[i, i] = sqrt(Lii2)
else:
for i in range(M.rows):
for j in range(i):
L[i, j] = ((1 / L[j, j])*(M[i, j] -
sum(L[i, k]*L[j, k] for k in range(j))))
L[i, i] = sqrt(M[i, i] -
sum(L[i, k]**2 for k in range(i)))
return M._new(L)
def _cholesky_sparse(M, hermitian=True):
"""
Returns the Cholesky decomposition L of a matrix A
such that L * L.T = A
A must be a square, symmetric, positive-definite
and non-singular matrix
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> A = SparseMatrix(((25,15,-5),(15,18,0),(-5,0,11)))
>>> A.cholesky()
Matrix([
[ 5, 0, 0],
[ 3, 3, 0],
[-1, 1, 3]])
>>> A.cholesky() * A.cholesky().T == A
True
The matrix can have complex entries:
>>> from sympy import I
>>> A = SparseMatrix(((9, 3*I), (-3*I, 5)))
>>> A.cholesky()
Matrix([
[ 3, 0],
[-I, 2]])
>>> A.cholesky() * A.cholesky().H
Matrix([
[ 9, 3*I],
[-3*I, 5]])
Non-hermitian Cholesky-type decomposition may be useful when the
matrix is not positive-definite.
>>> A = SparseMatrix([[1, 2], [2, 1]])
>>> L = A.cholesky(hermitian=False)
>>> L
Matrix([
[1, 0],
[2, sqrt(3)*I]])
>>> L*L.T == A
True
See Also
========
sympy.matrices.sparse.SparseMatrix.LDLdecomposition
sympy.matrices.matrices.MatrixBase.LUdecomposition
QRdecomposition
"""
from .dense import MutableDenseMatrix
if not M.is_square:
raise NonSquareMatrixError("Matrix must be square.")
if hermitian and not M.is_hermitian:
raise ValueError("Matrix must be Hermitian.")
if not hermitian and not M.is_symmetric():
raise ValueError("Matrix must be symmetric.")
dps = _get_intermediate_simp(expand_mul, expand_mul)
Crowstruc = M.row_structure_symbolic_cholesky()
C = MutableDenseMatrix.zeros(M.rows)
for i in range(len(Crowstruc)):
for j in Crowstruc[i]:
if i != j:
C[i, j] = M[i, j]
summ = 0
for p1 in Crowstruc[i]:
if p1 < j:
for p2 in Crowstruc[j]:
if p2 < j:
if p1 == p2:
if hermitian:
summ += C[i, p1]*C[j, p1].conjugate()
else:
summ += C[i, p1]*C[j, p1]
else:
break
else:
break
C[i, j] = dps((C[i, j] - summ) / C[j, j])
else: # i == j
C[j, j] = M[j, j]
summ = 0
for k in Crowstruc[j]:
if k < j:
if hermitian:
summ += C[j, k]*C[j, k].conjugate()
else:
summ += C[j, k]**2
else:
break
Cjj2 = dps(C[j, j] - summ)
if hermitian and Cjj2.is_positive is False:
raise NonPositiveDefiniteMatrixError(
"Matrix must be positive-definite")
C[j, j] = sqrt(Cjj2)
return M._new(C)
def _LDLdecomposition(M, hermitian=True):
"""Returns the LDL Decomposition (L, D) of matrix A,
such that L * D * L.H == A if hermitian flag is True, or
L * D * L.T == A if hermitian is False.
This method eliminates the use of square root.
Further this ensures that all the diagonal entries of L are 1.
A must be a Hermitian positive-definite matrix if hermitian is True,
or a symmetric matrix otherwise.
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
>>> L, D = A.LDLdecomposition()
>>> L
Matrix([
[ 1, 0, 0],
[ 3/5, 1, 0],
[-1/5, 1/3, 1]])
>>> D
Matrix([
[25, 0, 0],
[ 0, 9, 0],
[ 0, 0, 9]])
>>> L * D * L.T * A.inv() == eye(A.rows)
True
The matrix can have complex entries:
>>> from sympy import I
>>> A = Matrix(((9, 3*I), (-3*I, 5)))
>>> L, D = A.LDLdecomposition()
>>> L
Matrix([
[ 1, 0],
[-I/3, 1]])
>>> D
Matrix([
[9, 0],
[0, 4]])
>>> L*D*L.H == A
True
See Also
========
sympy.matrices.dense.DenseMatrix.cholesky
sympy.matrices.matrices.MatrixBase.LUdecomposition
QRdecomposition
"""
from .dense import MutableDenseMatrix
if not M.is_square:
raise NonSquareMatrixError("Matrix must be square.")
if hermitian and not M.is_hermitian:
raise ValueError("Matrix must be Hermitian.")
if not hermitian and not M.is_symmetric():
raise ValueError("Matrix must be symmetric.")
D = MutableDenseMatrix.zeros(M.rows, M.rows)
L = MutableDenseMatrix.eye(M.rows)
if hermitian:
for i in range(M.rows):
for j in range(i):
L[i, j] = (1 / D[j, j])*(M[i, j] - sum(
L[i, k]*L[j, k].conjugate()*D[k, k] for k in range(j)))
D[i, i] = (M[i, i] -
sum(L[i, k]*L[i, k].conjugate()*D[k, k] for k in range(i)))
if D[i, i].is_positive is False:
raise NonPositiveDefiniteMatrixError(
"Matrix must be positive-definite")
else:
for i in range(M.rows):
for j in range(i):
L[i, j] = (1 / D[j, j])*(M[i, j] - sum(
L[i, k]*L[j, k]*D[k, k] for k in range(j)))
D[i, i] = M[i, i] - sum(L[i, k]**2*D[k, k] for k in range(i))
return M._new(L), M._new(D)
def _LDLdecomposition_sparse(M, hermitian=True):
"""
Returns the LDL Decomposition (matrices ``L`` and ``D``) of matrix
``A``, such that ``L * D * L.T == A``. ``A`` must be a square,
symmetric, positive-definite and non-singular.
This method eliminates the use of square root and ensures that all
the diagonal entries of L are 1.
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
>>> L, D = A.LDLdecomposition()
>>> L
Matrix([
[ 1, 0, 0],
[ 3/5, 1, 0],
[-1/5, 1/3, 1]])
>>> D
Matrix([
[25, 0, 0],
[ 0, 9, 0],
[ 0, 0, 9]])
>>> L * D * L.T == A
True
"""
from .dense import MutableDenseMatrix
if not M.is_square:
raise NonSquareMatrixError("Matrix must be square.")
if hermitian and not M.is_hermitian:
raise ValueError("Matrix must be Hermitian.")
if not hermitian and not M.is_symmetric():
raise ValueError("Matrix must be symmetric.")
dps = _get_intermediate_simp(expand_mul, expand_mul)
Lrowstruc = M.row_structure_symbolic_cholesky()
L = MutableDenseMatrix.eye(M.rows)
D = MutableDenseMatrix.zeros(M.rows, M.cols)
for i in range(len(Lrowstruc)):
for j in Lrowstruc[i]:
if i != j:
L[i, j] = M[i, j]
summ = 0
for p1 in Lrowstruc[i]:
if p1 < j:
for p2 in Lrowstruc[j]:
if p2 < j:
if p1 == p2:
if hermitian:
summ += L[i, p1]*L[j, p1].conjugate()*D[p1, p1]
else:
summ += L[i, p1]*L[j, p1]*D[p1, p1]
else:
break
else:
break
L[i, j] = dps((L[i, j] - summ) / D[j, j])
else: # i == j
D[i, i] = M[i, i]
summ = 0
for k in Lrowstruc[i]:
if k < i:
if hermitian:
summ += L[i, k]*L[i, k].conjugate()*D[k, k]
else:
summ += L[i, k]**2*D[k, k]
else:
break
D[i, i] = dps(D[i, i] - summ)
if hermitian and D[i, i].is_positive is False:
raise NonPositiveDefiniteMatrixError(
"Matrix must be positive-definite")
return M._new(L), M._new(D)
def _LUdecomposition(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False):
"""Returns (L, U, perm) where L is a lower triangular matrix with unit
diagonal, U is an upper triangular matrix, and perm is a list of row
swap index pairs. If A is the original matrix, then
``A = (L*U).permuteBkwd(perm)``, and the row permutation matrix P such
that $P A = L U$ can be computed by ``P = eye(A.rows).permuteFwd(perm)``.
See documentation for LUCombined for details about the keyword argument
rankcheck, iszerofunc, and simpfunc.
Parameters
==========
rankcheck : bool, optional
Determines if this function should detect the rank
deficiency of the matrixis and should raise a
``ValueError``.
iszerofunc : function, optional
A function which determines if a given expression is zero.
The function should be a callable that takes a single
sympy expression and returns a 3-valued boolean value
``True``, ``False``, or ``None``.
It is internally used by the pivot searching algorithm.
See the notes section for a more information about the
pivot searching algorithm.
simpfunc : function or None, optional
A function that simplifies the input.
If this is specified as a function, this function should be
a callable that takes a single sympy expression and returns
an another sympy expression that is algebraically
equivalent.
If ``None``, it indicates that the pivot search algorithm
should not attempt to simplify any candidate pivots.
It is internally used by the pivot searching algorithm.
See the notes section for a more information about the
pivot searching algorithm.
Examples
========
>>> from sympy import Matrix
>>> a = Matrix([[4, 3], [6, 3]])
>>> L, U, _ = a.LUdecomposition()
>>> L
Matrix([
[ 1, 0],
[3/2, 1]])
>>> U
Matrix([
[4, 3],
[0, -3/2]])
See Also
========
sympy.matrices.dense.DenseMatrix.cholesky
sympy.matrices.dense.DenseMatrix.LDLdecomposition
QRdecomposition
LUdecomposition_Simple
LUdecompositionFF
LUsolve
"""
combined, p = M.LUdecomposition_Simple(iszerofunc=iszerofunc,
simpfunc=simpfunc, rankcheck=rankcheck)
# L is lower triangular ``M.rows x M.rows``
# U is upper triangular ``M.rows x M.cols``
# L has unit diagonal. For each column in combined, the subcolumn
# below the diagonal of combined is shared by L.
# If L has more columns than combined, then the remaining subcolumns
# below the diagonal of L are zero.
# The upper triangular portion of L and combined are equal.
def entry_L(i, j):
if i < j:
# Super diagonal entry
return M.zero
elif i == j:
return M.one
elif j < combined.cols:
return combined[i, j]
# Subdiagonal entry of L with no corresponding
# entry in combined
return M.zero
def entry_U(i, j):
return M.zero if i > j else combined[i, j]
L = M._new(combined.rows, combined.rows, entry_L)
U = M._new(combined.rows, combined.cols, entry_U)
return L, U, p
def _LUdecomposition_Simple(M, iszerofunc=_iszero, simpfunc=None,
rankcheck=False):
r"""Compute the PLU decomposition of the matrix.
Parameters
==========
rankcheck : bool, optional
Determines if this function should detect the rank
deficiency of the matrixis and should raise a
``ValueError``.
iszerofunc : function, optional
A function which determines if a given expression is zero.
The function should be a callable that takes a single
sympy expression and returns a 3-valued boolean value
``True``, ``False``, or ``None``.
It is internally used by the pivot searching algorithm.
See the notes section for a more information about the
pivot searching algorithm.
simpfunc : function or None, optional
A function that simplifies the input.
If this is specified as a function, this function should be
a callable that takes a single sympy expression and returns
an another sympy expression that is algebraically
equivalent.
If ``None``, it indicates that the pivot search algorithm
should not attempt to simplify any candidate pivots.
It is internally used by the pivot searching algorithm.
See the notes section for a more information about the
pivot searching algorithm.
Returns
=======
(lu, row_swaps) : (Matrix, list)
If the original matrix is a $m, n$ matrix:
*lu* is a $m, n$ matrix, which contains result of the
decomposition in a compresed form. See the notes section
to see how the matrix is compressed.
*row_swaps* is a $m$-element list where each element is a
pair of row exchange indices.
``A = (L*U).permute_backward(perm)``, and the row
permutation matrix $P$ from the formula $P A = L U$ can be
computed by ``P=eye(A.row).permute_forward(perm)``.
Raises
======
ValueError
Raised if ``rankcheck=True`` and the matrix is found to
be rank deficient during the computation.
Notes
=====
About the PLU decomposition:
PLU decomposition is a generalization of a LU decomposition
which can be extended for rank-deficient matrices.
It can further be generalized for non-square matrices, and this
is the notation that SymPy is using.
PLU decomposition is a decomposition of a $m, n$ matrix $A$ in
the form of $P A = L U$ where
* $L$ is a $m, m$ lower triangular matrix with unit diagonal
entries.
* $U$ is a $m, n$ upper triangular matrix.
* $P$ is a $m, m$ permutation matrix.
So, for a square matrix, the decomposition would look like:
.. math::
L = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
L_{1, 0} & 1 & 0 & \cdots & 0 \\
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1
\end{bmatrix}
.. math::
U = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & U_{n-1, n-1}
\end{bmatrix}
And for a matrix with more rows than the columns,
the decomposition would look like:
.. math::
L = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 & 0 & \cdots & 0 \\
L_{1, 0} & 1 & 0 & \cdots & 0 & 0 & \cdots & 0 \\
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 & 0 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots
& \vdots \\
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 & 0
& \cdots & 0 \\
L_{n, 0} & L_{n, 1} & L_{n, 2} & \cdots & L_{n, n-1} & 1
& \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots
& \ddots & \vdots \\
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1}
& 0 & \cdots & 1 \\
\end{bmatrix}
.. math::
U = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & U_{n-1, n-1} \\
0 & 0 & 0 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 0
\end{bmatrix}
Finally, for a matrix with more columns than the rows, the
decomposition would look like:
.. math::
L = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
L_{1, 0} & 1 & 0 & \cdots & 0 \\
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & 1
\end{bmatrix}
.. math::
U = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1}
& \cdots & U_{0, n-1} \\
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1}
& \cdots & U_{1, n-1} \\
0 & 0 & U_{2, 2} & \cdots & U_{2, m-1}
& \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots
& \cdots & \vdots \\
0 & 0 & 0 & \cdots & U_{m-1, m-1}
& \cdots & U_{m-1, n-1} \\
\end{bmatrix}
About the compressed LU storage:
The results of the decomposition are often stored in compressed
forms rather than returning $L$ and $U$ matrices individually.
It may be less intiuitive, but it is commonly used for a lot of
numeric libraries because of the efficiency.
The storage matrix is defined as following for this specific
method:
* The subdiagonal elements of $L$ are stored in the subdiagonal
portion of $LU$, that is $LU_{i, j} = L_{i, j}$ whenever
$i > j$.
* The elements on the diagonal of $L$ are all 1, and are not
explicitly stored.
* $U$ is stored in the upper triangular portion of $LU$, that is
$LU_{i, j} = U_{i, j}$ whenever $i <= j$.
* For a case of $m > n$, the right side of the $L$ matrix is
trivial to store.
* For a case of $m < n$, the below side of the $U$ matrix is
trivial to store.
So, for a square matrix, the compressed output matrix would be:
.. math::
LU = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1}
\end{bmatrix}
For a matrix with more rows than the columns, the compressed
output matrix would be:
.. math::
LU = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots
& U_{n-1, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots
& L_{m-1, n-1} \\
\end{bmatrix}
For a matrix with more columns than the rows, the compressed
output matrix would be:
.. math::
LU = \begin{bmatrix}
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1}
& \cdots & U_{0, n-1} \\
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1}
& \cdots & U_{1, n-1} \\
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, m-1}
& \cdots & U_{2, n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots
& \cdots & \vdots \\
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & U_{m-1, m-1}
& \cdots & U_{m-1, n-1} \\
\end{bmatrix}
About the pivot searching algorithm:
When a matrix contains symbolic entries, the pivot search algorithm
differs from the case where every entry can be categorized as zero or
nonzero.
The algorithm searches column by column through the submatrix whose
top left entry coincides with the pivot position.
If it exists, the pivot is the first entry in the current search
column that iszerofunc guarantees is nonzero.
If no such candidate exists, then each candidate pivot is simplified
if simpfunc is not None.
The search is repeated, with the difference that a candidate may be
the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero.
In the second search the pivot is the first candidate that
iszerofunc can guarantee is nonzero.
If no such candidate exists, then the pivot is the first candidate
for which iszerofunc returns None.
If no such candidate exists, then the search is repeated in the next
column to the right.
The pivot search algorithm differs from the one in ``rref()``, which
relies on ``_find_reasonable_pivot()``.
Future versions of ``LUdecomposition_simple()`` may use
``_find_reasonable_pivot()``.
See Also
========
sympy.matrices.matrices.MatrixBase.LUdecomposition
LUdecompositionFF
LUsolve
"""
if rankcheck:
# https://github.com/sympy/sympy/issues/9796
pass
if M.rows == 0 or M.cols == 0:
# Define LU decomposition of a matrix with no entries as a matrix
# of the same dimensions with all zero entries.
return M.zeros(M.rows, M.cols), []
dps = _get_intermediate_simp()
lu = M.as_mutable()
row_swaps = []
pivot_col = 0
for pivot_row in range(0, lu.rows - 1):
# Search for pivot. Prefer entry that iszeropivot determines
# is nonzero, over entry that iszeropivot cannot guarantee
# is zero.
# XXX ``_find_reasonable_pivot`` uses slow zero testing. Blocked by bug #10279
# Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc
# to _find_reasonable_pivot().
# In pass 3 of _find_reasonable_pivot(), the predicate in ``if x.equals(S.Zero):``
# calls sympy.simplify(), and not the simplification function passed in via
# the keyword argument simpfunc.
iszeropivot = True
while pivot_col != M.cols and iszeropivot:
sub_col = (lu[r, pivot_col] for r in range(pivot_row, M.rows))
pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\
_find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc)
iszeropivot = pivot_value is None
if iszeropivot:
# All candidate pivots in this column are zero.
# Proceed to next column.
pivot_col += 1
if rankcheck and pivot_col != pivot_row:
# All entries including and below the pivot position are
# zero, which indicates that the rank of the matrix is
# strictly less than min(num rows, num cols)
# Mimic behavior of previous implementation, by throwing a
# ValueError.
raise ValueError("Rank of matrix is strictly less than"
" number of rows or columns."
" Pass keyword argument"
" rankcheck=False to compute"
" the LU decomposition of this matrix.")
candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset
if candidate_pivot_row is None and iszeropivot:
# If candidate_pivot_row is None and iszeropivot is True
# after pivot search has completed, then the submatrix
# below and to the right of (pivot_row, pivot_col) is
# all zeros, indicating that Gaussian elimination is
# complete.
return lu, row_swaps
# Update entries simplified during pivot search.
for offset, val in ind_simplified_pairs:
lu[pivot_row + offset, pivot_col] = val
if pivot_row != candidate_pivot_row:
# Row swap book keeping:
# Record which rows were swapped.
# Update stored portion of L factor by multiplying L on the
# left and right with the current permutation.
# Swap rows of U.
row_swaps.append([pivot_row, candidate_pivot_row])
# Update L.
lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \
lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row]
# Swap pivot row of U with candidate pivot row.
lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \
lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols]
# Introduce zeros below the pivot by adding a multiple of the
# pivot row to a row under it, and store the result in the
# row under it.
# Only entries in the target row whose index is greater than
# start_col may be nonzero.
start_col = pivot_col + 1
for row in range(pivot_row + 1, lu.rows):
# Store factors of L in the subcolumn below
# (pivot_row, pivot_row).
lu[row, pivot_row] = \
dps(lu[row, pivot_col]/lu[pivot_row, pivot_col])
# Form the linear combination of the pivot row and the current
# row below the pivot row that zeros the entries below the pivot.
# Employing slicing instead of a loop here raises
# NotImplementedError: Cannot add Zero to MutableSparseMatrix
# in sympy/matrices/tests/test_sparse.py.
# c = pivot_row + 1 if pivot_row == pivot_col else pivot_col
for c in range(start_col, lu.cols):
lu[row, c] = dps(lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c])
if pivot_row != pivot_col:
# matrix rank < min(num rows, num cols),
# so factors of L are not stored directly below the pivot.
# These entries are zero by construction, so don't bother
# computing them.
for row in range(pivot_row + 1, lu.rows):
lu[row, pivot_col] = M.zero
pivot_col += 1
if pivot_col == lu.cols:
# All candidate pivots are zero implies that Gaussian
# elimination is complete.
return lu, row_swaps
if rankcheck:
if iszerofunc(
lu[Min(lu.rows, lu.cols) - 1, Min(lu.rows, lu.cols) - 1]):
raise ValueError("Rank of matrix is strictly less than"
" number of rows or columns."
" Pass keyword argument"
" rankcheck=False to compute"
" the LU decomposition of this matrix.")
return lu, row_swaps
def _LUdecompositionFF(M):
"""Compute a fraction-free LU decomposition.
Returns 4 matrices P, L, D, U such that PA = L D**-1 U.
If the elements of the matrix belong to some integral domain I, then all
elements of L, D and U are guaranteed to belong to I.
See Also
========
sympy.matrices.matrices.MatrixBase.LUdecomposition
LUdecomposition_Simple
LUsolve
References
==========
.. [1] W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms
for LU and QR factors". Frontiers in Computer Science in China,
Vol 2, no. 1, pp. 67-80, 2008.
"""
from sympy.matrices import SparseMatrix
zeros = SparseMatrix.zeros
eye = SparseMatrix.eye
n, m = M.rows, M.cols
U, L, P = M.as_mutable(), eye(n), eye(n)
DD = zeros(n, n)
oldpivot = 1
for k in range(n - 1):
if U[k, k] == 0:
for kpivot in range(k + 1, n):
if U[kpivot, k]:
break
else:
raise ValueError("Matrix is not full rank")
U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:]
L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k]
P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :]
L [k, k] = Ukk = U[k, k]
DD[k, k] = oldpivot * Ukk
for i in range(k + 1, n):
L[i, k] = Uik = U[i, k]
for j in range(k + 1, m):
U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot
U[i, k] = 0
oldpivot = Ukk
DD[n - 1, n - 1] = oldpivot
return P, L, DD, U
def _singular_value_decomposition(A):
r"""Returns a Condensed Singular Value decomposition.
Explanation
===========
A Singular Value decomposition is a decomposition in the form $A = U \Sigma V$
where
- $U, V$ are column orthogonal matrix.
- $\Sigma$ is a diagonal matrix, where the main diagonal contains singular
values of matrix A.
A column orthogonal matrix satisfies
$\mathbb{I} = U^H U$ while a full orthogonal matrix satisfies
relation $\mathbb{I} = U U^H = U^H U$ where $\mathbb{I}$ is an identity
matrix with matching dimensions.
For matrices which are not square or are rank-deficient, it is
sufficient to return a column orthogonal matrix because augmenting
them may introduce redundant computations.
In condensed Singular Value Decomposition we only return column orthognal
matrices because of this reason
If you want to augment the results to return a full orthogonal
decomposition, you should use the following procedures.
- Augment the $U , V$ matrices with columns that are orthogonal to every
other columns and make it square.
- Augument the $\Sigma$ matrix with zero rows to make it have the same
shape as the original matrix.
The procedure will be illustrated in the examples section.
Examples
========
we take a full rank matrix first:
>>> from sympy import Matrix
>>> A = Matrix([[1, 2],[2,1]])
>>> U, S, V = A.singular_value_decomposition()
>>> U
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> S
Matrix([
[1, 0],
[0, 3]])
>>> V
Matrix([
[-sqrt(2)/2, sqrt(2)/2],
[ sqrt(2)/2, sqrt(2)/2]])
If a matrix if square and full rank both U, V
are orthogonal in both directions
>>> U * U.H
Matrix([
[1, 0],
[0, 1]])
>>> U.H * U
Matrix([
[1, 0],
[0, 1]])
>>> V * V.H
Matrix([
[1, 0],
[0, 1]])
>>> V.H * V
Matrix([
[1, 0],
[0, 1]])
>>> A == U * S * V.H
True
>>> C = Matrix([
... [1, 0, 0, 0, 2],
... [0, 0, 3, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 2, 0, 0, 0],
... ])
>>> U, S, V = C.singular_value_decomposition()
>>> V.H * V
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> V * V.H
Matrix([
[1/5, 0, 0, 0, 2/5],
[ 0, 1, 0, 0, 0],
[ 0, 0, 1, 0, 0],
[ 0, 0, 0, 0, 0],
[2/5, 0, 0, 0, 4/5]])
If you want to augment the results to be a full orthogonal
decomposition, you should augment $V$ with an another orthogonal
column.
You are able to append an arbitrary standard basis that are linearly
independent to every other columns and you can run the Gram-Schmidt
process to make them augmented as orthogonal basis.
>>> V_aug = V.row_join(Matrix([[0,0,0,0,1],
... [0,0,0,1,0]]).H)
>>> V_aug = V_aug.QRdecomposition()[0]
>>> V_aug
Matrix([
[0, sqrt(5)/5, 0, -2*sqrt(5)/5, 0],
[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 1],
[0, 2*sqrt(5)/5, 0, sqrt(5)/5, 0]])
>>> V_aug.H * V_aug
Matrix([
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
>>> V_aug * V_aug.H
Matrix([
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
Similarly we augment U
>>> U_aug = U.row_join(Matrix([0,0,1,0]))
>>> U_aug = U_aug.QRdecomposition()[0]
>>> U_aug
Matrix([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0]])
>>> U_aug.H * U_aug
Matrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
>>> U_aug * U_aug.H
Matrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
We add 2 zero columns and one row to S
>>> S_aug = S.col_join(Matrix([[0,0,0]]))
>>> S_aug = S_aug.row_join(Matrix([[0,0,0,0],
... [0,0,0,0]]).H)
>>> S_aug
Matrix([
[2, 0, 0, 0, 0],
[0, sqrt(5), 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 0, 0]])
>>> U_aug * S_aug * V_aug.H == C
True
"""
AH = A.H
m, n = A.shape
if m >= n:
V, S = (AH * A).diagonalize()
ranked = []
for i, x in enumerate(S.diagonal()):
if not x.is_zero:
ranked.append(i)
V = V[:, ranked]
Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked]
S = S.zeros(len(Singular_vals))
for i in range(len(Singular_vals)):
S[i, i] = Singular_vals[i]
V, _ = V.QRdecomposition()
U = A * V * S.inv()
else:
U, S = (A * AH).diagonalize()
ranked = []
for i, x in enumerate(S.diagonal()):
if not x.is_zero:
ranked.append(i)
U = U[:, ranked]
Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked]
S = S.zeros(len(Singular_vals))
for i in range(len(Singular_vals)):
S[i, i] = Singular_vals[i]
U, _ = U.QRdecomposition()
V = AH * U * S.inv()
return U, S, V
def _QRdecomposition_optional(M, normalize=True):
def dot(u, v):
return u.dot(v, hermitian=True)
dps = _get_intermediate_simp(expand_mul, expand_mul)
A = M.as_mutable()
ranked = list()
Q = A
R = A.zeros(A.cols)
for j in range(A.cols):
for i in range(j):
if Q[:, i].is_zero_matrix:
continue
R[i, j] = dot(Q[:, i], Q[:, j]) / dot(Q[:, i], Q[:, i])
R[i, j] = dps(R[i, j])
Q[:, j] -= Q[:, i] * R[i, j]
Q[:, j] = dps(Q[:, j])
if Q[:, j].is_zero_matrix is False:
ranked.append(j)
R[j, j] = M.one
Q = Q.extract(range(Q.rows), ranked)
R = R.extract(ranked, range(R.cols))
if normalize:
# Normalization
for i in range(Q.cols):
norm = Q[:, i].norm()
Q[:, i] /= norm
R[i, :] *= norm
return M.__class__(Q), M.__class__(R)
def _QRdecomposition(M):
r"""Returns a QR decomposition.
Explanation
===========
A QR decomposition is a decomposition in the form $A = Q R$
where
- $Q$ is a column orthogonal matrix.
- $R$ is a upper triangular (trapezoidal) matrix.
A column orthogonal matrix satisfies
$\mathbb{I} = Q^H Q$ while a full orthogonal matrix satisfies
relation $\mathbb{I} = Q Q^H = Q^H Q$ where $I$ is an identity
matrix with matching dimensions.
For matrices which are not square or are rank-deficient, it is
sufficient to return a column orthogonal matrix because augmenting
them may introduce redundant computations.
And an another advantage of this is that you can easily inspect the
matrix rank by counting the number of columns of $Q$.
If you want to augment the results to return a full orthogonal
decomposition, you should use the following procedures.
- Augment the $Q$ matrix with columns that are orthogonal to every
other columns and make it square.
- Augument the $R$ matrix with zero rows to make it have the same
shape as the original matrix.
The procedure will be illustrated in the examples section.
Examples
========
A full rank matrix example:
>>> from sympy import Matrix
>>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]])
>>> Q, R = A.QRdecomposition()
>>> Q
Matrix([
[ 6/7, -69/175, -58/175],
[ 3/7, 158/175, 6/175],
[-2/7, 6/35, -33/35]])
>>> R
Matrix([
[14, 21, -14],
[ 0, 175, -70],
[ 0, 0, 35]])
If the matrix is square and full rank, the $Q$ matrix becomes
orthogonal in both directions, and needs no augmentation.
>>> Q * Q.H
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> Q.H * Q
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> A == Q*R
True
A rank deficient matrix example:
>>> A = Matrix([[12, -51, 0], [6, 167, 0], [-4, 24, 0]])
>>> Q, R = A.QRdecomposition()
>>> Q
Matrix([
[ 6/7, -69/175],
[ 3/7, 158/175],
[-2/7, 6/35]])
>>> R
Matrix([
[14, 21, 0],
[ 0, 175, 0]])
QRdecomposition might return a matrix Q that is rectangular.
In this case the orthogonality condition might be satisfied as
$\mathbb{I} = Q.H*Q$ but not in the reversed product
$\mathbb{I} = Q * Q.H$.
>>> Q.H * Q
Matrix([
[1, 0],
[0, 1]])
>>> Q * Q.H
Matrix([
[27261/30625, 348/30625, -1914/6125],
[ 348/30625, 30589/30625, 198/6125],
[ -1914/6125, 198/6125, 136/1225]])
If you want to augment the results to be a full orthogonal
decomposition, you should augment $Q$ with an another orthogonal
column.
You are able to append an arbitrary standard basis that are linearly
independent to every other columns and you can run the Gram-Schmidt
process to make them augmented as orthogonal basis.
>>> Q_aug = Q.row_join(Matrix([0, 0, 1]))
>>> Q_aug = Q_aug.QRdecomposition()[0]
>>> Q_aug
Matrix([
[ 6/7, -69/175, 58/175],
[ 3/7, 158/175, -6/175],
[-2/7, 6/35, 33/35]])
>>> Q_aug.H * Q_aug
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> Q_aug * Q_aug.H
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
Augmenting the $R$ matrix with zero row is straightforward.
>>> R_aug = R.col_join(Matrix([[0, 0, 0]]))
>>> R_aug
Matrix([
[14, 21, 0],
[ 0, 175, 0],
[ 0, 0, 0]])
>>> Q_aug * R_aug == A
True
A zero matrix example:
>>> from sympy import Matrix
>>> A = Matrix.zeros(3, 4)
>>> Q, R = A.QRdecomposition()
They may return matrices with zero rows and columns.
>>> Q
Matrix(3, 0, [])
>>> R
Matrix(0, 4, [])
>>> Q*R
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
As the same augmentation rule described above, $Q$ can be augmented
with columns of an identity matrix and $R$ can be augmented with
rows of a zero matrix.
>>> Q_aug = Q.row_join(Matrix.eye(3))
>>> R_aug = R.col_join(Matrix.zeros(3, 4))
>>> Q_aug * Q_aug.T
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> R_aug
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> Q_aug * R_aug == A
True
See Also
========
sympy.matrices.dense.DenseMatrix.cholesky
sympy.matrices.dense.DenseMatrix.LDLdecomposition
sympy.matrices.matrices.MatrixBase.LUdecomposition
QRsolve
"""
return _QRdecomposition_optional(M, normalize=True)
def _upper_hessenberg_decomposition(A):
"""Converts a matrix into Hessenberg matrix H
Returns 2 matrices H, P s.t.
$P H P^{T} = A$, where H is an upper hessenberg matrix
and P is an orthogonal matrix
Examples
========
>>> from sympy import Matrix
>>> A = Matrix([
... [1,2,3],
... [-3,5,6],
... [4,-8,9],
... ])
>>> H, P = A.upper_hessenberg_decomposition()
>>> H
Matrix([
[1, 6/5, 17/5],
[5, 213/25, -134/25],
[0, 216/25, 137/25]])
>>> P
Matrix([
[1, 0, 0],
[0, -3/5, 4/5],
[0, 4/5, 3/5]])
>>> P * H * P.H == A
True
References
==========
.. [#] https://mathworld.wolfram.com/HessenbergDecomposition.html
"""
M = A.as_mutable()
if not M.is_square:
raise NonSquareMatrixError("Matrix must be square.")
n = M.cols
P = M.eye(n)
H = M
for j in range(n - 2):
u = H[j + 1:, j]
if u[1:, :].is_zero_matrix:
continue
if sign(u[0]) != 0:
u[0] = u[0] + sign(u[0]) * u.norm()
else:
u[0] = u[0] + u.norm()
v = u / u.norm()
H[j + 1:, :] = H[j + 1:, :] - 2 * v * (v.H * H[j + 1:, :])
H[:, j + 1:] = H[:, j + 1:] - (H[:, j + 1:] * (2 * v)) * v.H
P[:, j + 1:] = P[:, j + 1:] - (P[:, j + 1:] * (2 * v)) * v.H
return H, P
|
7a8e5c60045bf64333a8217e05d7628d937b171aa946199ef21d544b4f9354bb | """A module that handles matrices.
Includes functions for fast creating matrices like zero, one/eye, random
matrix, etc.
"""
from .common import ShapeError, NonSquareMatrixError, MatrixKind
from .dense import (
GramSchmidt, casoratian, diag, eye, hessian, jordan_cell,
list2numpy, matrix2numpy, matrix_multiply_elementwise, ones,
randMatrix, rot_axis1, rot_axis2, rot_axis3, symarray, wronskian,
zeros)
from .dense import MutableDenseMatrix
from .matrices import DeferredVector, MatrixBase
Matrix = MutableMatrix = MutableDenseMatrix
from .sparse import MutableSparseMatrix
from .sparsetools import banded
from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix
ImmutableMatrix = ImmutableDenseMatrix
SparseMatrix = MutableSparseMatrix
from .expressions import (
MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity,
Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace,
Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint,
hadamard_product, HadamardProduct, HadamardPower, Determinant, det,
diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace,
DotProduct, kronecker_product, KroneckerProduct,
PermutationMatrix, MatrixPermute, MatrixSet, Permanent, per)
from .utilities import dotprodsimp
__all__ = [
'ShapeError', 'NonSquareMatrixError', 'MatrixKind',
'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell',
'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones',
'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray',
'wronskian', 'zeros',
'MutableDenseMatrix',
'DeferredVector', 'MatrixBase',
'Matrix', 'MutableMatrix',
'MutableSparseMatrix',
'banded',
'ImmutableDenseMatrix', 'ImmutableSparseMatrix',
'ImmutableMatrix', 'SparseMatrix',
'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix',
'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr',
'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix',
'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint',
'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant',
'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix',
'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product',
'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet',
'Permanent', 'per',
'dotprodsimp',
]
|
1b3ccf5277f86de3e4334fd5c2461d13e27e3d3ea82cde9454ae09f66e0e6347 | """
Basic methods common to all matrices to be used
when creating more advanced matrices (e.g., matrices over rings,
etc.).
"""
from collections import defaultdict
from collections.abc import Iterable
from inspect import isfunction
from functools import reduce
from sympy.core.logic import FuzzyBool
from sympy.assumptions.refine import refine
from sympy.core import SympifyError, Add
from sympy.core.basic import Atom
from sympy.core.compatibility import as_int, is_sequence
from sympy.core.decorators import call_highest_priority
from sympy.core.kind import Kind, NumberKind
from sympy.core.logic import fuzzy_and
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions import Abs
from sympy.polys.polytools import Poly
from sympy.simplify import simplify as _simplify
from sympy.simplify.simplify import dotprodsimp as _dotprodsimp
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
from sympy.tensor.array import NDimArray
from .utilities import _get_intermediate_simp_bool
class MatrixError(Exception):
pass
class ShapeError(ValueError, MatrixError):
"""Wrong matrix shape"""
pass
class NonSquareMatrixError(ShapeError):
pass
class NonInvertibleMatrixError(ValueError, MatrixError):
"""The matrix in not invertible (division by multidimensional zero error)."""
pass
class NonPositiveDefiniteMatrixError(ValueError, MatrixError):
"""The matrix is not a positive-definite matrix."""
pass
class MatrixRequired:
"""All subclasses of matrix objects must implement the
required matrix properties listed here."""
rows = None # type: int
cols = None # type: int
_simplify = None
@classmethod
def _new(cls, *args, **kwargs):
"""`_new` must, at minimum, be callable as
`_new(rows, cols, mat) where mat is a flat list of the
elements of the matrix."""
raise NotImplementedError("Subclasses must implement this.")
def __eq__(self, other):
raise NotImplementedError("Subclasses must implement this.")
def __getitem__(self, key):
"""Implementations of __getitem__ should accept ints, in which
case the matrix is indexed as a flat list, tuples (i,j) in which
case the (i,j) entry is returned, slices, or mixed tuples (a,b)
where a and b are any combintion of slices and integers."""
raise NotImplementedError("Subclasses must implement this.")
def __len__(self):
"""The total number of entries in the matrix."""
raise NotImplementedError("Subclasses must implement this.")
@property
def shape(self):
raise NotImplementedError("Subclasses must implement this.")
class MatrixShaping(MatrixRequired):
"""Provides basic matrix shaping and extracting of submatrices"""
def _eval_col_del(self, col):
def entry(i, j):
return self[i, j] if j < col else self[i, j + 1]
return self._new(self.rows, self.cols - 1, entry)
def _eval_col_insert(self, pos, other):
def entry(i, j):
if j < pos:
return self[i, j]
elif pos <= j < pos + other.cols:
return other[i, j - pos]
return self[i, j - other.cols]
return self._new(self.rows, self.cols + other.cols,
lambda i, j: entry(i, j))
def _eval_col_join(self, other):
rows = self.rows
def entry(i, j):
if i < rows:
return self[i, j]
return other[i - rows, j]
return classof(self, other)._new(self.rows + other.rows, self.cols,
lambda i, j: entry(i, j))
def _eval_extract(self, rowsList, colsList):
mat = list(self)
cols = self.cols
indices = (i * cols + j for i in rowsList for j in colsList)
return self._new(len(rowsList), len(colsList),
list(mat[i] for i in indices))
def _eval_get_diag_blocks(self):
sub_blocks = []
def recurse_sub_blocks(M):
i = 1
while i <= M.shape[0]:
if i == 1:
to_the_right = M[0, i:]
to_the_bottom = M[i:, 0]
else:
to_the_right = M[:i, i:]
to_the_bottom = M[i:, :i]
if any(to_the_right) or any(to_the_bottom):
i += 1
continue
else:
sub_blocks.append(M[:i, :i])
if M.shape == M[:i, :i].shape:
return
else:
recurse_sub_blocks(M[i:, i:])
return
recurse_sub_blocks(self)
return sub_blocks
def _eval_row_del(self, row):
def entry(i, j):
return self[i, j] if i < row else self[i + 1, j]
return self._new(self.rows - 1, self.cols, entry)
def _eval_row_insert(self, pos, other):
entries = list(self)
insert_pos = pos * self.cols
entries[insert_pos:insert_pos] = list(other)
return self._new(self.rows + other.rows, self.cols, entries)
def _eval_row_join(self, other):
cols = self.cols
def entry(i, j):
if j < cols:
return self[i, j]
return other[i, j - cols]
return classof(self, other)._new(self.rows, self.cols + other.cols,
lambda i, j: entry(i, j))
def _eval_tolist(self):
return [list(self[i,:]) for i in range(self.rows)]
def _eval_todok(self):
dok = {}
rows, cols = self.shape
for i in range(rows):
for j in range(cols):
val = self[i, j]
if val != self.zero:
dok[i, j] = val
return dok
def _eval_vec(self):
rows = self.rows
def entry(n, _):
# we want to read off the columns first
j = n // rows
i = n - j * rows
return self[i, j]
return self._new(len(self), 1, entry)
def _eval_vech(self, diagonal):
c = self.cols
v = []
if diagonal:
for j in range(c):
for i in range(j, c):
v.append(self[i, j])
else:
for j in range(c):
for i in range(j + 1, c):
v.append(self[i, j])
return self._new(len(v), 1, v)
def col_del(self, col):
"""Delete the specified column."""
if col < 0:
col += self.cols
if not 0 <= col < self.cols:
raise IndexError("Column {} is out of range.".format(col))
return self._eval_col_del(col)
def col_insert(self, pos, other):
"""Insert one or more columns at the given column position.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.col_insert(1, V)
Matrix([
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]])
See Also
========
col
row_insert
"""
# Allows you to build a matrix even if it is null matrix
if not self:
return type(self)(other)
pos = as_int(pos)
if pos < 0:
pos = self.cols + pos
if pos < 0:
pos = 0
elif pos > self.cols:
pos = self.cols
if self.rows != other.rows:
raise ShapeError(
"`self` and `other` must have the same number of rows.")
return self._eval_col_insert(pos, other)
def col_join(self, other):
"""Concatenates two matrices along self's last and other's first row.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.col_join(V)
Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 1, 1]])
See Also
========
col
row_join
"""
# A null matrix can always be stacked (see #10770)
if self.rows == 0 and self.cols != other.cols:
return self._new(0, other.cols, []).col_join(other)
if self.cols != other.cols:
raise ShapeError(
"`self` and `other` must have the same number of columns.")
return self._eval_col_join(other)
def col(self, j):
"""Elementary column selector.
Examples
========
>>> from sympy import eye
>>> eye(2).col(0)
Matrix([
[1],
[0]])
See Also
========
row
sympy.matrices.dense.MutableDenseMatrix.col_op
sympy.matrices.dense.MutableDenseMatrix.col_swap
col_del
col_join
col_insert
"""
return self[:, j]
def extract(self, rowsList, colsList):
"""Return a submatrix by specifying a list of rows and columns.
Negative indices can be given. All indices must be in the range
-n <= i < n where n is the number of rows or columns.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(4, 3, range(12))
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]])
>>> m.extract([0, 1, 3], [0, 1])
Matrix([
[0, 1],
[3, 4],
[9, 10]])
Rows or columns can be repeated:
>>> m.extract([0, 0, 1], [-1])
Matrix([
[2],
[2],
[5]])
Every other row can be taken by using range to provide the indices:
>>> m.extract(range(0, m.rows, 2), [-1])
Matrix([
[2],
[8]])
RowsList or colsList can also be a list of booleans, in which case
the rows or columns corresponding to the True values will be selected:
>>> m.extract([0, 1, 2, 3], [True, False, True])
Matrix([
[0, 2],
[3, 5],
[6, 8],
[9, 11]])
"""
if not is_sequence(rowsList) or not is_sequence(colsList):
raise TypeError("rowsList and colsList must be iterable")
# ensure rowsList and colsList are lists of integers
if rowsList and all(isinstance(i, bool) for i in rowsList):
rowsList = [index for index, item in enumerate(rowsList) if item]
if colsList and all(isinstance(i, bool) for i in colsList):
colsList = [index for index, item in enumerate(colsList) if item]
# ensure everything is in range
rowsList = [a2idx(k, self.rows) for k in rowsList]
colsList = [a2idx(k, self.cols) for k in colsList]
return self._eval_extract(rowsList, colsList)
def get_diag_blocks(self):
"""Obtains the square sub-matrices on the main diagonal of a square matrix.
Useful for inverting symbolic matrices or solving systems of
linear equations which may be decoupled by having a block diagonal
structure.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import x, y, z
>>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
>>> a1, a2, a3 = A.get_diag_blocks()
>>> a1
Matrix([
[1, 3],
[y, z**2]])
>>> a2
Matrix([[x]])
>>> a3
Matrix([[0]])
"""
return self._eval_get_diag_blocks()
@classmethod
def hstack(cls, *args):
"""Return a matrix formed by joining args horizontally (i.e.
by repeated application of row_join).
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> Matrix.hstack(eye(2), 2*eye(2))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]])
"""
if len(args) == 0:
return cls._new()
kls = type(args[0])
return reduce(kls.row_join, args)
def reshape(self, rows, cols):
"""Reshape the matrix. Total number of elements must remain the same.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 3, lambda i, j: 1)
>>> m
Matrix([
[1, 1, 1],
[1, 1, 1]])
>>> m.reshape(1, 6)
Matrix([[1, 1, 1, 1, 1, 1]])
>>> m.reshape(3, 2)
Matrix([
[1, 1],
[1, 1],
[1, 1]])
"""
if self.rows * self.cols != rows * cols:
raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
return self._new(rows, cols, lambda i, j: self[i * cols + j])
def row_del(self, row):
"""Delete the specified row."""
if row < 0:
row += self.rows
if not 0 <= row < self.rows:
raise IndexError("Row {} is out of range.".format(row))
return self._eval_row_del(row)
def row_insert(self, pos, other):
"""Insert one or more rows at the given row position.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.row_insert(1, V)
Matrix([
[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
See Also
========
row
col_insert
"""
# Allows you to build a matrix even if it is null matrix
if not self:
return self._new(other)
pos = as_int(pos)
if pos < 0:
pos = self.rows + pos
if pos < 0:
pos = 0
elif pos > self.rows:
pos = self.rows
if self.cols != other.cols:
raise ShapeError(
"`self` and `other` must have the same number of columns.")
return self._eval_row_insert(pos, other)
def row_join(self, other):
"""Concatenates two matrices along self's last and rhs's first column
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.row_join(V)
Matrix([
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]])
See Also
========
row
col_join
"""
# A null matrix can always be stacked (see #10770)
if self.cols == 0 and self.rows != other.rows:
return self._new(other.rows, 0, []).row_join(other)
if self.rows != other.rows:
raise ShapeError(
"`self` and `rhs` must have the same number of rows.")
return self._eval_row_join(other)
def diagonal(self, k=0):
"""Returns the kth diagonal of self. The main diagonal
corresponds to `k=0`; diagonals above and below correspond to
`k > 0` and `k < 0`, respectively. The values of `self[i, j]`
for which `j - i = k`, are returned in order of increasing
`i + j`, starting with `i + j = |k|`.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(3, 3, lambda i, j: j - i); m
Matrix([
[ 0, 1, 2],
[-1, 0, 1],
[-2, -1, 0]])
>>> _.diagonal()
Matrix([[0, 0, 0]])
>>> m.diagonal(1)
Matrix([[1, 1]])
>>> m.diagonal(-2)
Matrix([[-2]])
Even though the diagonal is returned as a Matrix, the element
retrieval can be done with a single index:
>>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1]
2
See Also
========
diag - to create a diagonal matrix
"""
rv = []
k = as_int(k)
r = 0 if k > 0 else -k
c = 0 if r else k
while True:
if r == self.rows or c == self.cols:
break
rv.append(self[r, c])
r += 1
c += 1
if not rv:
raise ValueError(filldedent('''
The %s diagonal is out of range [%s, %s]''' % (
k, 1 - self.rows, self.cols - 1)))
return self._new(1, len(rv), rv)
def row(self, i):
"""Elementary row selector.
Examples
========
>>> from sympy import eye
>>> eye(2).row(0)
Matrix([[1, 0]])
See Also
========
col
sympy.matrices.dense.MutableDenseMatrix.row_op
sympy.matrices.dense.MutableDenseMatrix.row_swap
row_del
row_join
row_insert
"""
return self[i, :]
@property
def shape(self):
"""The shape (dimensions) of the matrix as the 2-tuple (rows, cols).
Examples
========
>>> from sympy.matrices import zeros
>>> M = zeros(2, 3)
>>> M.shape
(2, 3)
>>> M.rows
2
>>> M.cols
3
"""
return (self.rows, self.cols)
def todok(self):
"""Return the matrix as dictionary of keys.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix.eye(3)
>>> M.todok()
{(0, 0): 1, (1, 1): 1, (2, 2): 1}
"""
return self._eval_todok()
def tolist(self):
"""Return the Matrix as a nested Python list.
Examples
========
>>> from sympy import Matrix, ones
>>> m = Matrix(3, 3, range(9))
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> m.tolist()
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> ones(3, 0).tolist()
[[], [], []]
When there are no rows then it will not be possible to tell how
many columns were in the original matrix:
>>> ones(0, 3).tolist()
[]
"""
if not self.rows:
return []
if not self.cols:
return [[] for i in range(self.rows)]
return self._eval_tolist()
def vec(self):
"""Return the Matrix converted into a one column matrix by stacking columns
Examples
========
>>> from sympy import Matrix
>>> m=Matrix([[1, 3], [2, 4]])
>>> m
Matrix([
[1, 3],
[2, 4]])
>>> m.vec()
Matrix([
[1],
[2],
[3],
[4]])
See Also
========
vech
"""
return self._eval_vec()
def vech(self, diagonal=True, check_symmetry=True):
"""Reshapes the matrix into a column vector by stacking the
elements in the lower triangle.
Parameters
==========
diagonal : bool, optional
If ``True``, it includes the diagonal elements.
check_symmetry : bool, optional
If ``True``, it checks whether the matrix is symmetric.
Examples
========
>>> from sympy import Matrix
>>> m=Matrix([[1, 2], [2, 3]])
>>> m
Matrix([
[1, 2],
[2, 3]])
>>> m.vech()
Matrix([
[1],
[2],
[3]])
>>> m.vech(diagonal=False)
Matrix([[2]])
Notes
=====
This should work for symmetric matrices and ``vech`` can
represent symmetric matrices in vector form with less size than
``vec``.
See Also
========
vec
"""
if not self.is_square:
raise NonSquareMatrixError
if check_symmetry and not self.is_symmetric():
raise ValueError("The matrix is not symmetric.")
return self._eval_vech(diagonal)
@classmethod
def vstack(cls, *args):
"""Return a matrix formed by joining args vertically (i.e.
by repeated application of col_join).
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> Matrix.vstack(eye(2), 2*eye(2))
Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]])
"""
if len(args) == 0:
return cls._new()
kls = type(args[0])
return reduce(kls.col_join, args)
class MatrixSpecial(MatrixRequired):
"""Construction of special matrices"""
@classmethod
def _eval_diag(cls, rows, cols, diag_dict):
"""diag_dict is a defaultdict containing
all the entries of the diagonal matrix."""
def entry(i, j):
return diag_dict[(i, j)]
return cls._new(rows, cols, entry)
@classmethod
def _eval_eye(cls, rows, cols):
def entry(i, j):
return cls.one if i == j else cls.zero
return cls._new(rows, cols, entry)
@classmethod
def _eval_jordan_block(cls, rows, cols, eigenvalue, band='upper'):
if band == 'lower':
def entry(i, j):
if i == j:
return eigenvalue
elif j + 1 == i:
return cls.one
return cls.zero
else:
def entry(i, j):
if i == j:
return eigenvalue
elif i + 1 == j:
return cls.one
return cls.zero
return cls._new(rows, cols, entry)
@classmethod
def _eval_ones(cls, rows, cols):
def entry(i, j):
return cls.one
return cls._new(rows, cols, entry)
@classmethod
def _eval_zeros(cls, rows, cols):
def entry(i, j):
return cls.zero
return cls._new(rows, cols, entry)
@classmethod
def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs):
"""Returns a matrix with the specified diagonal.
If matrices are passed, a block-diagonal matrix
is created (i.e. the "direct sum" of the matrices).
kwargs
======
rows : rows of the resulting matrix; computed if
not given.
cols : columns of the resulting matrix; computed if
not given.
cls : class for the resulting matrix
unpack : bool which, when True (default), unpacks a single
sequence rather than interpreting it as a Matrix.
strict : bool which, when False (default), allows Matrices to
have variable-length rows.
Examples
========
>>> from sympy.matrices import Matrix
>>> Matrix.diag(1, 2, 3)
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
The current default is to unpack a single sequence. If this is
not desired, set `unpack=False` and it will be interpreted as
a matrix.
>>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
True
When more than one element is passed, each is interpreted as
something to put on the diagonal. Lists are converted to
matrices. Filling of the diagonal always continues from
the bottom right hand corner of the previous item: this
will create a block-diagonal matrix whether the matrices
are square or not.
>>> col = [1, 2, 3]
>>> row = [[4, 5]]
>>> Matrix.diag(col, row)
Matrix([
[1, 0, 0],
[2, 0, 0],
[3, 0, 0],
[0, 4, 5]])
When `unpack` is False, elements within a list need not all be
of the same length. Setting `strict` to True would raise a
ValueError for the following:
>>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
Matrix([
[1, 2, 3],
[4, 5, 0],
[6, 0, 0]])
The type of the returned matrix can be set with the ``cls``
keyword.
>>> from sympy.matrices import ImmutableMatrix
>>> from sympy.utilities.misc import func_name
>>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
'ImmutableDenseMatrix'
A zero dimension matrix can be used to position the start of
the filling at the start of an arbitrary row or column:
>>> from sympy import ones
>>> r2 = ones(0, 2)
>>> Matrix.diag(r2, 1, 2)
Matrix([
[0, 0, 1, 0],
[0, 0, 0, 2]])
See Also
========
eye
diagonal - to extract a diagonal
.dense.diag
.expressions.blockmatrix.BlockMatrix
.sparsetools.banded - to create multi-diagonal matrices
"""
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.dense import Matrix
from sympy.matrices.sparse import SparseMatrix
klass = kwargs.get('cls', kls)
if unpack and len(args) == 1 and is_sequence(args[0]) and \
not isinstance(args[0], MatrixBase):
args = args[0]
# fill a default dict with the diagonal entries
diag_entries = defaultdict(int)
rmax = cmax = 0 # keep track of the biggest index seen
for m in args:
if isinstance(m, list):
if strict:
# if malformed, Matrix will raise an error
_ = Matrix(m)
r, c = _.shape
m = _.tolist()
else:
r, c, smat = SparseMatrix._handle_creation_inputs(m)
for (i, j), _ in smat.items():
diag_entries[(i + rmax, j + cmax)] = _
m = [] # to skip process below
elif hasattr(m, 'shape'): # a Matrix
# convert to list of lists
r, c = m.shape
m = m.tolist()
else: # in this case, we're a single value
diag_entries[(rmax, cmax)] = m
rmax += 1
cmax += 1
continue
# process list of lists
for i in range(len(m)):
for j, _ in enumerate(m[i]):
diag_entries[(i + rmax, j + cmax)] = _
rmax += r
cmax += c
if rows is None:
rows, cols = cols, rows
if rows is None:
rows, cols = rmax, cmax
else:
cols = rows if cols is None else cols
if rows < rmax or cols < cmax:
raise ValueError(filldedent('''
The constructed matrix is {} x {} but a size of {} x {}
was specified.'''.format(rmax, cmax, rows, cols)))
return klass._eval_diag(rows, cols, diag_entries)
@classmethod
def eye(kls, rows, cols=None, **kwargs):
"""Returns an identity matrix.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_eye(rows, cols)
@classmethod
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs):
"""Returns a Jordan block
Parameters
==========
size : Integer, optional
Specifies the shape of the Jordan block matrix.
eigenvalue : Number or Symbol
Specifies the value for the main diagonal of the matrix.
.. note::
The keyword ``eigenval`` is also specified as an alias
of this keyword, but it is not recommended to use.
We may deprecate the alias in later release.
band : 'upper' or 'lower', optional
Specifies the position of the off-diagonal to put `1` s on.
cls : Matrix, optional
Specifies the matrix class of the output form.
If it is not specified, the class type where the method is
being executed on will be returned.
rows, cols : Integer, optional
Specifies the shape of the Jordan block matrix. See Notes
section for the details of how these key works.
.. note::
This feature will be deprecated in the future.
Returns
=======
Matrix
A Jordan block matrix.
Raises
======
ValueError
If insufficient arguments are given for matrix size
specification, or no eigenvalue is given.
Examples
========
Creating a default Jordan block:
>>> from sympy import Matrix
>>> from sympy.abc import x
>>> Matrix.jordan_block(4, x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
Creating an alternative Jordan block matrix where `1` is on
lower off-diagonal:
>>> Matrix.jordan_block(4, x, band='lower')
Matrix([
[x, 0, 0, 0],
[1, x, 0, 0],
[0, 1, x, 0],
[0, 0, 1, x]])
Creating a Jordan block with keyword arguments
>>> Matrix.jordan_block(size=4, eigenvalue=x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
Notes
=====
.. note::
This feature will be deprecated in the future.
The keyword arguments ``size``, ``rows``, ``cols`` relates to
the Jordan block size specifications.
If you want to create a square Jordan block, specify either
one of the three arguments.
If you want to create a rectangular Jordan block, specify
``rows`` and ``cols`` individually.
+--------------------------------+---------------------+
| Arguments Given | Matrix Shape |
+----------+----------+----------+----------+----------+
| size | rows | cols | rows | cols |
+==========+==========+==========+==========+==========+
| size | Any | size | size |
+----------+----------+----------+----------+----------+
| | None | ValueError |
| +----------+----------+----------+----------+
| None | rows | None | rows | rows |
| +----------+----------+----------+----------+
| | None | cols | cols | cols |
+ +----------+----------+----------+----------+
| | rows | cols | rows | cols |
+----------+----------+----------+----------+----------+
References
==========
.. [1] https://en.wikipedia.org/wiki/Jordan_matrix
"""
if 'rows' in kwargs or 'cols' in kwargs:
SymPyDeprecationWarning(
feature="Keyword arguments 'rows' or 'cols'",
issue=16102,
useinstead="a more generic banded matrix constructor",
deprecated_since_version="1.4"
).warn()
klass = kwargs.pop('cls', kls)
rows = kwargs.pop('rows', None)
cols = kwargs.pop('cols', None)
eigenval = kwargs.get('eigenval', None)
if eigenvalue is None and eigenval is None:
raise ValueError("Must supply an eigenvalue")
elif eigenvalue != eigenval and None not in (eigenval, eigenvalue):
raise ValueError(
"Inconsistent values are given: 'eigenval'={}, "
"'eigenvalue'={}".format(eigenval, eigenvalue))
else:
if eigenval is not None:
eigenvalue = eigenval
if (size, rows, cols) == (None, None, None):
raise ValueError("Must supply a matrix size")
if size is not None:
rows, cols = size, size
elif rows is not None and cols is None:
cols = rows
elif cols is not None and rows is None:
rows = cols
rows, cols = as_int(rows), as_int(cols)
return klass._eval_jordan_block(rows, cols, eigenvalue, band)
@classmethod
def ones(kls, rows, cols=None, **kwargs):
"""Returns a matrix of ones.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_ones(rows, cols)
@classmethod
def zeros(kls, rows, cols=None, **kwargs):
"""Returns a matrix of zeros.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_zeros(rows, cols)
@classmethod
def companion(kls, poly):
"""Returns a companion matrix of a polynomial.
Examples
========
>>> from sympy import Matrix, Poly, Symbol, symbols
>>> x = Symbol('x')
>>> c0, c1, c2, c3, c4 = symbols('c0:5')
>>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
>>> Matrix.companion(p)
Matrix([
[0, 0, 0, 0, -c0],
[1, 0, 0, 0, -c1],
[0, 1, 0, 0, -c2],
[0, 0, 1, 0, -c3],
[0, 0, 0, 1, -c4]])
"""
poly = kls._sympify(poly)
if not isinstance(poly, Poly):
raise ValueError("{} must be a Poly instance.".format(poly))
if not poly.is_monic:
raise ValueError("{} must be a monic polynomial.".format(poly))
if not poly.is_univariate:
raise ValueError(
"{} must be a univariate polynomial.".format(poly))
size = poly.degree()
if not size >= 1:
raise ValueError(
"{} must have degree not less than 1.".format(poly))
coeffs = poly.all_coeffs()
def entry(i, j):
if j == size - 1:
return -coeffs[-1 - i]
elif i == j + 1:
return kls.one
return kls.zero
return kls._new(size, size, entry)
class MatrixProperties(MatrixRequired):
"""Provides basic properties of a matrix."""
def _eval_atoms(self, *types):
result = set()
for i in self:
result.update(i.atoms(*types))
return result
def _eval_free_symbols(self):
return set().union(*(i.free_symbols for i in self if i))
def _eval_has(self, *patterns):
return any(a.has(*patterns) for a in self)
def _eval_is_anti_symmetric(self, simpfunc):
if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)):
return False
return True
def _eval_is_diagonal(self):
for i in range(self.rows):
for j in range(self.cols):
if i != j and self[i, j]:
return False
return True
# _eval_is_hermitian is called by some general sympy
# routines and has a different *args signature. Make
# sure the names don't clash by adding `_matrix_` in name.
def _eval_is_matrix_hermitian(self, simpfunc):
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate()))
return mat.is_zero_matrix
def _eval_is_Identity(self) -> FuzzyBool:
def dirac(i, j):
if i == j:
return 1
return 0
return all(self[i, j] == dirac(i, j)
for i in range(self.rows)
for j in range(self.cols))
def _eval_is_lower_hessenberg(self):
return all(self[i, j].is_zero
for i in range(self.rows)
for j in range(i + 2, self.cols))
def _eval_is_lower(self):
return all(self[i, j].is_zero
for i in range(self.rows)
for j in range(i + 1, self.cols))
def _eval_is_symbolic(self):
return self.has(Symbol)
def _eval_is_symmetric(self, simpfunc):
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i]))
return mat.is_zero_matrix
def _eval_is_zero_matrix(self):
if any(i.is_zero == False for i in self):
return False
if any(i.is_zero is None for i in self):
return None
return True
def _eval_is_upper_hessenberg(self):
return all(self[i, j].is_zero
for i in range(2, self.rows)
for j in range(min(self.cols, (i - 1))))
def _eval_values(self):
return [i for i in self if not i.is_zero]
def _has_positive_diagonals(self):
diagonal_entries = (self[i, i] for i in range(self.rows))
return fuzzy_and(x.is_positive for x in diagonal_entries)
def _has_nonnegative_diagonals(self):
diagonal_entries = (self[i, i] for i in range(self.rows))
return fuzzy_and(x.is_nonnegative for x in diagonal_entries)
def atoms(self, *types):
"""Returns the atoms that form the current object.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import Matrix
>>> Matrix([[x]])
Matrix([[x]])
>>> _.atoms()
{x}
>>> Matrix([[x, y], [y, x]])
Matrix([
[x, y],
[y, x]])
>>> _.atoms()
{x, y}
"""
types = tuple(t if isinstance(t, type) else type(t) for t in types)
if not types:
types = (Atom,)
return self._eval_atoms(*types)
@property
def free_symbols(self):
"""Returns the free symbols within the matrix.
Examples
========
>>> from sympy.abc import x
>>> from sympy.matrices import Matrix
>>> Matrix([[x], [1]]).free_symbols
{x}
"""
return self._eval_free_symbols()
def has(self, *patterns):
"""Test whether any subexpression matches any of the patterns.
Examples
========
>>> from sympy import Matrix, SparseMatrix, Float
>>> from sympy.abc import x, y
>>> A = Matrix(((1, x), (0.2, 3)))
>>> B = SparseMatrix(((1, x), (0.2, 3)))
>>> A.has(x)
True
>>> A.has(y)
False
>>> A.has(Float)
True
>>> B.has(x)
True
>>> B.has(y)
False
>>> B.has(Float)
True
"""
return self._eval_has(*patterns)
def is_anti_symmetric(self, simplify=True):
"""Check if matrix M is an antisymmetric matrix,
that is, M is a square matrix with all M[i, j] == -M[j, i].
When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
simplified before testing to see if it is zero. By default,
the SymPy simplify function is used. To use a custom function
set simplify to a function that accepts a single argument which
returns a simplified expression. To skip simplification, set
simplify to False but note that although this will be faster,
it may induce false negatives.
Examples
========
>>> from sympy import Matrix, symbols
>>> m = Matrix(2, 2, [0, 1, -1, 0])
>>> m
Matrix([
[ 0, 1],
[-1, 0]])
>>> m.is_anti_symmetric()
True
>>> x, y = symbols('x y')
>>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
>>> m
Matrix([
[ 0, 0, x],
[-y, 0, 0]])
>>> m.is_anti_symmetric()
False
>>> from sympy.abc import x, y
>>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
... -(x + 1)**2 , 0, x*y,
... -y, -x*y, 0])
Simplification of matrix elements is done by default so even
though two elements which should be equal and opposite wouldn't
pass an equality test, the matrix is still reported as
anti-symmetric:
>>> m[0, 1] == -m[1, 0]
False
>>> m.is_anti_symmetric()
True
If 'simplify=False' is used for the case when a Matrix is already
simplified, this will speed things up. Here, we see that without
simplification the matrix does not appear anti-symmetric:
>>> m.is_anti_symmetric(simplify=False)
False
But if the matrix were already expanded, then it would appear
anti-symmetric and simplification in the is_anti_symmetric routine
is not needed:
>>> m = m.expand()
>>> m.is_anti_symmetric(simplify=False)
True
"""
# accept custom simplification
simpfunc = simplify
if not isfunction(simplify):
simpfunc = _simplify if simplify else lambda x: x
if not self.is_square:
return False
return self._eval_is_anti_symmetric(simpfunc)
def is_diagonal(self):
"""Check if matrix is diagonal,
that is matrix in which the entries outside the main diagonal are all zero.
Examples
========
>>> from sympy import Matrix, diag
>>> m = Matrix(2, 2, [1, 0, 0, 2])
>>> m
Matrix([
[1, 0],
[0, 2]])
>>> m.is_diagonal()
True
>>> m = Matrix(2, 2, [1, 1, 0, 2])
>>> m
Matrix([
[1, 1],
[0, 2]])
>>> m.is_diagonal()
False
>>> m = diag(1, 2, 3)
>>> m
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> m.is_diagonal()
True
See Also
========
is_lower
is_upper
sympy.matrices.matrices.MatrixEigen.is_diagonalizable
diagonalize
"""
return self._eval_is_diagonal()
@property
def is_weakly_diagonally_dominant(self):
r"""Tests if the matrix is row weakly diagonally dominant.
Explanation
===========
A $n, n$ matrix $A$ is row weakly diagonally dominant if
.. math::
\left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
\left|A_{i, j}\right| \quad {\text{for all }}
i \in \{ 0, ..., n-1 \}
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
>>> A.is_weakly_diagonally_dominant
True
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
>>> A.is_weakly_diagonally_dominant
False
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
>>> A.is_weakly_diagonally_dominant
True
Notes
=====
If you want to test whether a matrix is column diagonally
dominant, you can apply the test after transposing the matrix.
"""
if not self.is_square:
return False
rows, cols = self.shape
def test_row(i):
summation = self.zero
for j in range(cols):
if i != j:
summation += Abs(self[i, j])
return (Abs(self[i, i]) - summation).is_nonnegative
return fuzzy_and(test_row(i) for i in range(rows))
@property
def is_strongly_diagonally_dominant(self):
r"""Tests if the matrix is row strongly diagonally dominant.
Explanation
===========
A $n, n$ matrix $A$ is row strongly diagonally dominant if
.. math::
\left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
\left|A_{i, j}\right| \quad {\text{for all }}
i \in \{ 0, ..., n-1 \}
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
>>> A.is_strongly_diagonally_dominant
False
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
>>> A.is_strongly_diagonally_dominant
False
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
>>> A.is_strongly_diagonally_dominant
True
Notes
=====
If you want to test whether a matrix is column diagonally
dominant, you can apply the test after transposing the matrix.
"""
if not self.is_square:
return False
rows, cols = self.shape
def test_row(i):
summation = self.zero
for j in range(cols):
if i != j:
summation += Abs(self[i, j])
return (Abs(self[i, i]) - summation).is_positive
return fuzzy_and(test_row(i) for i in range(rows))
@property
def is_hermitian(self):
"""Checks if the matrix is Hermitian.
In a Hermitian matrix element i,j is the complex conjugate of
element j,i.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy import I
>>> from sympy.abc import x
>>> a = Matrix([[1, I], [-I, 1]])
>>> a
Matrix([
[ 1, I],
[-I, 1]])
>>> a.is_hermitian
True
>>> a[0, 0] = 2*I
>>> a.is_hermitian
False
>>> a[0, 0] = x
>>> a.is_hermitian
>>> a[0, 1] = a[1, 0]*I
>>> a.is_hermitian
False
"""
if not self.is_square:
return False
return self._eval_is_matrix_hermitian(_simplify)
@property
def is_Identity(self) -> FuzzyBool:
if not self.is_square:
return False
return self._eval_is_Identity()
@property
def is_lower_hessenberg(self):
r"""Checks if the matrix is in the lower-Hessenberg form.
The lower hessenberg matrix has zero entries
above the first superdiagonal.
Examples
========
>>> from sympy.matrices import Matrix
>>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
>>> a
Matrix([
[1, 2, 0, 0],
[5, 2, 3, 0],
[3, 4, 3, 7],
[5, 6, 1, 1]])
>>> a.is_lower_hessenberg
True
See Also
========
is_upper_hessenberg
is_lower
"""
return self._eval_is_lower_hessenberg()
@property
def is_lower(self):
"""Check if matrix is a lower triangular matrix. True can be returned
even if the matrix is not square.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_lower
True
>>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4 , 0, 6, 6, 5])
>>> m
Matrix([
[0, 0, 0],
[2, 0, 0],
[1, 4, 0],
[6, 6, 5]])
>>> m.is_lower
True
>>> from sympy.abc import x, y
>>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
>>> m
Matrix([
[x**2 + y, x + y**2],
[ 0, x + y]])
>>> m.is_lower
False
See Also
========
is_upper
is_diagonal
is_lower_hessenberg
"""
return self._eval_is_lower()
@property
def is_square(self):
"""Checks if a matrix is square.
A matrix is square if the number of rows equals the number of columns.
The empty matrix is square by definition, since the number of rows and
the number of columns are both zero.
Examples
========
>>> from sympy import Matrix
>>> a = Matrix([[1, 2, 3], [4, 5, 6]])
>>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> c = Matrix([])
>>> a.is_square
False
>>> b.is_square
True
>>> c.is_square
True
"""
return self.rows == self.cols
def is_symbolic(self):
"""Checks if any elements contain Symbols.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.is_symbolic()
True
"""
return self._eval_is_symbolic()
def is_symmetric(self, simplify=True):
"""Check if matrix is symmetric matrix,
that is square matrix and is equal to its transpose.
By default, simplifications occur before testing symmetry.
They can be skipped using 'simplify=False'; while speeding things a bit,
this may however induce false negatives.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [0, 1, 1, 2])
>>> m
Matrix([
[0, 1],
[1, 2]])
>>> m.is_symmetric()
True
>>> m = Matrix(2, 2, [0, 1, 2, 0])
>>> m
Matrix([
[0, 1],
[2, 0]])
>>> m.is_symmetric()
False
>>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
>>> m
Matrix([
[0, 0, 0],
[0, 0, 0]])
>>> m.is_symmetric()
False
>>> from sympy.abc import x, y
>>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2 , 2, 0, y, 0, 3])
>>> m
Matrix([
[ 1, x**2 + 2*x + 1, y],
[(x + 1)**2, 2, 0],
[ y, 0, 3]])
>>> m.is_symmetric()
True
If the matrix is already simplified, you may speed-up is_symmetric()
test by using 'simplify=False'.
>>> bool(m.is_symmetric(simplify=False))
False
>>> m1 = m.expand()
>>> m1.is_symmetric(simplify=False)
True
"""
simpfunc = simplify
if not isfunction(simplify):
simpfunc = _simplify if simplify else lambda x: x
if not self.is_square:
return False
return self._eval_is_symmetric(simpfunc)
@property
def is_upper_hessenberg(self):
"""Checks if the matrix is the upper-Hessenberg form.
The upper hessenberg matrix has zero entries
below the first subdiagonal.
Examples
========
>>> from sympy.matrices import Matrix
>>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
>>> a
Matrix([
[1, 4, 2, 3],
[3, 4, 1, 7],
[0, 2, 3, 4],
[0, 0, 1, 3]])
>>> a.is_upper_hessenberg
True
See Also
========
is_lower_hessenberg
is_upper
"""
return self._eval_is_upper_hessenberg()
@property
def is_upper(self):
"""Check if matrix is an upper triangular matrix. True can be returned
even if the matrix is not square.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_upper
True
>>> m = Matrix(4, 3, [5, 1, 9, 0, 4 , 6, 0, 0, 5, 0, 0, 0])
>>> m
Matrix([
[5, 1, 9],
[0, 4, 6],
[0, 0, 5],
[0, 0, 0]])
>>> m.is_upper
True
>>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
>>> m
Matrix([
[4, 2, 5],
[6, 1, 1]])
>>> m.is_upper
False
See Also
========
is_lower
is_diagonal
is_upper_hessenberg
"""
return all(self[i, j].is_zero
for i in range(1, self.rows)
for j in range(min(i, self.cols)))
@property
def is_zero_matrix(self):
"""Checks if a matrix is a zero matrix.
A matrix is zero if every element is zero. A matrix need not be square
to be considered zero. The empty matrix is zero by the principle of
vacuous truth. For a matrix that may or may not be zero (e.g.
contains a symbol), this will be None
Examples
========
>>> from sympy import Matrix, zeros
>>> from sympy.abc import x
>>> a = Matrix([[0, 0], [0, 0]])
>>> b = zeros(3, 4)
>>> c = Matrix([[0, 1], [0, 0]])
>>> d = Matrix([])
>>> e = Matrix([[x, 0], [0, 0]])
>>> a.is_zero_matrix
True
>>> b.is_zero_matrix
True
>>> c.is_zero_matrix
False
>>> d.is_zero_matrix
True
>>> e.is_zero_matrix
"""
return self._eval_is_zero_matrix()
def values(self):
"""Return non-zero values of self."""
return self._eval_values()
class MatrixOperations(MatrixRequired):
"""Provides basic matrix shape and elementwise
operations. Should not be instantiated directly."""
def _eval_adjoint(self):
return self.transpose().conjugate()
def _eval_applyfunc(self, f):
out = self._new(self.rows, self.cols, [f(x) for x in self])
return out
def _eval_as_real_imag(self): # type: ignore
from sympy.functions.elementary.complexes import re, im
return (self.applyfunc(re), self.applyfunc(im))
def _eval_conjugate(self):
return self.applyfunc(lambda x: x.conjugate())
def _eval_permute_cols(self, perm):
# apply the permutation to a list
mapping = list(perm)
def entry(i, j):
return self[i, mapping[j]]
return self._new(self.rows, self.cols, entry)
def _eval_permute_rows(self, perm):
# apply the permutation to a list
mapping = list(perm)
def entry(i, j):
return self[mapping[i], j]
return self._new(self.rows, self.cols, entry)
def _eval_trace(self):
return sum(self[i, i] for i in range(self.rows))
def _eval_transpose(self):
return self._new(self.cols, self.rows, lambda i, j: self[j, i])
def adjoint(self):
"""Conjugate transpose or Hermitian conjugation."""
return self._eval_adjoint()
def applyfunc(self, f):
"""Apply a function to each element of the matrix.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, lambda i, j: i*2+j)
>>> m
Matrix([
[0, 1],
[2, 3]])
>>> m.applyfunc(lambda i: 2*i)
Matrix([
[0, 2],
[4, 6]])
"""
if not callable(f):
raise TypeError("`f` must be callable.")
return self._eval_applyfunc(f)
def as_real_imag(self, deep=True, **hints):
"""Returns a tuple containing the (real, imaginary) part of matrix."""
# XXX: Ignoring deep and hints...
return self._eval_as_real_imag()
def conjugate(self):
"""Return the by-element conjugation.
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> from sympy import I
>>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
>>> a
Matrix([
[1, 2 + I],
[3, 4],
[I, -I]])
>>> a.C
Matrix([
[ 1, 2 - I],
[ 3, 4],
[-I, I]])
See Also
========
transpose: Matrix transposition
H: Hermite conjugation
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
"""
return self._eval_conjugate()
def doit(self, **kwargs):
return self.applyfunc(lambda x: x.doit())
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
"""Apply evalf() to each element of self."""
options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict,
'quad':quad, 'verbose':verbose}
return self.applyfunc(lambda i: i.evalf(n, **options))
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
"""Apply core.function.expand to each entry of the matrix.
Examples
========
>>> from sympy.abc import x
>>> from sympy.matrices import Matrix
>>> Matrix(1, 1, [x*(x+1)])
Matrix([[x*(x + 1)]])
>>> _.expand()
Matrix([[x**2 + x]])
"""
return self.applyfunc(lambda x: x.expand(
deep, modulus, power_base, power_exp, mul, log, multinomial, basic,
**hints))
@property
def H(self):
"""Return Hermite conjugate.
Examples
========
>>> from sympy import Matrix, I
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m
Matrix([
[ 0],
[1 + I],
[ 2],
[ 3]])
>>> m.H
Matrix([[0, 1 - I, 2, 3]])
See Also
========
conjugate: By-element conjugation
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
"""
return self.T.C
def permute(self, perm, orientation='rows', direction='forward'):
r"""Permute the rows or columns of a matrix by the given list of
swaps.
Parameters
==========
perm : Permutation, list, or list of lists
A representation for the permutation.
If it is ``Permutation``, it is used directly with some
resizing with respect to the matrix size.
If it is specified as list of lists,
(e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
from applying the product of cycles. The direction how the
cyclic product is applied is described in below.
If it is specified as a list, the list should represent
an array form of a permutation. (e.g., ``[1, 2, 0]``) which
would would form the swapping function
`0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.
orientation : 'rows', 'cols'
A flag to control whether to permute the rows or the columns
direction : 'forward', 'backward'
A flag to control whether to apply the permutations from
the start of the list first, or from the back of the list
first.
For example, if the permutation specification is
``[[0, 1], [0, 2]]``,
If the flag is set to ``'forward'``, the cycle would be
formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.
If the flag is set to ``'backward'``, the cycle would be
formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.
If the argument ``perm`` is not in a form of list of lists,
this flag takes no effect.
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
Matrix([
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
Matrix([
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]])
Notes
=====
If a bijective function
`\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
permutation.
If the matrix `A` is the matrix to permute, represented as
a horizontal or a vertical stack of vectors:
.. math::
A =
\begin{bmatrix}
a_0 \\ a_1 \\ \vdots \\ a_{n-1}
\end{bmatrix} =
\begin{bmatrix}
\alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
\end{bmatrix}
If the matrix `B` is the result, the permutation of matrix rows
is defined as:
.. math::
B := \begin{bmatrix}
a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
\end{bmatrix}
And the permutation of matrix columns is defined as:
.. math::
B := \begin{bmatrix}
\alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
\cdots & \alpha_{\sigma(n-1)}
\end{bmatrix}
"""
from sympy.combinatorics import Permutation
# allow british variants and `columns`
if direction == 'forwards':
direction = 'forward'
if direction == 'backwards':
direction = 'backward'
if orientation == 'columns':
orientation = 'cols'
if direction not in ('forward', 'backward'):
raise TypeError("direction='{}' is an invalid kwarg. "
"Try 'forward' or 'backward'".format(direction))
if orientation not in ('rows', 'cols'):
raise TypeError("orientation='{}' is an invalid kwarg. "
"Try 'rows' or 'cols'".format(orientation))
if not isinstance(perm, (Permutation, Iterable)):
raise ValueError(
"{} must be a list, a list of lists, "
"or a SymPy permutation object.".format(perm))
# ensure all swaps are in range
max_index = self.rows if orientation == 'rows' else self.cols
if not all(0 <= t <= max_index for t in flatten(list(perm))):
raise IndexError("`swap` indices out of range.")
if perm and not isinstance(perm, Permutation) and \
isinstance(perm[0], Iterable):
if direction == 'forward':
perm = list(reversed(perm))
perm = Permutation(perm, size=max_index+1)
else:
perm = Permutation(perm, size=max_index+1)
if orientation == 'rows':
return self._eval_permute_rows(perm)
if orientation == 'cols':
return self._eval_permute_cols(perm)
def permute_cols(self, swaps, direction='forward'):
"""Alias for
``self.permute(swaps, orientation='cols', direction=direction)``
See Also
========
permute
"""
return self.permute(swaps, orientation='cols', direction=direction)
def permute_rows(self, swaps, direction='forward'):
"""Alias for
``self.permute(swaps, orientation='rows', direction=direction)``
See Also
========
permute
"""
return self.permute(swaps, orientation='rows', direction=direction)
def refine(self, assumptions=True):
"""Apply refine to each element of the matrix.
Examples
========
>>> from sympy import Symbol, Matrix, Abs, sqrt, Q
>>> x = Symbol('x')
>>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
Matrix([
[ Abs(x)**2, sqrt(x**2)],
[sqrt(x**2), Abs(x)**2]])
>>> _.refine(Q.real(x))
Matrix([
[ x**2, Abs(x)],
[Abs(x), x**2]])
"""
return self.applyfunc(lambda x: refine(x, assumptions))
def replace(self, F, G, map=False, simultaneous=True, exact=None):
"""Replaces Function F in Matrix entries with Function G.
Examples
========
>>> from sympy import symbols, Function, Matrix
>>> F, G = symbols('F, G', cls=Function)
>>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
Matrix([
[F(0), F(1)],
[F(1), F(2)]])
>>> N = M.replace(F,G)
>>> N
Matrix([
[G(0), G(1)],
[G(1), G(2)]])
"""
return self.applyfunc(
lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact))
def rot90(self, k=1):
"""Rotates Matrix by 90 degrees
Parameters
==========
k : int
Specifies how many times the matrix is rotated by 90 degrees
(clockwise when positive, counter-clockwise when negative).
Examples
========
>>> from sympy import Matrix, symbols
>>> A = Matrix(2, 2, symbols('a:d'))
>>> A
Matrix([
[a, b],
[c, d]])
Rotating the matrix clockwise one time:
>>> A.rot90(1)
Matrix([
[c, a],
[d, b]])
Rotating the matrix anticlockwise two times:
>>> A.rot90(-2)
Matrix([
[d, c],
[b, a]])
"""
mod = k%4
if mod == 0:
return self
if mod == 1:
return self[::-1, ::].T
if mod == 2:
return self[::-1, ::-1]
if mod == 3:
return self[::, ::-1].T
def simplify(self, **kwargs):
"""Apply simplify to each element of the matrix.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import sin, cos
>>> from sympy.matrices import SparseMatrix
>>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
Matrix([[x*sin(y)**2 + x*cos(y)**2]])
>>> _.simplify()
Matrix([[x]])
"""
return self.applyfunc(lambda x: x.simplify(**kwargs))
def subs(self, *args, **kwargs): # should mirror core.basic.subs
"""Return a new matrix with subs applied to each entry.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.subs(x, y)
Matrix([[y]])
>>> Matrix(_).subs(y, x)
Matrix([[x]])
"""
if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]):
args = (list(args[0]),)
return self.applyfunc(lambda x: x.subs(*args, **kwargs))
def trace(self):
"""
Returns the trace of a square matrix i.e. the sum of the
diagonal elements.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.trace()
5
"""
if self.rows != self.cols:
raise NonSquareMatrixError()
return self._eval_trace()
def transpose(self):
"""
Returns the transpose of the matrix.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.transpose()
Matrix([
[1, 3],
[2, 4]])
>>> from sympy import Matrix, I
>>> m=Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3, 4]])
>>> m.transpose()
Matrix([
[ 1, 3],
[2 + I, 4]])
>>> m.T == m.transpose()
True
See Also
========
conjugate: By-element conjugation
"""
return self._eval_transpose()
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
@property
def C(self):
'''By-element conjugation'''
return self.conjugate()
def n(self, *args, **kwargs):
"""Apply evalf() to each element of self."""
return self.evalf(*args, **kwargs)
def xreplace(self, rule): # should mirror core.basic.xreplace
"""Return a new matrix with xreplace applied to each entry.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.xreplace({x: y})
Matrix([[y]])
>>> Matrix(_).xreplace({y: x})
Matrix([[x]])
"""
return self.applyfunc(lambda x: x.xreplace(rule))
def _eval_simplify(self, **kwargs):
# XXX: We can't use self.simplify here as mutable subclasses will
# override simplify and have it return None
return MatrixOperations.simplify(self, **kwargs)
def _eval_trigsimp(self, **opts):
from sympy.simplify import trigsimp
return self.applyfunc(lambda x: trigsimp(x, **opts))
class MatrixArithmetic(MatrixRequired):
"""Provides basic matrix arithmetic operations.
Should not be instantiated directly."""
_op_priority = 10.01
def _eval_Abs(self):
return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j]))
def _eval_add(self, other):
return self._new(self.rows, self.cols,
lambda i, j: self[i, j] + other[i, j])
def _eval_matrix_mul(self, other):
def entry(i, j):
vec = [self[i,k]*other[k,j] for k in range(self.cols)]
try:
return Add(*vec)
except (TypeError, SympifyError):
# Some matrices don't work with `sum` or `Add`
# They don't work with `sum` because `sum` tries to add `0`
# Fall back to a safe way to multiply if the `Add` fails.
return reduce(lambda a, b: a + b, vec)
return self._new(self.rows, other.cols, entry)
def _eval_matrix_mul_elementwise(self, other):
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j])
def _eval_matrix_rmul(self, other):
def entry(i, j):
return sum(other[i,k]*self[k,j] for k in range(other.cols))
return self._new(other.rows, self.cols, entry)
def _eval_pow_by_recursion(self, num):
if num == 1:
return self
if num % 2 == 1:
a, b = self, self._eval_pow_by_recursion(num - 1)
else:
a = b = self._eval_pow_by_recursion(num // 2)
return a.multiply(b)
def _eval_pow_by_cayley(self, exp):
from sympy.discrete.recurrences import linrec_coeffs
row = self.shape[0]
p = self.charpoly()
coeffs = (-p).all_coeffs()[1:]
coeffs = linrec_coeffs(coeffs, exp)
new_mat = self.eye(row)
ans = self.zeros(row)
for i in range(row):
ans += coeffs[i]*new_mat
new_mat *= self
return ans
def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None):
if prevsimp is None:
prevsimp = [True]*len(self)
if num == 1:
return self
if num % 2 == 1:
a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1,
prevsimp=prevsimp)
else:
a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2,
prevsimp=prevsimp)
m = a.multiply(b, dotprodsimp=False)
lenm = len(m)
elems = [None]*lenm
for i in range(lenm):
if prevsimp[i]:
elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True)
else:
elems[i] = m[i]
return m._new(m.rows, m.cols, elems)
def _eval_scalar_mul(self, other):
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other)
def _eval_scalar_rmul(self, other):
return self._new(self.rows, self.cols, lambda i, j: other*self[i,j])
def _eval_Mod(self, other):
from sympy import Mod
return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other))
# python arithmetic functions
def __abs__(self):
"""Returns a new matrix with entry-wise absolute values."""
return self._eval_Abs()
@call_highest_priority('__radd__')
def __add__(self, other):
"""Return self + other, raising ShapeError if shapes don't match."""
if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented
return NotImplemented
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check.
if hasattr(other, 'shape'):
if self.shape != other.shape:
raise ShapeError("Matrix size mismatch: %s + %s" % (
self.shape, other.shape))
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
# call the highest-priority class's _eval_add
a, b = self, other
if a.__class__ != classof(a, b):
b, a = a, b
return a._eval_add(b)
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_add(self, other)
raise TypeError('cannot add %s and %s' % (type(self), type(other)))
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self * (self.one / other)
@call_highest_priority('__rmatmul__')
def __matmul__(self, other):
other = _matrixify(other)
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
return NotImplemented
return self.__mul__(other)
def __mod__(self, other):
return self.applyfunc(lambda x: x % other)
@call_highest_priority('__rmul__')
def __mul__(self, other):
"""Return self*other where other is either a scalar or a matrix
of compatible dimensions.
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
>>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
True
>>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> A*B
Matrix([
[30, 36, 42],
[66, 81, 96]])
>>> B*A
Traceback (most recent call last):
...
ShapeError: Matrices size mismatch.
>>>
See Also
========
matrix_multiply_elementwise
"""
return self.multiply(other)
def multiply(self, other, dotprodsimp=None):
"""Same as __mul__() but with optional simplification.
Parameters
==========
dotprodsimp : bool, optional
Specifies whether intermediate term algebraic simplification is used
during matrix multiplications to control expression blowup and thus
speed up calculation. Default is off.
"""
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check. Double check other is not explicitly not a Matrix.
if (hasattr(other, 'shape') and len(other.shape) == 2 and
(getattr(other, 'is_Matrix', True) or
getattr(other, 'is_MatrixLike', True))):
if self.shape[1] != other.shape[0]:
raise ShapeError("Matrix size mismatch: %s * %s." % (
self.shape, other.shape))
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
m = self._eval_matrix_mul(other)
if isimpbool:
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
return m
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_matrix_mul(self, other)
# if 'other' is not iterable then scalar multiplication.
if not isinstance(other, Iterable):
try:
return self._eval_scalar_mul(other)
except TypeError:
pass
return NotImplemented
def multiply_elementwise(self, other):
"""Return the Hadamard product (elementwise product) of A and B
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
>>> A.multiply_elementwise(B)
Matrix([
[ 0, 10, 200],
[300, 40, 5]])
See Also
========
sympy.matrices.matrices.MatrixBase.cross
sympy.matrices.matrices.MatrixBase.dot
multiply
"""
if self.shape != other.shape:
raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape))
return self._eval_matrix_mul_elementwise(other)
def __neg__(self):
return self._eval_scalar_mul(-1)
@call_highest_priority('__rpow__')
def __pow__(self, exp):
"""Return self**exp a scalar or symbol."""
return self.pow(exp)
def pow(self, exp, method=None):
r"""Return self**exp a scalar or symbol.
Parameters
==========
method : multiply, mulsimp, jordan, cayley
If multiply then it returns exponentiation using recursion.
If jordan then Jordan form exponentiation will be used.
If cayley then the exponentiation is done using Cayley-Hamilton
theorem.
If mulsimp then the exponentiation is done using recursion
with dotprodsimp. This specifies whether intermediate term
algebraic simplification is used during naive matrix power to
control expression blowup and thus speed up calculation.
If None, then it heuristically decides which method to use.
"""
if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']:
raise TypeError('No such method')
if self.rows != self.cols:
raise NonSquareMatrixError()
a = self
jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None)
exp = sympify(exp)
if exp.is_zero:
return a._new(a.rows, a.cols, lambda i, j: int(i == j))
if exp == 1:
return a
diagonal = getattr(a, 'is_diagonal', None)
if diagonal is not None and diagonal():
return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0)
if exp.is_Number and exp % 1 == 0:
if a.rows == 1:
return a._new([[a[0]**exp]])
if exp < 0:
exp = -exp
a = a.inv()
# When certain conditions are met,
# Jordan block algorithm is faster than
# computation by recursion.
if method == 'jordan':
try:
return jordan_pow(exp)
except MatrixError:
if method == 'jordan':
raise
elif method == 'cayley':
if not exp.is_Number or exp % 1 != 0:
raise ValueError("cayley method is only valid for integer powers")
return a._eval_pow_by_cayley(exp)
elif method == "mulsimp":
if not exp.is_Number or exp % 1 != 0:
raise ValueError("mulsimp method is only valid for integer powers")
return a._eval_pow_by_recursion_dotprodsimp(exp)
elif method == "multiply":
if not exp.is_Number or exp % 1 != 0:
raise ValueError("multiply method is only valid for integer powers")
return a._eval_pow_by_recursion(exp)
elif method is None and exp.is_Number and exp % 1 == 0:
# Decide heuristically which method to apply
if a.rows == 2 and exp > 100000:
return jordan_pow(exp)
elif _get_intermediate_simp_bool(True, None):
return a._eval_pow_by_recursion_dotprodsimp(exp)
elif exp > 10000:
return a._eval_pow_by_cayley(exp)
else:
return a._eval_pow_by_recursion(exp)
if jordan_pow:
try:
return jordan_pow(exp)
except NonInvertibleMatrixError:
# Raised by jordan_pow on zero determinant matrix unless exp is
# definitely known to be a non-negative integer.
# Here we raise if n is definitely not a non-negative integer
# but otherwise we can leave this as an unevaluated MatPow.
if exp.is_integer is False or exp.is_nonnegative is False:
raise
from sympy.matrices.expressions import MatPow
return MatPow(a, exp)
@call_highest_priority('__add__')
def __radd__(self, other):
return self + other
@call_highest_priority('__matmul__')
def __rmatmul__(self, other):
other = _matrixify(other)
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
return NotImplemented
return self.__rmul__(other)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return self.rmultiply(other)
def rmultiply(self, other, dotprodsimp=None):
"""Same as __rmul__() but with optional simplification.
Parameters
==========
dotprodsimp : bool, optional
Specifies whether intermediate term algebraic simplification is used
during matrix multiplications to control expression blowup and thus
speed up calculation. Default is off.
"""
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check. Double check other is not explicitly not a Matrix.
if (hasattr(other, 'shape') and len(other.shape) == 2 and
(getattr(other, 'is_Matrix', True) or
getattr(other, 'is_MatrixLike', True))):
if self.shape[0] != other.shape[1]:
raise ShapeError("Matrix size mismatch.")
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
m = self._eval_matrix_rmul(other)
if isimpbool:
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
return m
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_matrix_rmul(self, other)
# if 'other' is not iterable then scalar multiplication.
if not isinstance(other, Iterable):
try:
return self._eval_scalar_rmul(other)
except TypeError:
pass
return NotImplemented
@call_highest_priority('__sub__')
def __rsub__(self, a):
return (-self) + a
@call_highest_priority('__rsub__')
def __sub__(self, a):
return self + (-a)
class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties,
MatrixSpecial, MatrixShaping):
"""All common matrix operations including basic arithmetic, shaping,
and special matrices like `zeros`, and `eye`."""
_diff_wrt = True # type: bool
class _MinimalMatrix:
"""Class providing the minimum functionality
for a matrix-like object and implementing every method
required for a `MatrixRequired`. This class does not have everything
needed to become a full-fledged SymPy object, but it will satisfy the
requirements of anything inheriting from `MatrixRequired`. If you wish
to make a specialized matrix type, make sure to implement these
methods and properties with the exception of `__init__` and `__repr__`
which are included for convenience."""
is_MatrixLike = True
_sympify = staticmethod(sympify)
_class_priority = 3
zero = S.Zero
one = S.One
is_Matrix = True
is_MatrixExpr = False
@classmethod
def _new(cls, *args, **kwargs):
return cls(*args, **kwargs)
def __init__(self, rows, cols=None, mat=None):
if isfunction(mat):
# if we passed in a function, use that to populate the indices
mat = list(mat(i, j) for i in range(rows) for j in range(cols))
if cols is None and mat is None:
mat = rows
rows, cols = getattr(mat, 'shape', (rows, cols))
try:
# if we passed in a list of lists, flatten it and set the size
if cols is None and mat is None:
mat = rows
cols = len(mat[0])
rows = len(mat)
mat = [x for l in mat for x in l]
except (IndexError, TypeError):
pass
self.mat = tuple(self._sympify(x) for x in mat)
self.rows, self.cols = rows, cols
if self.rows is None or self.cols is None:
raise NotImplementedError("Cannot initialize matrix with given parameters")
def __getitem__(self, key):
def _normalize_slices(row_slice, col_slice):
"""Ensure that row_slice and col_slice don't have
`None` in their arguments. Any integers are converted
to slices of length 1"""
if not isinstance(row_slice, slice):
row_slice = slice(row_slice, row_slice + 1, None)
row_slice = slice(*row_slice.indices(self.rows))
if not isinstance(col_slice, slice):
col_slice = slice(col_slice, col_slice + 1, None)
col_slice = slice(*col_slice.indices(self.cols))
return (row_slice, col_slice)
def _coord_to_index(i, j):
"""Return the index in _mat corresponding
to the (i,j) position in the matrix. """
return i * self.cols + j
if isinstance(key, tuple):
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
# if the coordinates are not slices, make them so
# and expand the slices so they don't contain `None`
i, j = _normalize_slices(i, j)
rowsList, colsList = list(range(self.rows))[i], \
list(range(self.cols))[j]
indices = (i * self.cols + j for i in rowsList for j in
colsList)
return self._new(len(rowsList), len(colsList),
list(self.mat[i] for i in indices))
# if the key is a tuple of ints, change
# it to an array index
key = _coord_to_index(i, j)
return self.mat[key]
def __eq__(self, other):
try:
classof(self, other)
except TypeError:
return False
return (
self.shape == other.shape and list(self) == list(other))
def __len__(self):
return self.rows*self.cols
def __repr__(self):
return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols,
self.mat)
@property
def shape(self):
return (self.rows, self.cols)
class _CastableMatrix: # this is needed here ONLY FOR TESTS.
def as_mutable(self):
return self
def as_immutable(self):
return self
class _MatrixWrapper:
"""Wrapper class providing the minimum functionality for a matrix-like
object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
math operations should work on matrix-like objects. This one is intended for
matrix-like objects which use the same indexing format as SymPy with respect
to returning matrix elements instead of rows for non-tuple indexes.
"""
is_Matrix = False # needs to be here because of __getattr__
is_MatrixLike = True
def __init__(self, mat, shape):
self.mat = mat
self.shape = shape
self.rows, self.cols = shape
def __getitem__(self, key):
if isinstance(key, tuple):
return sympify(self.mat.__getitem__(key))
return sympify(self.mat.__getitem__((key // self.rows, key % self.cols)))
def __iter__(self): # supports numpy.matrix and numpy.array
mat = self.mat
cols = self.cols
return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols))
class MatrixKind(Kind):
"""
Kind for all matrices in SymPy.
Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``,
but any expression representing the matrix can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the matrix contains only numbers.
Examples
========
Any instance of matrix class has ``MatrixKind``.
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 2,2)
>>> A.kind
MatrixKind(NumberKind)
Although expression representing a matrix may be not instance of
matrix class, it will have ``MatrixKind`` as well.
>>> from sympy import Integral
>>> from sympy.matrices.expressions import MatrixExpr
>>> from sympy.abc import x
>>> intM = Integral(A, x)
>>> isinstance(intM, MatrixExpr)
False
>>> intM.kind
MatrixKind(NumberKind)
Use ``isinstance()`` to check for ``MatrixKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy import Matrix
>>> from sympy.matrices import MatrixKind
>>> from sympy.core.kind import NumberKind
>>> boolM = Matrix([True, False])
>>> isinstance(boolM.kind, MatrixKind)
True
>>> boolM.kind is MatrixKind(NumberKind)
False
See Also
========
shape : Function to return the shape of objects with ``MatrixKind``.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "MatrixKind(%s)" % self.element_kind
def _matrixify(mat):
"""If `mat` is a Matrix or is matrix-like,
return a Matrix or MatrixWrapper object. Otherwise
`mat` is passed through without modification."""
if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
return mat
if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)):
return mat
shape = None
if hasattr(mat, 'shape'): # numpy, scipy.sparse
if len(mat.shape) == 2:
shape = mat.shape
elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath
shape = (mat.rows, mat.cols)
if shape:
return _MatrixWrapper(mat, shape)
return mat
def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if type(j) is not int:
jindex = getattr(j, '__index__', None)
if jindex is not None:
j = jindex()
else:
raise IndexError("Invalid index a[%r]" % (j,))
if n is not None:
if j < 0:
j += n
if not (j >= 0 and j < n):
raise IndexError("Index out of range: a[%s]" % (j,))
return int(j)
def classof(A, B):
"""
Get the type of the result when combining matrices of different types.
Currently the strategy is that immutability is contagious.
Examples
========
>>> from sympy import Matrix, ImmutableMatrix
>>> from sympy.matrices.common import classof
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
>>> classof(M, IM)
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
"""
priority_A = getattr(A, '_class_priority', None)
priority_B = getattr(B, '_class_priority', None)
if None not in (priority_A, priority_B):
if A._class_priority > B._class_priority:
return A.__class__
else:
return B.__class__
try:
import numpy
except ImportError:
pass
else:
if isinstance(A, numpy.ndarray):
return B.__class__
if isinstance(B, numpy.ndarray):
return A.__class__
raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
|
6a94ac457894496a0cc52adb9e4043d05140764ecaae5a9d569a7ea3fae12d1a | import mpmath as mp
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.compatibility import (
Callable, NotIterable, as_int, is_sequence)
from sympy.core.decorators import deprecated
from sympy.core.expr import Expr
from sympy.core.kind import _NumberKind, NumberKind, UndefinedKind
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol, uniquely_named_symbol
from sympy.core.sympify import sympify
from sympy.core.sympify import _sympify
from sympy.functions import exp, factorial, log
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import cancel
from sympy.printing import sstr
from sympy.printing.defaults import Printable
from sympy.simplify import simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
from .common import (
MatrixCommon, MatrixError, NonSquareMatrixError, NonInvertibleMatrixError,
ShapeError, MatrixKind)
from .utilities import _iszero, _is_zero_after_expand_mul
from .determinant import (
_find_reasonable_pivot, _find_reasonable_pivot_naive,
_adjugate, _charpoly, _cofactor, _cofactor_matrix, _per,
_det, _det_bareiss, _det_berkowitz, _det_LU, _minor, _minor_submatrix)
from .reductions import _is_echelon, _echelon_form, _rank, _rref
from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize
from .eigen import (
_eigenvals, _eigenvects,
_bidiagonalize, _bidiagonal_decomposition,
_is_diagonalizable, _diagonalize,
_is_positive_definite, _is_positive_semidefinite,
_is_negative_definite, _is_negative_semidefinite, _is_indefinite,
_jordan_form, _left_eigenvects, _singular_values)
from .decompositions import (
_rank_decomposition, _cholesky, _LDLdecomposition,
_LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF,
_singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition)
from .graph import _connected_components, _connected_components_decomposition
from .solvers import (
_diagonal_solve, _lower_triangular_solve, _upper_triangular_solve,
_cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve,
_pinv_solve, _solve, _solve_least_squares)
from .inverse import (
_pinv, _inv_mod, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR,
_inv, _inv_block)
class DeferredVector(Symbol, NotIterable):
"""A vector whose components are deferred (e.g. for use with lambdify)
Examples
========
>>> from sympy import DeferredVector, lambdify
>>> X = DeferredVector( 'X' )
>>> X
X
>>> expr = (X[0] + 2, X[2] + 3)
>>> func = lambdify( X, expr)
>>> func( [1, 2, 3] )
(3, 6)
"""
def __getitem__(self, i):
if i == -0:
i = 0
if i < 0:
raise IndexError('DeferredVector index out of range')
component_name = '%s[%d]' % (self.name, i)
return Symbol(component_name)
def __str__(self):
return sstr(self)
def __repr__(self):
return "DeferredVector('%s')" % self.name
class MatrixDeterminant(MatrixCommon):
"""Provides basic matrix determinant operations. Should not be instantiated
directly. See ``determinant.py`` for their implementations."""
def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul):
return _det_bareiss(self, iszerofunc=iszerofunc)
def _eval_det_berkowitz(self):
return _det_berkowitz(self)
def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None):
return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc)
def _eval_determinant(self): # for expressions.determinant.Determinant
return _det(self)
def adjugate(self, method="berkowitz"):
return _adjugate(self, method=method)
def charpoly(self, x='lambda', simplify=_simplify):
return _charpoly(self, x=x, simplify=simplify)
def cofactor(self, i, j, method="berkowitz"):
return _cofactor(self, i, j, method=method)
def cofactor_matrix(self, method="berkowitz"):
return _cofactor_matrix(self, method=method)
def det(self, method="bareiss", iszerofunc=None):
return _det(self, method=method, iszerofunc=iszerofunc)
def per(self):
return _per(self)
def minor(self, i, j, method="berkowitz"):
return _minor(self, i, j, method=method)
def minor_submatrix(self, i, j):
return _minor_submatrix(self, i, j)
_find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__
_find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__
_eval_det_bareiss.__doc__ = _det_bareiss.__doc__
_eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__
_eval_det_lu.__doc__ = _det_LU.__doc__
_eval_determinant.__doc__ = _det.__doc__
adjugate.__doc__ = _adjugate.__doc__
charpoly.__doc__ = _charpoly.__doc__
cofactor.__doc__ = _cofactor.__doc__
cofactor_matrix.__doc__ = _cofactor_matrix.__doc__
det.__doc__ = _det.__doc__
per.__doc__ = _per.__doc__
minor.__doc__ = _minor.__doc__
minor_submatrix.__doc__ = _minor_submatrix.__doc__
class MatrixReductions(MatrixDeterminant):
"""Provides basic matrix row/column operations. Should not be instantiated
directly. See ``reductions.py`` for some of their implementations."""
def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False):
return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify,
with_pivots=with_pivots)
@property
def is_echelon(self):
return _is_echelon(self)
def rank(self, iszerofunc=_iszero, simplify=False):
return _rank(self, iszerofunc=iszerofunc, simplify=simplify)
def rref(self, iszerofunc=_iszero, simplify=False, pivots=True,
normalize_last=True):
return _rref(self, iszerofunc=iszerofunc, simplify=simplify,
pivots=pivots, normalize_last=normalize_last)
echelon_form.__doc__ = _echelon_form.__doc__
is_echelon.__doc__ = _is_echelon.__doc__
rank.__doc__ = _rank.__doc__
rref.__doc__ = _rref.__doc__
def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"):
"""Validate the arguments for a row/column operation. ``error_str``
can be one of "row" or "col" depending on the arguments being parsed."""
if op not in ["n->kn", "n<->m", "n->n+km"]:
raise ValueError("Unknown {} operation '{}'. Valid col operations "
"are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op))
# define self_col according to error_str
self_cols = self.cols if error_str == 'col' else self.rows
# normalize and validate the arguments
if op == "n->kn":
col = col if col is not None else col1
if col is None or k is None:
raise ValueError("For a {0} operation 'n->kn' you must provide the "
"kwargs `{0}` and `k`".format(error_str))
if not 0 <= col < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col))
elif op == "n<->m":
# we need two cols to swap. It doesn't matter
# how they were specified, so gather them together and
# remove `None`
cols = {col, k, col1, col2}.difference([None])
if len(cols) > 2:
# maybe the user left `k` by mistake?
cols = {col, col1, col2}.difference([None])
if len(cols) != 2:
raise ValueError("For a {0} operation 'n<->m' you must provide the "
"kwargs `{0}1` and `{0}2`".format(error_str))
col1, col2 = cols
if not 0 <= col1 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col1))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col2))
elif op == "n->n+km":
col = col1 if col is None else col
col2 = col1 if col2 is None else col2
if col is None or col2 is None or k is None:
raise ValueError("For a {0} operation 'n->n+km' you must provide the "
"kwargs `{0}`, `k`, and `{0}2`".format(error_str))
if col == col2:
raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must "
"be different.".format(error_str))
if not 0 <= col < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col2))
else:
raise ValueError('invalid operation %s' % repr(op))
return op, col, k, col1, col2
def _eval_col_op_multiply_col_by_const(self, col, k):
def entry(i, j):
if j == col:
return k * self[i, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_col_op_swap(self, col1, col2):
def entry(i, j):
if j == col1:
return self[i, col2]
elif j == col2:
return self[i, col1]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_col_op_add_multiple_to_other_col(self, col, k, col2):
def entry(i, j):
if j == col:
return self[i, j] + k * self[i, col2]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_swap(self, row1, row2):
def entry(i, j):
if i == row1:
return self[row2, j]
elif i == row2:
return self[row1, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_multiply_row_by_const(self, row, k):
def entry(i, j):
if i == row:
return k * self[i, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_add_multiple_to_other_row(self, row, k, row2):
def entry(i, j):
if i == row:
return self[i, j] + k * self[row2, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None):
"""Performs the elementary column operation `op`.
`op` may be one of
* "n->kn" (column n goes to k*n)
* "n<->m" (swap column n and column m)
* "n->n+km" (column n goes to column n + k*column m)
Parameters
==========
op : string; the elementary row operation
col : the column to apply the column operation
k : the multiple to apply in the column operation
col1 : one column of a column swap
col2 : second column of a column swap or column "m" in the column operation
"n->n+km"
"""
op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col")
# now that we've validated, we're all good to dispatch
if op == "n->kn":
return self._eval_col_op_multiply_col_by_const(col, k)
if op == "n<->m":
return self._eval_col_op_swap(col1, col2)
if op == "n->n+km":
return self._eval_col_op_add_multiple_to_other_col(col, k, col2)
def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None):
"""Performs the elementary row operation `op`.
`op` may be one of
* "n->kn" (row n goes to k*n)
* "n<->m" (swap row n and row m)
* "n->n+km" (row n goes to row n + k*row m)
Parameters
==========
op : string; the elementary row operation
row : the row to apply the row operation
k : the multiple to apply in the row operation
row1 : one row of a row swap
row2 : second row of a row swap or row "m" in the row operation
"n->n+km"
"""
op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row")
# now that we've validated, we're all good to dispatch
if op == "n->kn":
return self._eval_row_op_multiply_row_by_const(row, k)
if op == "n<->m":
return self._eval_row_op_swap(row1, row2)
if op == "n->n+km":
return self._eval_row_op_add_multiple_to_other_row(row, k, row2)
class MatrixSubspaces(MatrixReductions):
"""Provides methods relating to the fundamental subspaces of a matrix.
Should not be instantiated directly. See ``subspaces.py`` for their
implementations."""
def columnspace(self, simplify=False):
return _columnspace(self, simplify=simplify)
def nullspace(self, simplify=False, iszerofunc=_iszero):
return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc)
def rowspace(self, simplify=False):
return _rowspace(self, simplify=simplify)
# This is a classmethod but is converted to such later in order to allow
# assignment of __doc__ since that does not work for already wrapped
# classmethods in Python 3.6.
def orthogonalize(cls, *vecs, **kwargs):
return _orthogonalize(cls, *vecs, **kwargs)
columnspace.__doc__ = _columnspace.__doc__
nullspace.__doc__ = _nullspace.__doc__
rowspace.__doc__ = _rowspace.__doc__
orthogonalize.__doc__ = _orthogonalize.__doc__
orthogonalize = classmethod(orthogonalize) # type:ignore
class MatrixEigen(MatrixSubspaces):
"""Provides basic matrix eigenvalue/vector operations.
Should not be instantiated directly. See ``eigen.py`` for their
implementations."""
def eigenvals(self, error_when_incomplete=True, **flags):
return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags)
def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags):
return _eigenvects(self, error_when_incomplete=error_when_incomplete,
iszerofunc=iszerofunc, **flags)
def is_diagonalizable(self, reals_only=False, **kwargs):
return _is_diagonalizable(self, reals_only=reals_only, **kwargs)
def diagonalize(self, reals_only=False, sort=False, normalize=False):
return _diagonalize(self, reals_only=reals_only, sort=sort,
normalize=normalize)
def bidiagonalize(self, upper=True):
return _bidiagonalize(self, upper=upper)
def bidiagonal_decomposition(self, upper=True):
return _bidiagonal_decomposition(self, upper=upper)
@property
def is_positive_definite(self):
return _is_positive_definite(self)
@property
def is_positive_semidefinite(self):
return _is_positive_semidefinite(self)
@property
def is_negative_definite(self):
return _is_negative_definite(self)
@property
def is_negative_semidefinite(self):
return _is_negative_semidefinite(self)
@property
def is_indefinite(self):
return _is_indefinite(self)
def jordan_form(self, calc_transform=True, **kwargs):
return _jordan_form(self, calc_transform=calc_transform, **kwargs)
def left_eigenvects(self, **flags):
return _left_eigenvects(self, **flags)
def singular_values(self):
return _singular_values(self)
eigenvals.__doc__ = _eigenvals.__doc__
eigenvects.__doc__ = _eigenvects.__doc__
is_diagonalizable.__doc__ = _is_diagonalizable.__doc__
diagonalize.__doc__ = _diagonalize.__doc__
is_positive_definite.__doc__ = _is_positive_definite.__doc__
is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__
is_negative_definite.__doc__ = _is_negative_definite.__doc__
is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__
is_indefinite.__doc__ = _is_indefinite.__doc__
jordan_form.__doc__ = _jordan_form.__doc__
left_eigenvects.__doc__ = _left_eigenvects.__doc__
singular_values.__doc__ = _singular_values.__doc__
bidiagonalize.__doc__ = _bidiagonalize.__doc__
bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__
class MatrixCalculus(MatrixCommon):
"""Provides calculus-related matrix operations."""
def diff(self, *args, **kwargs):
"""Calculate the derivative of each element in the matrix.
``args`` will be passed to the ``integrate`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.diff(x)
Matrix([
[1, 0],
[0, 0]])
See Also
========
integrate
limit
"""
# XXX this should be handled here rather than in Derivative
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
deriv = ArrayDerivative(self, *args, evaluate=True)
if not isinstance(self, Basic):
return deriv.as_mutable()
else:
return deriv
def _eval_derivative(self, arg):
return self.applyfunc(lambda x: x.diff(arg))
def integrate(self, *args, **kwargs):
"""Integrate each element of the matrix. ``args`` will
be passed to the ``integrate`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.integrate((x, ))
Matrix([
[x**2/2, x*y],
[ x, 0]])
>>> M.integrate((x, 0, 2))
Matrix([
[2, 2*y],
[2, 0]])
See Also
========
limit
diff
"""
return self.applyfunc(lambda x: x.integrate(*args, **kwargs))
def jacobian(self, X):
"""Calculates the Jacobian matrix (derivative of a vector-valued function).
Parameters
==========
``self`` : vector of expressions representing functions f_i(x_1, ..., x_n).
X : set of x_i's in order, it can be a list or a Matrix
Both ``self`` and X can be a row or a column matrix in any order
(i.e., jacobian() should always work).
Examples
========
>>> from sympy import sin, cos, Matrix
>>> from sympy.abc import rho, phi
>>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
>>> Y = Matrix([rho, phi])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0]])
>>> X = Matrix([rho*cos(phi), rho*sin(phi)])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)]])
See Also
========
hessian
wronskian
"""
if not isinstance(X, MatrixBase):
X = self._new(X)
# Both X and ``self`` can be a row or a column matrix, so we need to make
# sure all valid combinations work, but everything else fails:
if self.shape[0] == 1:
m = self.shape[1]
elif self.shape[1] == 1:
m = self.shape[0]
else:
raise TypeError("``self`` must be a row or a column matrix")
if X.shape[0] == 1:
n = X.shape[1]
elif X.shape[1] == 1:
n = X.shape[0]
else:
raise TypeError("X must be a row or a column matrix")
# m is the number of functions and n is the number of variables
# computing the Jacobian is now easy:
return self._new(m, n, lambda j, i: self[j].diff(X[i]))
def limit(self, *args):
"""Calculate the limit of each element in the matrix.
``args`` will be passed to the ``limit`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.limit(x, 2)
Matrix([
[2, y],
[1, 0]])
See Also
========
integrate
diff
"""
return self.applyfunc(lambda x: x.limit(*args))
# https://github.com/sympy/sympy/pull/12854
class MatrixDeprecated(MatrixCommon):
"""A class to house deprecated matrix methods."""
def _legacy_array_dot(self, b):
"""Compatibility function for deprecated behavior of ``matrix.dot(vector)``
"""
from .dense import Matrix
if not isinstance(b, MatrixBase):
if is_sequence(b):
if len(b) != self.cols and len(b) != self.rows:
raise ShapeError(
"Dimensions incorrect for dot product: %s, %s" % (
self.shape, len(b)))
return self.dot(Matrix(b))
else:
raise TypeError(
"`b` must be an ordered iterable or Matrix, not %s." %
type(b))
mat = self
if mat.cols == b.rows:
if b.cols != 1:
mat = mat.T
b = b.T
prod = flatten((mat * b).tolist())
return prod
if mat.cols == b.cols:
return mat.dot(b.T)
elif mat.rows == b.rows:
return mat.T.dot(b)
else:
raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (
self.shape, b.shape))
def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):
return self.charpoly(x=x)
def berkowitz_det(self):
"""Computes determinant using Berkowitz method.
See Also
========
det
berkowitz
"""
return self.det(method='berkowitz')
def berkowitz_eigenvals(self, **flags):
"""Computes eigenvalues of a Matrix using Berkowitz method.
See Also
========
berkowitz
"""
return self.eigenvals(**flags)
def berkowitz_minors(self):
"""Computes principal minors using Berkowitz method.
See Also
========
berkowitz
"""
sign, minors = self.one, []
for poly in self.berkowitz():
minors.append(sign * poly[-1])
sign = -sign
return tuple(minors)
def berkowitz(self):
from sympy.matrices import zeros
berk = ((1,),)
if not self:
return berk
if not self.is_square:
raise NonSquareMatrixError()
A, N = self, self.rows
transforms = [0] * (N - 1)
for n in range(N, 1, -1):
T, k = zeros(n + 1, n), n - 1
R, C = -A[k, :k], A[:k, k]
A, a = A[:k, :k], -A[k, k]
items = [C]
for i in range(0, n - 2):
items.append(A * items[i])
for i, B in enumerate(items):
items[i] = (R * B)[0, 0]
items = [self.one, a] + items
for i in range(n):
T[i:, i] = items[:n - i + 1]
transforms[k - 1] = T
polys = [self._new([self.one, -A[0, 0]])]
for i, T in enumerate(transforms):
polys.append(T * polys[i])
return berk + tuple(map(tuple, polys))
def cofactorMatrix(self, method="berkowitz"):
return self.cofactor_matrix(method=method)
def det_bareis(self):
return _det_bareiss(self)
def det_LU_decomposition(self):
"""Compute matrix determinant using LU decomposition
Note that this method fails if the LU decomposition itself
fails. In particular, if the matrix has no inverse this method
will fail.
TODO: Implement algorithm for sparse matrices (SFF),
http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
See Also
========
det
det_bareiss
berkowitz_det
"""
return self.det(method='lu')
def jordan_cell(self, eigenval, n):
return self.jordan_block(size=n, eigenvalue=eigenval)
def jordan_cells(self, calc_transformation=True):
P, J = self.jordan_form()
return P, J.get_diag_blocks()
def minorEntry(self, i, j, method="berkowitz"):
return self.minor(i, j, method=method)
def minorMatrix(self, i, j):
return self.minor_submatrix(i, j)
def permuteBkwd(self, perm):
"""Permute the rows of the matrix with the given permutation in reverse."""
return self.permute_rows(perm, direction='backward')
def permuteFwd(self, perm):
"""Permute the rows of the matrix with the given permutation."""
return self.permute_rows(perm, direction='forward')
@Mul._kind_dispatcher.register(_NumberKind, MatrixKind)
def num_mat_mul(k1, k2):
"""
Return MatrixKind. The element kind is selected by recursive dispatching.
Do not need to dispatch in reversed order because KindDispatcher
searches for this automatically.
"""
# Deal with Mul._kind_dispatcher's commutativity
elemk = Mul._kind_dispatcher(NumberKind, k2.element_kind)
return MatrixKind(elemk)
@Mul._kind_dispatcher.register(MatrixKind, MatrixKind)
def mat_mat_mul(k1, k2):
"""
Return MatrixKind. The element kind is selected by recursive dispatching.
"""
elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind)
return MatrixKind(elemk)
class MatrixBase(MatrixDeprecated,
MatrixCalculus,
MatrixEigen,
MatrixCommon,
Printable):
"""Base class for matrix objects."""
# Added just for numpy compatibility
__array_priority__ = 11
is_Matrix = True
_class_priority = 3
_sympify = staticmethod(sympify)
zero = S.Zero
one = S.One
@property
def kind(self):
elem_kinds = set(e.kind for e in self._mat)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return MatrixKind(elemkind)
def __array__(self, dtype=object):
from .dense import matrix2numpy
return matrix2numpy(self, dtype=dtype)
def __len__(self):
"""Return the number of elements of ``self``.
Implemented mainly so bool(Matrix()) == False.
"""
return self.rows * self.cols
def _matrix_pow_by_jordan_blocks(self, num):
from sympy.matrices import diag, MutableMatrix
from sympy import binomial
def jordan_cell_power(jc, n):
N = jc.shape[0]
l = jc[0,0]
if l.is_zero:
if N == 1 and n.is_nonnegative:
jc[0,0] = l**n
elif not (n.is_integer and n.is_nonnegative):
raise NonInvertibleMatrixError("Non-invertible matrix can only be raised to a nonnegative integer")
else:
for i in range(N):
jc[0,i] = KroneckerDelta(i, n)
else:
for i in range(N):
bn = binomial(n, i)
if isinstance(bn, binomial):
bn = bn._eval_expand_func()
jc[0,i] = l**(n-i)*bn
for i in range(N):
for j in range(1, N-i):
jc[j,i+j] = jc [j-1,i+j-1]
P, J = self.jordan_form()
jordan_cells = J.get_diag_blocks()
# Make sure jordan_cells matrices are mutable:
jordan_cells = [MutableMatrix(j) for j in jordan_cells]
for j in jordan_cells:
jordan_cell_power(j, num)
return self._new(P.multiply(diag(*jordan_cells))
.multiply(P.inv()))
def __str__(self):
if self.rows == 0 or self.cols == 0:
return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
return "Matrix(%s)" % str(self.tolist())
def _format_str(self, printer=None):
if not printer:
from sympy.printing.str import StrPrinter
printer = StrPrinter()
# Handle zero dimensions:
if self.rows == 0 or self.cols == 0:
return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
if self.rows == 1:
return "Matrix([%s])" % self.table(printer, rowsep=',\n')
return "Matrix([\n%s])" % self.table(printer, rowsep=',\n')
@classmethod
def irregular(cls, ntop, *matrices, **kwargs):
"""Return a matrix filled by the given matrices which
are listed in order of appearance from left to right, top to
bottom as they first appear in the matrix. They must fill the
matrix completely.
Examples
========
>>> from sympy import ones, Matrix
>>> Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
... ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7)
Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
"""
from sympy.core.compatibility import as_int
ntop = as_int(ntop)
# make sure we are working with explicit matrices
b = [i.as_explicit() if hasattr(i, 'as_explicit') else i
for i in matrices]
q = list(range(len(b)))
dat = [i.rows for i in b]
active = [q.pop(0) for _ in range(ntop)]
cols = sum([b[i].cols for i in active])
rows = []
while any(dat):
r = []
for a, j in enumerate(active):
r.extend(b[j][-dat[j], :])
dat[j] -= 1
if dat[j] == 0 and q:
active[a] = q.pop(0)
if len(r) != cols:
raise ValueError(filldedent('''
Matrices provided do not appear to fill
the space completely.'''))
rows.append(r)
return cls._new(rows)
@classmethod
def _handle_ndarray(cls, arg):
# NumPy array or matrix or some other object that implements
# __array__. So let's first use this method to get a
# numpy.array() and then make a python list out of it.
arr = arg.__array__()
if len(arr.shape) == 2:
rows, cols = arr.shape[0], arr.shape[1]
flat_list = [cls._sympify(i) for i in arr.ravel()]
return rows, cols, flat_list
elif len(arr.shape) == 1:
flat_list = [cls._sympify(i) for i in arr]
return arr.shape[0], 1, flat_list
else:
raise NotImplementedError(
"SymPy supports just 1D and 2D matrices")
@classmethod
def _handle_creation_inputs(cls, *args, **kwargs):
"""Return the number of rows, cols and flat matrix elements.
Examples
========
>>> from sympy import Matrix, I
Matrix can be constructed as follows:
* from a nested list of iterables
>>> Matrix( ((1, 2+I), (3, 4)) )
Matrix([
[1, 2 + I],
[3, 4]])
* from un-nested iterable (interpreted as a column)
>>> Matrix( [1, 2] )
Matrix([
[1],
[2]])
* from un-nested iterable with dimensions
>>> Matrix(1, 2, [1, 2] )
Matrix([[1, 2]])
* from no arguments (a 0 x 0 matrix)
>>> Matrix()
Matrix(0, 0, [])
* from a rule
>>> Matrix(2, 2, lambda i, j: i/(j + 1) )
Matrix([
[0, 0],
[1, 1/2]])
See Also
========
irregular - filling a matrix with irregular blocks
"""
from sympy.matrices.sparse import SparseMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.utilities.iterables import reshape
flat_list = None
if len(args) == 1:
# Matrix(SparseMatrix(...))
if isinstance(args[0], SparseMatrix):
return args[0].rows, args[0].cols, flatten(args[0].tolist())
# Matrix(Matrix(...))
elif isinstance(args[0], MatrixBase):
return args[0].rows, args[0].cols, args[0]._mat
# Matrix(MatrixSymbol('X', 2, 2))
elif isinstance(args[0], Basic) and args[0].is_Matrix:
return args[0].rows, args[0].cols, args[0].as_explicit()._mat
elif isinstance(args[0], mp.matrix):
M = args[0]
flat_list = [cls._sympify(x) for x in M]
return M.rows, M.cols, flat_list
# Matrix(numpy.ones((2, 2)))
elif hasattr(args[0], "__array__"):
return cls._handle_ndarray(args[0])
# Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]])
elif is_sequence(args[0]) \
and not isinstance(args[0], DeferredVector):
dat = list(args[0])
ismat = lambda i: isinstance(i, MatrixBase) and (
evaluate or
isinstance(i, BlockMatrix) or
isinstance(i, MatrixSymbol))
raw = lambda i: is_sequence(i) and not ismat(i)
evaluate = kwargs.get('evaluate', True)
if evaluate:
def do(x):
# make Block and Symbol explicit
if isinstance(x, (list, tuple)):
return type(x)([do(i) for i in x])
if isinstance(x, BlockMatrix) or \
isinstance(x, MatrixSymbol) and \
all(_.is_Integer for _ in x.shape):
return x.as_explicit()
return x
dat = do(dat)
if dat == [] or dat == [[]]:
rows = cols = 0
flat_list = []
elif not any(raw(i) or ismat(i) for i in dat):
# a column as a list of values
flat_list = [cls._sympify(i) for i in dat]
rows = len(flat_list)
cols = 1 if rows else 0
elif evaluate and all(ismat(i) for i in dat):
# a column as a list of matrices
ncol = {i.cols for i in dat if any(i.shape)}
if ncol:
if len(ncol) != 1:
raise ValueError('mismatched dimensions')
flat_list = [_ for i in dat for r in i.tolist() for _ in r]
cols = ncol.pop()
rows = len(flat_list)//cols
else:
rows = cols = 0
flat_list = []
elif evaluate and any(ismat(i) for i in dat):
ncol = set()
flat_list = []
for i in dat:
if ismat(i):
flat_list.extend(
[k for j in i.tolist() for k in j])
if any(i.shape):
ncol.add(i.cols)
elif raw(i):
if i:
ncol.add(len(i))
flat_list.extend(i)
else:
ncol.add(1)
flat_list.append(i)
if len(ncol) > 1:
raise ValueError('mismatched dimensions')
cols = ncol.pop()
rows = len(flat_list)//cols
else:
# list of lists; each sublist is a logical row
# which might consist of many rows if the values in
# the row are matrices
flat_list = []
ncol = set()
rows = cols = 0
for row in dat:
if not is_sequence(row) and \
not getattr(row, 'is_Matrix', False):
raise ValueError('expecting list of lists')
if hasattr(row, '__array__'):
if 0 in row.shape:
continue
elif not row:
continue
if evaluate and all(ismat(i) for i in row):
r, c, flatT = cls._handle_creation_inputs(
[i.T for i in row])
T = reshape(flatT, [c])
flat = \
[T[i][j] for j in range(c) for i in range(r)]
r, c = c, r
else:
r = 1
if getattr(row, 'is_Matrix', False):
c = 1
flat = [row]
else:
c = len(row)
flat = [cls._sympify(i) for i in row]
ncol.add(c)
if len(ncol) > 1:
raise ValueError('mismatched dimensions')
flat_list.extend(flat)
rows += r
cols = ncol.pop() if ncol else 0
elif len(args) == 3:
rows = as_int(args[0])
cols = as_int(args[1])
if rows < 0 or cols < 0:
raise ValueError("Cannot create a {} x {} matrix. "
"Both dimensions must be positive".format(rows, cols))
# Matrix(2, 2, lambda i, j: i+j)
if len(args) == 3 and isinstance(args[2], Callable):
op = args[2]
flat_list = []
for i in range(rows):
flat_list.extend(
[cls._sympify(op(cls._sympify(i), cls._sympify(j)))
for j in range(cols)])
# Matrix(2, 2, [1, 2, 3, 4])
elif len(args) == 3 and is_sequence(args[2]):
flat_list = args[2]
if len(flat_list) != rows * cols:
raise ValueError(
'List length should be equal to rows*columns')
flat_list = [cls._sympify(i) for i in flat_list]
# Matrix()
elif len(args) == 0:
# Empty Matrix
rows = cols = 0
flat_list = []
if flat_list is None:
raise TypeError(filldedent('''
Data type not understood; expecting list of lists
or lists of values.'''))
return rows, cols, flat_list
def _setitem(self, key, value):
"""Helper to set value at location given by key.
Examples
========
>>> from sympy import Matrix, I, zeros, ones
>>> m = Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3, 4]])
>>> m[1, 0] = 9
>>> m
Matrix([
[1, 2 + I],
[9, 4]])
>>> m[1, 0] = [[0, 1]]
To replace row r you assign to position r*m where m
is the number of columns:
>>> M = zeros(4)
>>> m = M.cols
>>> M[3*m] = ones(1, m)*2; M
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[2, 2, 2, 2]])
And to replace column c you can assign to position c:
>>> M[2] = ones(m, 1)*4; M
Matrix([
[0, 0, 4, 0],
[0, 0, 4, 0],
[0, 0, 4, 0],
[2, 2, 4, 2]])
"""
from .dense import Matrix
is_slice = isinstance(key, slice)
i, j = key = self.key2ij(key)
is_mat = isinstance(value, MatrixBase)
if type(i) is slice or type(j) is slice:
if is_mat:
self.copyin_matrix(key, value)
return
if not isinstance(value, Expr) and is_sequence(value):
self.copyin_list(key, value)
return
raise ValueError('unexpected value: %s' % value)
else:
if (not is_mat and
not isinstance(value, Basic) and is_sequence(value)):
value = Matrix(value)
is_mat = True
if is_mat:
if is_slice:
key = (slice(*divmod(i, self.cols)),
slice(*divmod(j, self.cols)))
else:
key = (slice(i, i + value.rows),
slice(j, j + value.cols))
self.copyin_matrix(key, value)
else:
return i, j, self._sympify(value)
return
def add(self, b):
"""Return self + b """
return self + b
def condition_number(self):
"""Returns the condition number of a matrix.
This is the maximum singular value divided by the minimum singular value
Examples
========
>>> from sympy import Matrix, S
>>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])
>>> A.condition_number()
100
See Also
========
singular_values
"""
if not self:
return self.zero
singularvalues = self.singular_values()
return Max(*singularvalues) / Min(*singularvalues)
def copy(self):
"""
Returns the copy of a matrix.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.copy()
Matrix([
[1, 2],
[3, 4]])
"""
return self._new(self.rows, self.cols, self._mat)
def cross(self, b):
r"""
Return the cross product of ``self`` and ``b`` relaxing the condition
of compatible dimensions: if each has 3 elements, a matrix of the
same type and shape as ``self`` will be returned. If ``b`` has the same
shape as ``self`` then common identities for the cross product (like
`a \times b = - b \times a`) will hold.
Parameters
==========
b : 3x1 or 1x3 Matrix
See Also
========
dot
multiply
multiply_elementwise
"""
from sympy.matrices.expressions.matexpr import MatrixExpr
if not isinstance(b, MatrixBase) and not isinstance(b, MatrixExpr):
raise TypeError(
"{} must be a Matrix, not {}.".format(b, type(b)))
if not (self.rows * self.cols == b.rows * b.cols == 3):
raise ShapeError("Dimensions incorrect for cross product: %s x %s" %
((self.rows, self.cols), (b.rows, b.cols)))
else:
return self._new(self.rows, self.cols, (
(self[1] * b[2] - self[2] * b[1]),
(self[2] * b[0] - self[0] * b[2]),
(self[0] * b[1] - self[1] * b[0])))
@property
def D(self):
"""Return Dirac conjugate (if ``self.rows == 4``).
Examples
========
>>> from sympy import Matrix, I, eye
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m.D
Matrix([[0, 1 - I, -2, -3]])
>>> m = (eye(4) + I*eye(4))
>>> m[0, 3] = 2
>>> m.D
Matrix([
[1 - I, 0, 0, 0],
[ 0, 1 - I, 0, 0],
[ 0, 0, -1 + I, 0],
[ 2, 0, 0, -1 + I]])
If the matrix does not have 4 rows an AttributeError will be raised
because this property is only defined for matrices with 4 rows.
>>> Matrix(eye(2)).D
Traceback (most recent call last):
...
AttributeError: Matrix has no attribute D.
See Also
========
sympy.matrices.common.MatrixCommon.conjugate: By-element conjugation
sympy.matrices.common.MatrixCommon.H: Hermite conjugation
"""
from sympy.physics.matrices import mgamma
if self.rows != 4:
# In Python 3.2, properties can only return an AttributeError
# so we can't raise a ShapeError -- see commit which added the
# first line of this inline comment. Also, there is no need
# for a message since MatrixBase will raise the AttributeError
raise AttributeError
return self.H * mgamma(0)
def dot(self, b, hermitian=None, conjugate_convention=None):
"""Return the dot or inner product of two vectors of equal length.
Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b``
must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n.
A scalar is returned.
By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are
complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``)
to compute the hermitian inner product.
Possible kwargs are ``hermitian`` and ``conjugate_convention``.
If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``,
the conjugate of the first vector (``self``) is used. If ``"right"``
or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> v = Matrix([1, 1, 1])
>>> M.row(0).dot(v)
6
>>> M.col(0).dot(v)
12
>>> v = [3, 2, 1]
>>> M.row(0).dot(v)
10
>>> from sympy import I
>>> q = Matrix([1*I, 1*I, 1*I])
>>> q.dot(q, hermitian=False)
-3
>>> q.dot(q, hermitian=True)
3
>>> q1 = Matrix([1, 1, 1*I])
>>> q.dot(q1, hermitian=True, conjugate_convention="maths")
1 - 2*I
>>> q.dot(q1, hermitian=True, conjugate_convention="physics")
1 + 2*I
See Also
========
cross
multiply
multiply_elementwise
"""
from .dense import Matrix
if not isinstance(b, MatrixBase):
if is_sequence(b):
if len(b) != self.cols and len(b) != self.rows:
raise ShapeError(
"Dimensions incorrect for dot product: %s, %s" % (
self.shape, len(b)))
return self.dot(Matrix(b))
else:
raise TypeError(
"`b` must be an ordered iterable or Matrix, not %s." %
type(b))
mat = self
if (1 not in mat.shape) or (1 not in b.shape) :
SymPyDeprecationWarning(
feature="Dot product of non row/column vectors",
issue=13815,
deprecated_since_version="1.2",
useinstead="* to take matrix products").warn()
return mat._legacy_array_dot(b)
if len(mat) != len(b):
raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape))
n = len(mat)
if mat.shape != (1, n):
mat = mat.reshape(1, n)
if b.shape != (n, 1):
b = b.reshape(n, 1)
# Now ``mat`` is a row vector and ``b`` is a column vector.
# If it so happens that only conjugate_convention is passed
# then automatically set hermitian to True. If only hermitian
# is true but no conjugate_convention is not passed then
# automatically set it to ``"maths"``
if conjugate_convention is not None and hermitian is None:
hermitian = True
if hermitian and conjugate_convention is None:
conjugate_convention = "maths"
if hermitian == True:
if conjugate_convention in ("maths", "left", "math"):
mat = mat.conjugate()
elif conjugate_convention in ("physics", "right"):
b = b.conjugate()
else:
raise ValueError("Unknown conjugate_convention was entered."
" conjugate_convention must be one of the"
" following: math, maths, left, physics or right.")
return (mat * b)[0]
def dual(self):
"""Returns the dual of a matrix, which is:
``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l`
Since the levicivita method is anti_symmetric for any pairwise
exchange of indices, the dual of a symmetric matrix is the zero
matrix. Strictly speaking the dual defined here assumes that the
'matrix' `M` is a contravariant anti_symmetric second rank tensor,
so that the dual is a covariant second rank tensor.
"""
from sympy import LeviCivita
from sympy.matrices import zeros
M, n = self[:, :], self.rows
work = zeros(n)
if self.is_symmetric():
return work
for i in range(1, n):
for j in range(1, n):
acum = 0
for k in range(1, n):
acum += LeviCivita(i, j, 0, k) * M[0, k]
work[i, j] = acum
work[j, i] = -acum
for l in range(1, n):
acum = 0
for a in range(1, n):
for b in range(1, n):
acum += LeviCivita(0, l, a, b) * M[a, b]
acum /= 2
work[0, l] = -acum
work[l, 0] = acum
return work
def _eval_matrix_exp_jblock(self):
"""A helper function to compute an exponential of a Jordan block
matrix
Examples
========
>>> from sympy import Symbol, Matrix
>>> l = Symbol('lamda')
A trivial example of 1*1 Jordan block:
>>> m = Matrix.jordan_block(1, l)
>>> m._eval_matrix_exp_jblock()
Matrix([[exp(lamda)]])
An example of 3*3 Jordan block:
>>> m = Matrix.jordan_block(3, l)
>>> m._eval_matrix_exp_jblock()
Matrix([
[exp(lamda), exp(lamda), exp(lamda)/2],
[ 0, exp(lamda), exp(lamda)],
[ 0, 0, exp(lamda)]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition
"""
size = self.rows
l = self[0, 0]
exp_l = exp(l)
bands = {i: exp_l / factorial(i) for i in range(size)}
from .sparsetools import banded
return self.__class__(banded(size, bands))
def analytic_func(self, f, x):
"""
Computes f(A) where A is a Square Matrix
and f is an analytic function.
Examples
========
>>> from sympy import Symbol, Matrix, S, log
>>> x = Symbol('x')
>>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
>>> f = log(x)
>>> m.analytic_func(f, x)
Matrix([
[ 0, log(2)],
[log(2), 0]])
Parameters
==========
f : Expr
Analytic Function
x : Symbol
parameter of f
"""
from sympy import diff
f, x = _sympify(f), _sympify(x)
if not self.is_square:
raise NonSquareMatrixError
if not x.is_symbol:
raise ValueError("{} must be a symbol.".format(x))
if x not in f.free_symbols:
raise ValueError(
"{} must be a parameter of {}.".format(x, f))
if x in self.free_symbols:
raise ValueError(
"{} must not be a parameter of {}.".format(x, self))
eigen = self.eigenvals()
max_mul = max(eigen.values())
derivative = {}
dd = f
for i in range(max_mul - 1):
dd = diff(dd, x)
derivative[i + 1] = dd
n = self.shape[0]
r = self.zeros(n)
f_val = self.zeros(n, 1)
row = 0
for i in eigen:
mul = eigen[i]
f_val[row] = f.subs(x, i)
if f_val[row].is_number and not f_val[row].is_complex:
raise ValueError(
"Cannot evaluate the function because the "
"function {} is not analytic at the given "
"eigenvalue {}".format(f, f_val[row]))
val = 1
for a in range(n):
r[row, a] = val
val *= i
if mul > 1:
coe = [1 for ii in range(n)]
deri = 1
while mul > 1:
row = row + 1
mul -= 1
d_i = derivative[deri].subs(x, i)
if d_i.is_number and not d_i.is_complex:
raise ValueError(
"Cannot evaluate the function because the "
"derivative {} is not analytic at the given "
"eigenvalue {}".format(derivative[deri], d_i))
f_val[row] = d_i
for a in range(n):
if a - deri + 1 <= 0:
r[row, a] = 0
coe[a] = 0
continue
coe[a] = coe[a]*(a - deri + 1)
r[row, a] = coe[a]*pow(i, a - deri)
deri += 1
row += 1
c = r.solve(f_val)
ans = self.zeros(n)
pre = self.eye(n)
for i in range(n):
ans = ans + c[i]*pre
pre *= self
return ans
def exp(self):
"""Return the exponential of a square matrix
Examples
========
>>> from sympy import Symbol, Matrix
>>> t = Symbol('t')
>>> m = Matrix([[0, 1], [-1, 0]]) * t
>>> m.exp()
Matrix([
[ exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2],
[I*exp(I*t)/2 - I*exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]])
"""
if not self.is_square:
raise NonSquareMatrixError(
"Exponentiation is valid only for square matrices")
try:
P, J = self.jordan_form()
cells = J.get_diag_blocks()
except MatrixError:
raise NotImplementedError(
"Exponentiation is implemented only for matrices for which the Jordan normal form can be computed")
blocks = [cell._eval_matrix_exp_jblock() for cell in cells]
from sympy.matrices import diag
from sympy import re
eJ = diag(*blocks)
# n = self.rows
ret = P.multiply(eJ, dotprodsimp=None).multiply(P.inv(), dotprodsimp=None)
if all(value.is_real for value in self.values()):
return type(self)(re(ret))
else:
return type(self)(ret)
def _eval_matrix_log_jblock(self):
"""Helper function to compute logarithm of a jordan block.
Examples
========
>>> from sympy import Symbol, Matrix
>>> l = Symbol('lamda')
A trivial example of 1*1 Jordan block:
>>> m = Matrix.jordan_block(1, l)
>>> m._eval_matrix_log_jblock()
Matrix([[log(lamda)]])
An example of 3*3 Jordan block:
>>> m = Matrix.jordan_block(3, l)
>>> m._eval_matrix_log_jblock()
Matrix([
[log(lamda), 1/lamda, -1/(2*lamda**2)],
[ 0, log(lamda), 1/lamda],
[ 0, 0, log(lamda)]])
"""
size = self.rows
l = self[0, 0]
if l.is_zero:
raise MatrixError(
'Could not take logarithm or reciprocal for the given '
'eigenvalue {}'.format(l))
bands = {0: log(l)}
for i in range(1, size):
bands[i] = -((-l) ** -i) / i
from .sparsetools import banded
return self.__class__(banded(size, bands))
def log(self, simplify=cancel):
"""Return the logarithm of a square matrix
Parameters
==========
simplify : function, bool
The function to simplify the result with.
Default is ``cancel``, which is effective to reduce the
expression growing for taking reciprocals and inverses for
symbolic matrices.
Examples
========
>>> from sympy import S, Matrix
Examples for positive-definite matrices:
>>> m = Matrix([[1, 1], [0, 1]])
>>> m.log()
Matrix([
[0, 1],
[0, 0]])
>>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
>>> m.log()
Matrix([
[ 0, log(2)],
[log(2), 0]])
Examples for non positive-definite matrices:
>>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]])
>>> m.log()
Matrix([
[ I*pi/2, log(2) - I*pi/2],
[log(2) - I*pi/2, I*pi/2]])
>>> m = Matrix(
... [[0, 0, 0, 1],
... [0, 0, 1, 0],
... [0, 1, 0, 0],
... [1, 0, 0, 0]])
>>> m.log()
Matrix([
[ I*pi/2, 0, 0, -I*pi/2],
[ 0, I*pi/2, -I*pi/2, 0],
[ 0, -I*pi/2, I*pi/2, 0],
[-I*pi/2, 0, 0, I*pi/2]])
"""
if not self.is_square:
raise NonSquareMatrixError(
"Logarithm is valid only for square matrices")
try:
if simplify:
P, J = simplify(self).jordan_form()
else:
P, J = self.jordan_form()
cells = J.get_diag_blocks()
except MatrixError:
raise NotImplementedError(
"Logarithm is implemented only for matrices for which "
"the Jordan normal form can be computed")
blocks = [
cell._eval_matrix_log_jblock()
for cell in cells]
from sympy.matrices import diag
eJ = diag(*blocks)
if simplify:
ret = simplify(P * eJ * simplify(P.inv()))
ret = self.__class__(ret)
else:
ret = P * eJ * P.inv()
return ret
def is_nilpotent(self):
"""Checks if a matrix is nilpotent.
A matrix B is nilpotent if for some integer k, B**k is
a zero matrix.
Examples
========
>>> from sympy import Matrix
>>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
True
>>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
False
"""
if not self:
return True
if not self.is_square:
raise NonSquareMatrixError(
"Nilpotency is valid only for square matrices")
x = uniquely_named_symbol('x', self, modify=lambda s: '_' + s)
p = self.charpoly(x)
if p.args[0] == x ** self.rows:
return True
return False
def key2bounds(self, keys):
"""Converts a key with potentially mixed types of keys (integer and slice)
into a tuple of ranges and raises an error if any index is out of ``self``'s
range.
See Also
========
key2ij
"""
from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py
islice, jslice = [isinstance(k, slice) for k in keys]
if islice:
if not self.rows:
rlo = rhi = 0
else:
rlo, rhi = keys[0].indices(self.rows)[:2]
else:
rlo = a2idx_(keys[0], self.rows)
rhi = rlo + 1
if jslice:
if not self.cols:
clo = chi = 0
else:
clo, chi = keys[1].indices(self.cols)[:2]
else:
clo = a2idx_(keys[1], self.cols)
chi = clo + 1
return rlo, rhi, clo, chi
def key2ij(self, key):
"""Converts key into canonical form, converting integers or indexable
items into valid integers for ``self``'s range or returning slices
unchanged.
See Also
========
key2bounds
"""
from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py
if is_sequence(key):
if not len(key) == 2:
raise TypeError('key must be a sequence of length 2')
return [a2idx_(i, n) if not isinstance(i, slice) else i
for i, n in zip(key, self.shape)]
elif isinstance(key, slice):
return key.indices(len(self))[:2]
else:
return divmod(a2idx_(key, len(self)), self.cols)
def normalized(self, iszerofunc=_iszero):
"""Return the normalized version of ``self``.
Parameters
==========
iszerofunc : Function, optional
A function to determine whether ``self`` is a zero vector.
The default ``_iszero`` tests to see if each element is
exactly zero.
Returns
=======
Matrix
Normalized vector form of ``self``.
It has the same length as a unit vector. However, a zero vector
will be returned for a vector with norm 0.
Raises
======
ShapeError
If the matrix is not in a vector form.
See Also
========
norm
"""
if self.rows != 1 and self.cols != 1:
raise ShapeError("A Matrix must be a vector to normalize.")
norm = self.norm()
if iszerofunc(norm):
out = self.zeros(self.rows, self.cols)
else:
out = self.applyfunc(lambda i: i / norm)
return out
def norm(self, ord=None):
"""Return the Norm of a Matrix or Vector.
In the simplest case this is the geometric size of the vector
Other norms can be specified by the ord parameter
===== ============================ ==========================
ord norm for matrices norm for vectors
===== ============================ ==========================
None Frobenius norm 2-norm
'fro' Frobenius norm - does not exist
inf maximum row sum max(abs(x))
-inf -- min(abs(x))
1 maximum column sum as below
-1 -- as below
2 2-norm (largest sing. value) as below
-2 smallest singular value as below
other - does not exist sum(abs(x)**ord)**(1./ord)
===== ============================ ==========================
Examples
========
>>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo
>>> x = Symbol('x', real=True)
>>> v = Matrix([cos(x), sin(x)])
>>> trigsimp( v.norm() )
1
>>> v.norm(10)
(sin(x)**10 + cos(x)**10)**(1/10)
>>> A = Matrix([[1, 1], [1, 1]])
>>> A.norm(1) # maximum sum of absolute values of A is 2
2
>>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm)
2
>>> A.norm(-2) # Inverse spectral norm (smallest singular value)
0
>>> A.norm() # Frobenius Norm
2
>>> A.norm(oo) # Infinity Norm
2
>>> Matrix([1, -2]).norm(oo)
2
>>> Matrix([-1, 2]).norm(-oo)
1
See Also
========
normalized
"""
# Row or Column Vector Norms
vals = list(self.values()) or [0]
if self.rows == 1 or self.cols == 1:
if ord == 2 or ord is None: # Common case sqrt(<x, x>)
return sqrt(Add(*(abs(i) ** 2 for i in vals)))
elif ord == 1: # sum(abs(x))
return Add(*(abs(i) for i in vals))
elif ord is S.Infinity: # max(abs(x))
return Max(*[abs(i) for i in vals])
elif ord is S.NegativeInfinity: # min(abs(x))
return Min(*[abs(i) for i in vals])
# Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord)
# Note that while useful this is not mathematically a norm
try:
return Pow(Add(*(abs(i) ** ord for i in vals)), S.One / ord)
except (NotImplementedError, TypeError):
raise ValueError("Expected order to be Number, Symbol, oo")
# Matrix Norms
else:
if ord == 1: # Maximum column sum
m = self.applyfunc(abs)
return Max(*[sum(m.col(i)) for i in range(m.cols)])
elif ord == 2: # Spectral Norm
# Maximum singular value
return Max(*self.singular_values())
elif ord == -2:
# Minimum singular value
return Min(*self.singular_values())
elif ord is S.Infinity: # Infinity Norm - Maximum row sum
m = self.applyfunc(abs)
return Max(*[sum(m.row(i)) for i in range(m.rows)])
elif (ord is None or isinstance(ord,
str) and ord.lower() in
['f', 'fro', 'frobenius', 'vector']):
# Reshape as vector and send back to norm function
return self.vec().norm(ord=2)
else:
raise NotImplementedError("Matrix Norms under development")
def print_nonzero(self, symb="X"):
"""Shows location of non-zero entries for fast shape lookup.
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> m = Matrix(2, 3, lambda i, j: i*3+j)
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5]])
>>> m.print_nonzero()
[ XX]
[XXX]
>>> m = eye(4)
>>> m.print_nonzero("x")
[x ]
[ x ]
[ x ]
[ x]
"""
s = []
for i in range(self.rows):
line = []
for j in range(self.cols):
if self[i, j] == 0:
line.append(" ")
else:
line.append(str(symb))
s.append("[%s]" % ''.join(line))
print('\n'.join(s))
def project(self, v):
"""Return the projection of ``self`` onto the line containing ``v``.
Examples
========
>>> from sympy import Matrix, S, sqrt
>>> V = Matrix([sqrt(3)/2, S.Half])
>>> x = Matrix([[1, 0]])
>>> V.project(x)
Matrix([[sqrt(3)/2, 0]])
>>> V.project(-x)
Matrix([[sqrt(3)/2, 0]])
"""
return v * (self.dot(v) / v.dot(v))
def table(self, printer, rowstart='[', rowend=']', rowsep='\n',
colsep=', ', align='right'):
r"""
String form of Matrix as a table.
``printer`` is the printer to use for on the elements (generally
something like StrPrinter())
``rowstart`` is the string used to start each row (by default '[').
``rowend`` is the string used to end each row (by default ']').
``rowsep`` is the string used to separate rows (by default a newline).
``colsep`` is the string used to separate columns (by default ', ').
``align`` defines how the elements are aligned. Must be one of 'left',
'right', or 'center'. You can also use '<', '>', and '^' to mean the
same thing, respectively.
This is used by the string printer for Matrix.
Examples
========
>>> from sympy import Matrix
>>> from sympy.printing.str import StrPrinter
>>> M = Matrix([[1, 2], [-33, 4]])
>>> printer = StrPrinter()
>>> M.table(printer)
'[ 1, 2]\n[-33, 4]'
>>> print(M.table(printer))
[ 1, 2]
[-33, 4]
>>> print(M.table(printer, rowsep=',\n'))
[ 1, 2],
[-33, 4]
>>> print('[%s]' % M.table(printer, rowsep=',\n'))
[[ 1, 2],
[-33, 4]]
>>> print(M.table(printer, colsep=' '))
[ 1 2]
[-33 4]
>>> print(M.table(printer, align='center'))
[ 1 , 2]
[-33, 4]
>>> print(M.table(printer, rowstart='{', rowend='}'))
{ 1, 2}
{-33, 4}
"""
# Handle zero dimensions:
if self.rows == 0 or self.cols == 0:
return '[]'
# Build table of string representations of the elements
res = []
# Track per-column max lengths for pretty alignment
maxlen = [0] * self.cols
for i in range(self.rows):
res.append([])
for j in range(self.cols):
s = printer._print(self[i, j])
res[-1].append(s)
maxlen[j] = max(len(s), maxlen[j])
# Patch strings together
align = {
'left': 'ljust',
'right': 'rjust',
'center': 'center',
'<': 'ljust',
'>': 'rjust',
'^': 'center',
}[align]
for i, row in enumerate(res):
for j, elem in enumerate(row):
row[j] = getattr(elem, align)(maxlen[j])
res[i] = rowstart + colsep.join(row) + rowend
return rowsep.join(res)
def rank_decomposition(self, iszerofunc=_iszero, simplify=False):
return _rank_decomposition(self, iszerofunc=iszerofunc,
simplify=simplify)
def cholesky(self, hermitian=True):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def LDLdecomposition(self, hermitian=True):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None,
rankcheck=False):
return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc,
rankcheck=rankcheck)
def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None,
rankcheck=False):
return _LUdecomposition_Simple(self, iszerofunc=iszerofunc,
simpfunc=simpfunc, rankcheck=rankcheck)
def LUdecompositionFF(self):
return _LUdecompositionFF(self)
def singular_value_decomposition(self):
return _singular_value_decomposition(self)
def QRdecomposition(self):
return _QRdecomposition(self)
def upper_hessenberg_decomposition(self):
return _upper_hessenberg_decomposition(self)
def diagonal_solve(self, rhs):
return _diagonal_solve(self, rhs)
def lower_triangular_solve(self, rhs):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def upper_triangular_solve(self, rhs):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def cholesky_solve(self, rhs):
return _cholesky_solve(self, rhs)
def LDLsolve(self, rhs):
return _LDLsolve(self, rhs)
def LUsolve(self, rhs, iszerofunc=_iszero):
return _LUsolve(self, rhs, iszerofunc=iszerofunc)
def QRsolve(self, b):
return _QRsolve(self, b)
def gauss_jordan_solve(self, B, freevar=False):
return _gauss_jordan_solve(self, B, freevar=freevar)
def pinv_solve(self, B, arbitrary_matrix=None):
return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix)
def solve(self, rhs, method='GJ'):
return _solve(self, rhs, method=method)
def solve_least_squares(self, rhs, method='CH'):
return _solve_least_squares(self, rhs, method=method)
def pinv(self, method='RD'):
return _pinv(self, method=method)
def inv_mod(self, m):
return _inv_mod(self, m)
def inverse_ADJ(self, iszerofunc=_iszero):
return _inv_ADJ(self, iszerofunc=iszerofunc)
def inverse_BLOCK(self, iszerofunc=_iszero):
return _inv_block(self, iszerofunc=iszerofunc)
def inverse_GE(self, iszerofunc=_iszero):
return _inv_GE(self, iszerofunc=iszerofunc)
def inverse_LU(self, iszerofunc=_iszero):
return _inv_LU(self, iszerofunc=iszerofunc)
def inverse_CH(self, iszerofunc=_iszero):
return _inv_CH(self, iszerofunc=iszerofunc)
def inverse_LDL(self, iszerofunc=_iszero):
return _inv_LDL(self, iszerofunc=iszerofunc)
def inverse_QR(self, iszerofunc=_iszero):
return _inv_QR(self, iszerofunc=iszerofunc)
def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False):
return _inv(self, method=method, iszerofunc=iszerofunc,
try_block_diag=try_block_diag)
def connected_components(self):
return _connected_components(self)
def connected_components_decomposition(self):
return _connected_components_decomposition(self)
rank_decomposition.__doc__ = _rank_decomposition.__doc__
cholesky.__doc__ = _cholesky.__doc__
LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
LUdecomposition.__doc__ = _LUdecomposition.__doc__
LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__
LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__
singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__
QRdecomposition.__doc__ = _QRdecomposition.__doc__
upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__
diagonal_solve.__doc__ = _diagonal_solve.__doc__
lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
cholesky_solve.__doc__ = _cholesky_solve.__doc__
LDLsolve.__doc__ = _LDLsolve.__doc__
LUsolve.__doc__ = _LUsolve.__doc__
QRsolve.__doc__ = _QRsolve.__doc__
gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__
pinv_solve.__doc__ = _pinv_solve.__doc__
solve.__doc__ = _solve.__doc__
solve_least_squares.__doc__ = _solve_least_squares.__doc__
pinv.__doc__ = _pinv.__doc__
inv_mod.__doc__ = _inv_mod.__doc__
inverse_ADJ.__doc__ = _inv_ADJ.__doc__
inverse_GE.__doc__ = _inv_GE.__doc__
inverse_LU.__doc__ = _inv_LU.__doc__
inverse_CH.__doc__ = _inv_CH.__doc__
inverse_LDL.__doc__ = _inv_LDL.__doc__
inverse_QR.__doc__ = _inv_QR.__doc__
inverse_BLOCK.__doc__ = _inv_block.__doc__
inv.__doc__ = _inv.__doc__
connected_components.__doc__ = _connected_components.__doc__
connected_components_decomposition.__doc__ = \
_connected_components_decomposition.__doc__
@deprecated(
issue=15109,
useinstead="from sympy.matrices.common import classof",
deprecated_since_version="1.3")
def classof(A, B):
from sympy.matrices.common import classof as classof_
return classof_(A, B)
@deprecated(
issue=15109,
deprecated_since_version="1.3",
useinstead="from sympy.matrices.common import a2idx")
def a2idx(j, n=None):
from sympy.matrices.common import a2idx as a2idx_
return a2idx_(j, n)
|
e7567a85282a912dedd8e3d6e3027cbb6d5c7e0759fcffc34234ccf591144aab | 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, EvalfMixin):
"""
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)
def _eval_evalf(self, prec):
return self.func(*[arg.evalf(n=prec_to_dps(prec)) for arg in self.args])
@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):
"""
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):
"""
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 __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):
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):
"""
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])
def _eval_simplify(self, **kwargs):
from sympy.simplify import simplify
return FiniteSet(*[simplify(elem, **kwargs) 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)
|
2038db17f02f34b14c74fd41066527ae77508c84e2a6cf2d8c5e574e432319d7 | from sympy import S
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.function import Lambda
from sympy.core.logic import fuzzy_bool
from sympy.core.relational import Eq
from sympy.core.symbol import Dummy
from sympy.core.sympify import _sympify
from sympy.logic.boolalg import And, as_Boolean
from sympy.utilities.iterables import sift
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .contains import Contains
from .sets import Set, EmptySet, Union, FiniteSet
adummy = Dummy('conditionset')
class ConditionSet(Set):
"""
Set of elements which satisfies a given condition.
{x | condition(x) is True for x in S}
Examples
========
>>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval
>>> from sympy.abc import x, y, z
>>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi))
>>> 2*pi in sin_sols
True
>>> pi/2 in sin_sols
False
>>> 3*pi in sin_sols
False
>>> 5 in ConditionSet(x, x**2 > 4, S.Reals)
True
If the value is not in the base set, the result is false:
>>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4))
False
Notes
=====
Symbols with assumptions should be avoided or else the
condition may evaluate without consideration of the set:
>>> n = Symbol('n', negative=True)
>>> cond = (n > 0); cond
False
>>> ConditionSet(n, cond, S.Integers)
EmptySet
Only free symbols can be changed by using `subs`:
>>> c = ConditionSet(x, x < 1, {x, z})
>>> c.subs(x, y)
ConditionSet(x, x < 1, FiniteSet(y, z))
To check if ``pi`` is in ``c`` use:
>>> pi in c
False
If no base set is specified, the universal set is implied:
>>> ConditionSet(x, x < 1).base_set
UniversalSet
Only symbols or symbol-like expressions can be used:
>>> ConditionSet(x + 1, x + 1 < 1, S.Integers)
Traceback (most recent call last):
...
ValueError: non-symbol dummy not recognized in condition
When the base set is a ConditionSet, the symbols will be
unified if possible with preference for the outermost symbols:
>>> ConditionSet(x, x < y, ConditionSet(z, z + y < 2, S.Integers))
ConditionSet(x, (x < y) & (x + y < 2), Integers)
"""
def __new__(cls, sym, condition, base_set=S.UniversalSet):
from sympy.core.function import BadSignatureError
from sympy.utilities.iterables import flatten, has_dups
sym = _sympify(sym)
flat = flatten([sym])
if has_dups(flat):
raise BadSignatureError("Duplicate symbols detected")
base_set = _sympify(base_set)
if not isinstance(base_set, Set):
raise TypeError(
'base set should be a Set object, not %s' % base_set)
condition = _sympify(condition)
if isinstance(condition, FiniteSet):
condition_orig = condition
temp = (Eq(lhs, 0) for lhs in condition)
condition = And(*temp)
SymPyDeprecationWarning(
feature="Using {} for condition".format(condition_orig),
issue=17651,
deprecated_since_version='1.5',
useinstead="{} for condition".format(condition)
).warn()
condition = as_Boolean(condition)
if condition is S.true:
return base_set
if condition is S.false:
return S.EmptySet
if isinstance(base_set, EmptySet):
return base_set
# no simple answers, so now check syms
for i in flat:
if not getattr(i, '_diff_wrt', False):
raise ValueError('`%s` is not symbol-like' % i)
if base_set.contains(sym) is S.false:
raise TypeError('sym `%s` is not in base_set `%s`' % (sym, base_set))
know = None
if isinstance(base_set, FiniteSet):
sifted = sift(
base_set, lambda _: fuzzy_bool(condition.subs(sym, _)))
if sifted[None]:
know = FiniteSet(*sifted[True])
base_set = FiniteSet(*sifted[None])
else:
return FiniteSet(*sifted[True])
if isinstance(base_set, cls):
s, c, b = base_set.args
def sig(s):
return cls(s, Eq(adummy, 0)).as_dummy().sym
sa, sb = map(sig, (sym, s))
if sa != sb:
raise BadSignatureError('sym does not match sym of base set')
reps = dict(zip(flatten([sym]), flatten([s])))
if s == sym:
condition = And(condition, c)
base_set = b
elif not c.free_symbols & sym.free_symbols:
reps = {v: k for k, v in reps.items()}
condition = And(condition, c.xreplace(reps))
base_set = b
elif not condition.free_symbols & s.free_symbols:
sym = sym.xreplace(reps)
condition = And(condition.xreplace(reps), c)
base_set = b
# flatten ConditionSet(Contains(ConditionSet())) expressions
if isinstance(condition, Contains) and (sym == condition.args[0]):
if isinstance(condition.args[1], Set):
return condition.args[1].intersect(base_set)
rv = Basic.__new__(cls, sym, condition, base_set)
return rv if know is None else Union(know, rv)
sym = property(lambda self: self.args[0])
condition = property(lambda self: self.args[1])
base_set = property(lambda self: self.args[2])
@property
def free_symbols(self):
cond_syms = self.condition.free_symbols - self.sym.free_symbols
return cond_syms | self.base_set.free_symbols
@property
def bound_symbols(self):
from sympy.utilities.iterables import flatten
return flatten([self.sym])
def _contains(self, other):
def ok_sig(a, b):
tuples = [isinstance(i, Tuple) for i in (a, b)]
c = tuples.count(True)
if c == 1:
return False
if c == 0:
return True
return len(a) == len(b) and all(
ok_sig(i, j) for i, j in zip(a, b))
if not ok_sig(self.sym, other):
return S.false
# try doing base_cond first and return
# False immediately if it is False
base_cond = Contains(other, self.base_set)
if base_cond is S.false:
return S.false
# Substitute other into condition. This could raise e.g. for
# ConditionSet(x, 1/x >= 0, Reals).contains(0)
lamda = Lambda((self.sym,), self.condition)
try:
lambda_cond = lamda(other)
except TypeError:
return Contains(other, self, evaluate=False)
else:
return And(base_cond, lambda_cond)
def as_relational(self, other):
f = Lambda(self.sym, self.condition)
if isinstance(self.sym, Tuple):
f = f(*other)
else:
f = f(other)
return And(f, self.base_set.contains(other))
def _eval_subs(self, old, new):
sym, cond, base = self.args
dsym = sym.subs(old, adummy)
insym = dsym.has(adummy)
# prioritize changing a symbol in the base
newbase = base.subs(old, new)
if newbase != base:
if not insym:
cond = cond.subs(old, new)
return self.func(sym, cond, newbase)
if insym:
pass # no change of bound symbols via subs
elif getattr(new, '_diff_wrt', False):
cond = cond.subs(old, new)
else:
pass # let error about the symbol raise from __new__
return self.func(sym, cond, base)
|
d323f9f1fccca04cf50ec1f7d5b10a664ee45fe0ede1f94b64d8c23af1d9a60a | 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.matrices import Matrix
from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial, BetaBinomial,
Hypergeometric, Rademacher, IdealSoliton, RobustSoliton, P, E, variance,
covariance, skewness, 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
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)
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))
|
84e33f522c75126c1fdf92bf02b37042b385a3433a097cced249ee4919127da5 | 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,
FlorySchulz, Poisson, Geometric, Hermite, Logarithmic,
NegativeBinomial, Skellam, YuleSimon, Zeta,
DiscreteRV)
from sympy.testing.pytest import slow, nocache_fail, raises, ignore_warnings
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
def test_FlorySchulz():
a = Symbol("a")
z = Symbol("z")
x = FlorySchulz('x' , a)
assert E(x) == (2 - a)/a
assert (variance(x) - 2*(1 - a)/a**2).simplify() == S(0)
assert density(x)(z) == a**2*z*(1 - a)**(z - 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
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)
|
b060be72e7c06a824292e12e72878f4ed4c2048626f110c55596a640707fc52a | 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, atan, 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.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, 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, LogCauchy,
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, 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_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_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_logcauchy():
mu = Symbol("mu" , positive=True)
sigma = Symbol("sigma" , positive=True)
X = LogCauchy("x", mu, sigma)
assert density(X)(x) == sigma/(x*pi*(sigma**2 + (-mu + log(x))**2))
assert cdf(X)(x) == atan((log(x) - mu)/sigma)/pi + S.Half
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)
# 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_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_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_issue_20756():
X = Uniform('X', -1, +1)
Y = Uniform('Y', -1, +1)
assert E(X * Y) == S.Zero
assert E(X * ((Y + 1) - 1)) == S.Zero
assert E(Y * (X*(X + 1) - X*X)) == S.Zero
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_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}))
|
59ca10e990470bbfc29cade8838bda602b99b5bcb3f4b2814536f2bf2ad4c2f1 | from functools import singledispatch
from sympy.external import import_module
from sympy.stats.crv_types import BetaDistribution, ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution
from sympy.stats.drv_types import GeometricDistribution, PoissonDistribution, ZetaDistribution
from sympy.stats.frv_types import BinomialDistribution
numpy = import_module('numpy')
@singledispatch
def do_sample_numpy(dist, size, rand_state):
return None
# CRV:
@do_sample_numpy.register(BetaDistribution)
def _(dist: BetaDistribution, size, rand_state):
return rand_state.beta(a=float(dist.alpha), b=float(dist.beta), size=size)
@do_sample_numpy.register(ChiSquaredDistribution)
def _(dist: ChiSquaredDistribution, size, rand_state):
return rand_state.chisquare(df=float(dist.k), size=size)
@do_sample_numpy.register(ExponentialDistribution)
def _(dist: ExponentialDistribution, size, rand_state):
return rand_state.exponential(1 / float(dist.rate), size=size)
@do_sample_numpy.register(GammaDistribution)
def _(dist: GammaDistribution, size, rand_state):
return rand_state.gamma(float(dist.k), float(dist.theta), size=size)
@do_sample_numpy.register(LogNormalDistribution)
def _(dist: LogNormalDistribution, size, rand_state):
return rand_state.lognormal(float(dist.mean), float(dist.std), size=size)
@do_sample_numpy.register(NormalDistribution)
def _(dist: NormalDistribution, size, rand_state):
return rand_state.normal(float(dist.mean), float(dist.std), size=size)
@do_sample_numpy.register(ParetoDistribution)
def _(dist: ParetoDistribution, size, rand_state):
return (numpy.random.pareto(a=float(dist.alpha), size=size) + 1) * float(dist.xm)
@do_sample_numpy.register(UniformDistribution)
def _(dist: UniformDistribution, size, rand_state):
return rand_state.uniform(low=float(dist.left), high=float(dist.right), size=size)
# DRV:
@do_sample_numpy.register(GeometricDistribution)
def _(dist: GeometricDistribution, size, rand_state):
return rand_state.geometric(p=float(dist.p), size=size)
@do_sample_numpy.register(PoissonDistribution)
def _(dist: PoissonDistribution, size, rand_state):
return rand_state.poisson(lam=float(dist.lamda), size=size)
@do_sample_numpy.register(ZetaDistribution)
def _(dist: ZetaDistribution, size, rand_state):
return rand_state.zipf(a=float(dist.s), size=size)
# FRV:
@do_sample_numpy.register(BinomialDistribution)
def _(dist: BinomialDistribution, size, rand_state):
return rand_state.binomial(n=int(dist.n), p=float(dist.p), size=size)
|
ef5a516bc14bed04a3698c5d530901d9339c877d7897c39f6e2426f8b872b23d | from functools import singledispatch
from sympy import Dummy, lambdify, exp
from sympy.external import import_module
from sympy.stats import DiscreteDistributionHandmade
from sympy.stats.crv import SingleContinuousDistribution
from sympy.stats.crv_types import ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, BetaDistribution, \
StudentTDistribution, CauchyDistribution
from sympy.stats.drv_types import GeometricDistribution, LogarithmicDistribution, NegativeBinomialDistribution, \
PoissonDistribution, SkellamDistribution, YuleSimonDistribution, ZetaDistribution
from sympy.stats.frv import SingleFiniteDistribution
scipy = import_module("scipy")
if scipy is not None:
import scipy.stats
@singledispatch
def do_sample_scipy(dist, size, seed):
return None
# CRV
@do_sample_scipy.register(SingleContinuousDistribution)
def _(dist: SingleContinuousDistribution, size, seed):
# if we don't need to make a handmade pdf, we won't
import scipy.stats
z = Dummy('z')
handmade_pdf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
class scipy_pdf(scipy.stats.rv_continuous):
def _pdf(dist, x):
return handmade_pdf(x)
scipy_rv = scipy_pdf(a=float(dist.set._inf),
b=float(dist.set._sup), name='scipy_pdf')
return scipy_rv.rvs(size=size, random_state=seed)
@do_sample_scipy.register(ChiSquaredDistribution)
def _(dist: ChiSquaredDistribution, size, seed):
# same parametrisation
return scipy.stats.chi2.rvs(df=float(dist.k), size=size, random_state=seed)
@do_sample_scipy.register(ExponentialDistribution)
def _(dist: ExponentialDistribution, size, seed):
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html#scipy.stats.expon
return scipy.stats.expon.rvs(scale=1 / float(dist.rate), size=size, random_state=seed)
@do_sample_scipy.register(GammaDistribution)
def _(dist: GammaDistribution, size, seed):
# https://stackoverflow.com/questions/42150965/how-to-plot-gamma-distribution-with-alpha-and-beta-parameters-in-python
return scipy.stats.gamma.rvs(a=float(dist.k), scale=float(dist.theta), size=size, random_state=seed)
@do_sample_scipy.register(LogNormalDistribution)
def _(dist: LogNormalDistribution, size, seed):
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html
return scipy.stats.lognorm.rvs(scale=float(exp(dist.mean)), s=float(dist.std), size=size, random_state=seed)
@do_sample_scipy.register(NormalDistribution)
def _(dist: NormalDistribution, size, seed):
return scipy.stats.norm.rvs(loc=float(dist.mean), scale=float(dist.std), size=size, random_state=seed)
@do_sample_scipy.register(ParetoDistribution)
def _(dist: ParetoDistribution, size, seed):
# https://stackoverflow.com/questions/42260519/defining-pareto-distribution-in-python-scipy
return scipy.stats.pareto.rvs(b=float(dist.alpha), scale=float(dist.xm), size=size, random_state=seed)
@do_sample_scipy.register(StudentTDistribution)
def _(dist: StudentTDistribution, size, seed):
return scipy.stats.t.rvs(df=float(dist.nu), size=size, random_state=seed)
@do_sample_scipy.register(UniformDistribution)
def _(dist: UniformDistribution, size, seed):
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html
return scipy.stats.uniform.rvs(loc=float(dist.left), scale=float(dist.right - dist.left), size=size, random_state=seed)
@do_sample_scipy.register(BetaDistribution)
def _(dist: BetaDistribution, size, seed):
# same parametrisation
return scipy.stats.beta.rvs(a=float(dist.alpha), b=float(dist.beta), size=size, random_state=seed)
@do_sample_scipy.register(CauchyDistribution)
def _(dist: CauchyDistribution, size, seed):
return scipy.stats.cauchy.rvs(loc=float(dist.x0), scale=float(dist.gamma), size=size, random_state=seed)
# DRV:
@do_sample_scipy.register(DiscreteDistributionHandmade)
def _(dist: DiscreteDistributionHandmade, size, seed):
from scipy.stats import rv_discrete
from sympy import lambdify
z = Dummy('z')
handmade_pmf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
class scipy_pmf(rv_discrete):
def _pmf(dist, x):
return handmade_pmf(x)
scipy_rv = scipy_pmf(a=float(dist.set._inf), b=float(dist.set._sup),
name='scipy_pmf')
return scipy_rv.rvs(size=size, random_state=seed)
@do_sample_scipy.register(GeometricDistribution)
def _(dist: GeometricDistribution, size, seed):
return scipy.stats.geom.rvs(p=float(dist.p), size=size, random_state=seed)
@do_sample_scipy.register(LogarithmicDistribution)
def _(dist: LogarithmicDistribution, size, seed):
return scipy.stats.logser.rvs(p=float(dist.p), size=size, random_state=seed)
@do_sample_scipy.register(NegativeBinomialDistribution)
def _(dist: NegativeBinomialDistribution, size, seed):
return scipy.stats.nbinom.rvs(n=float(dist.r), p=float(dist.p), size=size, random_state=seed)
@do_sample_scipy.register(PoissonDistribution)
def _(dist: PoissonDistribution, size, seed):
return scipy.stats.poisson.rvs(mu=float(dist.lamda), size=size, random_state=seed)
@do_sample_scipy.register(SkellamDistribution)
def _(dist: SkellamDistribution, size, seed):
return scipy.stats.skellam.rvs(mu1=float(dist.mu1), mu2=float(dist.mu2), size=size, random_state=seed)
@do_sample_scipy.register(YuleSimonDistribution)
def _(dist: YuleSimonDistribution, size, seed):
return scipy.stats.yulesimon.rvs(alpha=float(dist.rho), size=size, random_state=seed)
@do_sample_scipy.register(ZetaDistribution)
def _(dist: ZetaDistribution, size, seed):
return scipy.stats.zipf.rvs(a=float(dist.s), size=size, random_state=seed)
# FRV:
@do_sample_scipy.register(SingleFiniteDistribution)
def _(dist: SingleFiniteDistribution, size, seed):
# scipy can handle with custom distributions
from scipy.stats import rv_discrete
density_ = dist.dict
x, y = [], []
for k, v in density_.items():
x.append(int(k))
y.append(float(v))
scipy_rv = rv_discrete(name='scipy_rv', values=(x, y))
return scipy_rv.rvs(size=size, random_state=seed)
|
149df35a1944c39ae5ff168948f89214ad958bf47db9810a6fc5bc43acc26bca | from functools import singledispatch
from sympy.external import import_module
from sympy.stats.crv_types import BetaDistribution, CauchyDistribution, ChiSquaredDistribution, ExponentialDistribution, \
GammaDistribution, LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, \
GaussianInverseDistribution
from sympy.stats.drv_types import PoissonDistribution, GeometricDistribution, NegativeBinomialDistribution
from sympy.stats.frv_types import BinomialDistribution, BernoulliDistribution
pymc3 = import_module('pymc3')
@singledispatch
def do_sample_pymc3(dist):
return None
# CRV:
@do_sample_pymc3.register(BetaDistribution)
def _(dist: BetaDistribution):
return pymc3.Beta('X', alpha=float(dist.alpha), beta=float(dist.beta))
@do_sample_pymc3.register(CauchyDistribution)
def _(dist: CauchyDistribution):
return pymc3.Cauchy('X', alpha=float(dist.x0), beta=float(dist.gamma))
@do_sample_pymc3.register(ChiSquaredDistribution)
def _(dist: ChiSquaredDistribution):
return pymc3.ChiSquared('X', nu=float(dist.k))
@do_sample_pymc3.register(ExponentialDistribution)
def _(dist: ExponentialDistribution):
return pymc3.Exponential('X', lam=float(dist.rate))
@do_sample_pymc3.register(GammaDistribution)
def _(dist: GammaDistribution):
return pymc3.Gamma('X', alpha=float(dist.k), beta=1 / float(dist.theta))
@do_sample_pymc3.register(LogNormalDistribution)
def _(dist: LogNormalDistribution):
return pymc3.Lognormal('X', mu=float(dist.mean), sigma=float(dist.std))
@do_sample_pymc3.register(NormalDistribution)
def _(dist: NormalDistribution):
return pymc3.Normal('X', float(dist.mean), float(dist.std))
@do_sample_pymc3.register(GaussianInverseDistribution)
def _(dist: GaussianInverseDistribution):
return pymc3.Wald('X', mu=float(dist.mean), lam=float(dist.shape))
@do_sample_pymc3.register(ParetoDistribution)
def _(dist: ParetoDistribution):
return pymc3.Pareto('X', alpha=float(dist.alpha), m=float(dist.xm))
@do_sample_pymc3.register(UniformDistribution)
def _(dist: UniformDistribution):
return pymc3.Uniform('X', lower=float(dist.left), upper=float(dist.right))
# DRV:
@do_sample_pymc3.register(GeometricDistribution)
def _(dist: GeometricDistribution):
return pymc3.Geometric('X', p=float(dist.p))
@do_sample_pymc3.register(NegativeBinomialDistribution)
def _(dist: NegativeBinomialDistribution):
return pymc3.NegativeBinomial('X', mu=float((dist.p * dist.r) / (1 - dist.p)),
alpha=float(dist.r))
@do_sample_pymc3.register(PoissonDistribution)
def _(dist: PoissonDistribution):
return pymc3.Poisson('X', mu=float(dist.lamda))
# FRV:
@do_sample_pymc3.register(BernoulliDistribution)
def _(dist: BernoulliDistribution):
return pymc3.Bernoulli('X', p=float(dist.p))
@do_sample_pymc3.register(BinomialDistribution)
def _(dist: BinomialDistribution):
return pymc3.Binomial('X', n=int(dist.n), p=float(dist.p))
|
bb66e000713944dbb16a4ba33c3de4fd899bdf8dfd44fe318a0f9b52bda8acaf | from sympy import S, Rational
from sympy.external import import_module
from sympy.stats import Binomial, sample, Die, FiniteRV, DiscreteUniform, Bernoulli, BetaBinomial, Hypergeometric, \
Rademacher
from sympy.testing.pytest import skip, ignore_warnings, raises
def test_given_sample():
X = Die('X', 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_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')))
def test_sample_seed():
F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)})
libraries = ['scipy', 'numpy', 'pymc3']
for lib in libraries:
try:
imported_lib = import_module(lib)
if imported_lib:
s0 = list(sample(F, numsamples=10, library=lib, seed=0))
s1 = list(sample(F, numsamples=10, library=lib, seed=0))
s2 = list(sample(F, numsamples=10, library=lib, seed=1))
assert s0 == s1
assert s1 != s2
except NotImplementedError:
continue
|
29d19016f76f2f5e472a76085d327b40fb77f9bae078242388baca198d0d5766 | from sympy import exp, Interval, oo, Symbol
from sympy.external import import_module
from sympy.stats import Beta, Chi, Normal, Gamma, Exponential, LogNormal, Pareto, ChiSquared, Uniform, sample, \
BetaPrime, Cauchy, GammaInverse, GaussianInverse, StudentT, Weibull, density, ContinuousRV
from sympy.testing.pytest import skip, ignore_warnings, raises
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_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_lognormal_sampling():
# 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
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_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_sample_continuous():
z = Symbol('z')
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)
libraries = ['scipy', 'numpy', 'pymc3']
for lib in libraries:
try:
imported_lib = import_module(lib)
if imported_lib:
s0, s1, s2 = [], [], []
s0 = list(sample(Z, numsamples=10, library=lib, seed=0))
s1 = list(sample(Z, numsamples=10, library=lib, seed=0))
s2 = list(sample(Z, numsamples=10, library=lib, seed=1))
assert s0 == s1
assert s1 != s2
except NotImplementedError:
continue
|
a00c8c89ffd807ee543f78f5eb6c1ff119481b57c850beada17618ab1f23bdb8 | from sympy import S, Symbol
from sympy.external import import_module
from sympy.stats import Geometric, Poisson, Zeta, sample, Skellam, DiscreteRV, Logarithmic, NegativeBinomial, YuleSimon
from sympy.testing.pytest import skip, ignore_warnings, raises, slow
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')))
@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
libraries = ['scipy', 'numpy', 'pymc3']
for lib in libraries:
try:
imported_lib = import_module(lib)
if imported_lib:
s0, s1, s2 = [], [], []
s0 = list(sample(X, numsamples=10, library=lib, seed=0))
s1 = list(sample(X, numsamples=10, library=lib, seed=0))
s2 = list(sample(X, numsamples=10, library=lib, seed=1))
assert s0 == s1
assert s1 != s2
except NotImplementedError:
continue
|
904ae09ce84e62f0ccf9eae27c29bccbc904c2ce2077319967bcb0edae5df717 | from sympy import Sieve, sieve, Symbol, S, limit, I, zoo, nan, Rational
from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
from sympy.ntheory.generate import cycle_length
from sympy.ntheory.primetest import mr
from sympy.testing.pytest import raises
def test_prime():
assert prime(1) == 2
assert prime(2) == 3
assert prime(5) == 11
assert prime(11) == 31
assert prime(57) == 269
assert prime(296) == 1949
assert prime(559) == 4051
assert prime(3000) == 27449
assert prime(4096) == 38873
assert prime(9096) == 94321
assert prime(25023) == 287341
raises(ValueError, lambda: prime(0))
sieve.extend(3000)
assert prime(401) == 2749
def test_primepi():
assert primepi(-1) == 0
assert primepi(1) == 0
assert primepi(2) == 1
assert primepi(Rational(7, 2)) == 2
assert primepi(3.5) == 2
assert primepi(5) == 3
assert primepi(11) == 5
assert primepi(57) == 16
assert primepi(296) == 62
assert primepi(559) == 102
assert primepi(3000) == 430
assert primepi(4096) == 564
assert primepi(9096) == 1128
assert primepi(25023) == 2763
assert primepi(10**8) == 5761455
assert primepi(253425253) == 13856396
assert primepi(8769575643) == 401464322
sieve.extend(3000)
assert primepi(2000) == 303
n = Symbol('n')
assert primepi(n).subs(n, 2) == 1
r = Symbol('r', real=True)
assert primepi(r).subs(r, 2) == 1
assert primepi(S.Infinity) is S.Infinity
assert primepi(S.NegativeInfinity) == 0
assert limit(primepi(n), n, 100) == 25
raises(ValueError, lambda: primepi(I))
raises(ValueError, lambda: primepi(1 + I))
raises(ValueError, lambda: primepi(zoo))
raises(ValueError, lambda: primepi(nan))
def test_composite():
from sympy.ntheory.generate import sieve
sieve._reset()
assert composite(1) == 4
assert composite(2) == 6
assert composite(5) == 10
assert composite(11) == 20
assert composite(41) == 58
assert composite(57) == 80
assert composite(296) == 370
assert composite(559) == 684
assert composite(3000) == 3488
assert composite(4096) == 4736
assert composite(9096) == 10368
assert composite(25023) == 28088
sieve.extend(3000)
assert composite(1957) == 2300
assert composite(2568) == 2998
raises(ValueError, lambda: composite(0))
def test_compositepi():
assert compositepi(1) == 0
assert compositepi(2) == 0
assert compositepi(5) == 1
assert compositepi(11) == 5
assert compositepi(57) == 40
assert compositepi(296) == 233
assert compositepi(559) == 456
assert compositepi(3000) == 2569
assert compositepi(4096) == 3531
assert compositepi(9096) == 7967
assert compositepi(25023) == 22259
assert compositepi(10**8) == 94238544
assert compositepi(253425253) == 239568856
assert compositepi(8769575643) == 8368111320
sieve.extend(3000)
assert compositepi(2321) == 1976
def test_generate():
from sympy.ntheory.generate import sieve
sieve._reset()
assert nextprime(-4) == 2
assert nextprime(2) == 3
assert nextprime(5) == 7
assert nextprime(12) == 13
assert prevprime(3) == 2
assert prevprime(7) == 5
assert prevprime(13) == 11
assert prevprime(19) == 17
assert prevprime(20) == 19
sieve.extend_to_no(9)
assert sieve._list[-1] == 23
assert sieve._list[-1] < 31
assert 31 in sieve
assert nextprime(90) == 97
assert nextprime(10**40) == (10**40 + 121)
assert prevprime(97) == 89
assert prevprime(10**40) == (10**40 - 17)
assert list(sieve.primerange(10, 1)) == []
assert list(sieve.primerange(5, 9)) == [5, 7]
sieve._reset(prime=True)
assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
assert list(sieve.primerange(8)) == [2, 3, 5, 7]
assert list(sieve.primerange(-2)) == []
assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
sieve._reset(totient=True)
assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
assert list(sieve.totientrange(0, 1)) == []
assert list(sieve.totientrange(1, 2)) == [1]
assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
sieve._reset(mobius=True)
assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
assert list(sieve.mobiusrange(0, 1)) == []
assert list(sieve.mobiusrange(1, 2)) == [1]
assert list(primerange(10, 1)) == []
assert list(primerange(2, 7)) == [2, 3, 5]
assert list(primerange(2, 10)) == [2, 3, 5, 7]
assert list(primerange(1050, 1100)) == [1051, 1061,
1063, 1069, 1087, 1091, 1093, 1097]
s = Sieve()
for i in range(30, 2350, 376):
for j in range(2, 5096, 1139):
A = list(s.primerange(i, i + j))
B = list(primerange(i, i + j))
assert A == B
s = Sieve()
assert s[10] == 29
assert nextprime(2, 2) == 5
raises(ValueError, lambda: totient(0))
raises(ValueError, lambda: reduced_totient(0))
raises(ValueError, lambda: primorial(0))
assert mr(1, [2]) is False
func = lambda i: (i**2 + 1) % 51
assert next(cycle_length(func, 4)) == (6, 2)
assert list(cycle_length(func, 4, values=True)) == \
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
assert next(cycle_length(func, 4, nmax=5)) == (5, None)
assert list(cycle_length(func, 4, nmax=5, values=True)) == \
[17, 35, 2, 5, 26]
sieve.extend(3000)
assert nextprime(2968) == 2969
assert prevprime(2930) == 2927
raises(ValueError, lambda: prevprime(1))
def test_randprime():
assert randprime(10, 1) is None
assert randprime(2, 3) == 2
assert randprime(1, 3) == 2
assert randprime(3, 5) == 3
raises(ValueError, lambda: randprime(20, 22))
for a in [100, 300, 500, 250000]:
for b in [100, 300, 500, 250000]:
p = randprime(a, a + b)
assert a <= p < (a + b) and isprime(p)
def test_primorial():
assert primorial(1) == 2
assert primorial(1, nth=0) == 1
assert primorial(2) == 6
assert primorial(2, nth=0) == 2
assert primorial(4, nth=0) == 6
def test_search():
assert 2 in sieve
assert 2.1 not in sieve
assert 1 not in sieve
assert 2**1000 not in sieve
raises(ValueError, lambda: sieve.search(1))
def test_sieve_slice():
assert sieve[5] == 11
assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
assert list(sieve[1:5]) == [2, 3, 5, 7]
raises(IndexError, lambda: sieve[:5])
raises(IndexError, lambda: sieve[0])
raises(IndexError, lambda: sieve[0:5])
def test_sieve_iter():
values = []
for value in sieve:
if value > 7:
break
values.append(value)
assert values == list(sieve[1:5])
def test_sieve_repr():
assert "sieve" in repr(sieve)
assert "prime" in repr(sieve)
|
a07fe2f7e5b3c1a3188b021c13d5099a79faf541b160ec64b56ff0cbeea35274 | from sympy import log, exp, cos, Symbol, Pow, sin, MatrixSymbol, sinc
from sympy.assumptions import assuming, Q
from sympy.printing import ccode
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.cfunctions import log2, exp2, expm1, log1p
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
from sympy.codegen.rewriting import (
optimize, cosm1_opt, log2_opt, exp2_opt, expm1_opt, log1p_opt, optims_c99,
create_expand_pow_optimization, matinv_opt, logaddexp_opt, logaddexp2_opt,
optims_numpy, sinc_opts
)
from sympy.testing.pytest import XFAIL
def test_log2_opt():
x = Symbol('x')
expr1 = 7*log(3*x + 5)/(log(2))
opt1 = optimize(expr1, [log2_opt])
assert opt1 == 7*log2(3*x + 5)
assert opt1.rewrite(log) == expr1
expr2 = 3*log(5*x + 7)/(13*log(2))
opt2 = optimize(expr2, [log2_opt])
assert opt2 == 3*log2(5*x + 7)/13
assert opt2.rewrite(log) == expr2
expr3 = log(x)/log(2)
opt3 = optimize(expr3, [log2_opt])
assert opt3 == log2(x)
assert opt3.rewrite(log) == expr3
expr4 = log(x)/log(2) + log(x+1)
opt4 = optimize(expr4, [log2_opt])
assert opt4 == log2(x) + log(2)*log2(x+1)
assert opt4.rewrite(log) == expr4
expr5 = log(17)
opt5 = optimize(expr5, [log2_opt])
assert opt5 == expr5
expr6 = log(x + 3)/log(2)
opt6 = optimize(expr6, [log2_opt])
assert str(opt6) == 'log2(x + 3)'
assert opt6.rewrite(log) == expr6
def test_exp2_opt():
x = Symbol('x')
expr1 = 1 + 2**x
opt1 = optimize(expr1, [exp2_opt])
assert opt1 == 1 + exp2(x)
assert opt1.rewrite(Pow) == expr1
expr2 = 1 + 3**x
assert expr2 == optimize(expr2, [exp2_opt])
def test_expm1_opt():
x = Symbol('x')
expr1 = exp(x) - 1
opt1 = optimize(expr1, [expm1_opt])
assert expm1(x) - opt1 == 0
assert opt1.rewrite(exp) == expr1
expr2 = 3*exp(x) - 3
opt2 = optimize(expr2, [expm1_opt])
assert 3*expm1(x) == opt2
assert opt2.rewrite(exp) == expr2
expr3 = 3*exp(x) - 5
assert expr3 == optimize(expr3, [expm1_opt])
expr4 = 3*exp(x) + log(x) - 3
opt4 = optimize(expr4, [expm1_opt])
assert 3*expm1(x) + log(x) == opt4
assert opt4.rewrite(exp) == expr4
expr5 = 3*exp(2*x) - 3
opt5 = optimize(expr5, [expm1_opt])
assert 3*expm1(2*x) == opt5
assert opt5.rewrite(exp) == expr5
@XFAIL # ideally this test should pass: need to improve `expm1_opt`
def test_expm1_two_exp_terms():
x, y = map(Symbol, 'x y'.split())
expr1 = exp(x) + exp(y) - 2
opt1 = optimize(expr1, [expm1_opt])
assert opt1 == expm1(x) + expm1(y)
def test_cosm1_opt():
x = Symbol('x')
expr1 = cos(x) - 1
opt1 = optimize(expr1, [cosm1_opt])
assert cosm1(x) - opt1 == 0
assert opt1.rewrite(cos) == expr1
expr2 = 3*cos(x) - 3
opt2 = optimize(expr2, [cosm1_opt])
assert 3*cosm1(x) == opt2
assert opt2.rewrite(cos) == expr2
expr3 = 3*cos(x) - 5
assert expr3 == optimize(expr3, [cosm1_opt])
expr4 = 3*cos(x) + log(x) - 3
opt4 = optimize(expr4, [cosm1_opt])
assert 3*cosm1(x) + log(x) == opt4
assert opt4.rewrite(cos) == expr4
expr5 = 3*cos(2*x) - 3
opt5 = optimize(expr5, [cosm1_opt])
assert 3*cosm1(2*x) == opt5
assert opt5.rewrite(cos) == expr5
@XFAIL # ideally this test should pass: need to improve `cosm1_opt`
def test_cosm1_two_cos_terms():
x, y = map(Symbol, 'x y'.split())
expr1 = cos(x) + cos(y) - 2
opt1 = optimize(expr1, [cosm1_opt])
assert opt1 == cosm1(x) + cosm1(y)
@XFAIL # ideally this test should pass: need to add a new combined expm1_cosm1_opt?
def test_expm1_cosm1_mixed():
x = Symbol('x')
expr1 = exp(x) + cos(x) - 2
opt1 = optimize(expr1, [expm1_opt, cosm1_opt]) # need a combined opt pass?
assert opt1 == cosm1(x) + expm1(x)
def test_log1p_opt():
x = Symbol('x')
expr1 = log(x + 1)
opt1 = optimize(expr1, [log1p_opt])
assert log1p(x) - opt1 == 0
assert opt1.rewrite(log) == expr1
expr2 = log(3*x + 3)
opt2 = optimize(expr2, [log1p_opt])
assert log1p(x) + log(3) == opt2
assert (opt2.rewrite(log) - expr2).simplify() == 0
expr3 = log(2*x + 1)
opt3 = optimize(expr3, [log1p_opt])
assert log1p(2*x) - opt3 == 0
assert opt3.rewrite(log) == expr3
expr4 = log(x+3)
opt4 = optimize(expr4, [log1p_opt])
assert str(opt4) == 'log(x + 3)'
def test_optims_c99():
x = Symbol('x')
expr1 = 2**x + log(x)/log(2) + log(x + 1) + exp(x) - 1
opt1 = optimize(expr1, optims_c99).simplify()
assert opt1 == exp2(x) + log2(x) + log1p(x) + expm1(x)
assert opt1.rewrite(exp).rewrite(log).rewrite(Pow) == expr1
expr2 = log(x)/log(2) + log(x + 1)
opt2 = optimize(expr2, optims_c99)
assert opt2 == log2(x) + log1p(x)
assert opt2.rewrite(log) == expr2
expr3 = log(x)/log(2) + log(17*x + 17)
opt3 = optimize(expr3, optims_c99)
delta3 = opt3 - (log2(x) + log(17) + log1p(x))
assert delta3 == 0
assert (opt3.rewrite(log) - expr3).simplify() == 0
expr4 = 2**x + 3*log(5*x + 7)/(13*log(2)) + 11*exp(x) - 11 + log(17*x + 17)
opt4 = optimize(expr4, optims_c99).simplify()
delta4 = opt4 - (exp2(x) + 3*log2(5*x + 7)/13 + 11*expm1(x) + log(17) + log1p(x))
assert delta4 == 0
assert (opt4.rewrite(exp).rewrite(log).rewrite(Pow) - expr4).simplify() == 0
expr5 = 3*exp(2*x) - 3
opt5 = optimize(expr5, optims_c99)
delta5 = opt5 - 3*expm1(2*x)
assert delta5 == 0
assert opt5.rewrite(exp) == expr5
expr6 = exp(2*x) - 3
opt6 = optimize(expr6, optims_c99)
delta6 = opt6 - (exp(2*x) - 3)
assert delta6 == 0
expr7 = log(3*x + 3)
opt7 = optimize(expr7, optims_c99)
delta7 = opt7 - (log(3) + log1p(x))
assert delta7 == 0
assert (opt7.rewrite(log) - expr7).simplify() == 0
expr8 = log(2*x + 3)
opt8 = optimize(expr8, optims_c99)
assert opt8 == expr8
def test_create_expand_pow_optimization():
cc = lambda x: ccode(
optimize(x, [create_expand_pow_optimization(4)]))
x = Symbol('x')
assert cc(x**4) == 'x*x*x*x'
assert cc(x**4 + x**2) == 'x*x + x*x*x*x'
assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x'
assert cc(sin(x)**4) == 'pow(sin(x), 4)'
# gh issue 15335
assert cc(x**(-4)) == '1.0/(x*x*x*x)'
assert cc(x**(-5)) == 'pow(x, -5)'
assert cc(-x**4) == '-x*x*x*x'
assert cc(x**4 - x**2) == '-x*x + x*x*x*x'
i = Symbol('i', integer=True)
assert cc(x**i - x**2) == 'pow(x, i) - x*x'
# gh issue 20753
cc2 = lambda x: ccode(optimize(x, [create_expand_pow_optimization(
4, base_req=lambda b: b.is_Function)]))
assert cc2(x**3 + sin(x)**3) == "pow(x, 3) + sin(x)*sin(x)*sin(x)"
def test_matsolve():
n = Symbol('n', integer=True)
A = MatrixSymbol('A', n, n)
x = MatrixSymbol('x', n, 1)
with assuming(Q.fullrank(A)):
assert optimize(A**(-1) * x, [matinv_opt]) == MatrixSolve(A, x)
assert optimize(A**(-1) * x + x, [matinv_opt]) == MatrixSolve(A, x) + x
def test_logaddexp_opt():
x, y = map(Symbol, 'x y'.split())
expr1 = log(exp(x) + exp(y))
opt1 = optimize(expr1, [logaddexp_opt])
assert logaddexp(x, y) - opt1 == 0
assert logaddexp(y, x) - opt1 == 0
assert opt1.rewrite(log) == expr1
def test_logaddexp2_opt():
x, y = map(Symbol, 'x y'.split())
expr1 = log(2**x + 2**y)/log(2)
opt1 = optimize(expr1, [logaddexp2_opt])
assert logaddexp2(x, y) - opt1 == 0
assert logaddexp2(y, x) - opt1 == 0
assert opt1.rewrite(log) == expr1
def test_sinc_opts():
def check(d):
for k, v in d.items():
assert optimize(k, sinc_opts) == v
x = Symbol('x')
check({
sin(x)/x : sinc(x),
sin(2*x)/(2*x) : sinc(2*x),
sin(3*x)/x : 3*sinc(3*x),
x*sin(x) : x*sin(x)
})
y = Symbol('y')
check({
sin(x*y)/(x*y) : sinc(x*y),
y*sin(x/y)/x : sinc(x/y),
sin(sin(x))/sin(x) : sinc(sin(x)),
sin(3*sin(x))/sin(x) : 3*sinc(3*sin(x)),
sin(x)/y : sin(x)/y
})
def test_optims_numpy():
def check(d):
for k, v in d.items():
assert optimize(k, optims_numpy) == v
x = Symbol('x')
check({
sin(2*x)/(2*x) + exp(2*x) - 1: sinc(2*x) + expm1(2*x),
log(x+3)/log(2) + log(x**2 + 1): log1p(x**2) + log2(x+3)
})
@XFAIL # room for improvement, ideally this test case should pass.
def test_optims_numpy_TODO():
def check(d):
for k, v in d.items():
assert optimize(k, optims_numpy) == v
x, y = map(Symbol, 'x y'.split())
check({
log(x*y)*sin(x*y)*log(x*y+1)/(log(2)*x*y): log2(x*y)*sinc(x*y)*log1p(x*y),
exp(x*sin(y)/y) - 1: expm1(x*sinc(y))
})
|
e103f58e77f398e7a2a66760cb65543f68ef05f999e22e88b8d8009641d29b53 | from sympy import (
symbols, IndexedBase, Identity, cos, Inverse, tensorcontraction,
permutedims, tensorproduct, ZeroMatrix)
from sympy.codegen.array_utils import (
CodegenArrayContraction, CodegenArrayTensorProduct, CodegenArrayDiagonal,
CodegenArrayPermuteDims, CodegenArrayElementwiseAdd, _codegen_array_parse,
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, MatMul, Transpose
from sympy.tensor.array.expressions.array_expressions import ZeroArray
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) == CodegenArrayTensorProduct(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
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
cg = CodegenArrayPermuteDims(
CodegenArrayContraction(
CodegenArrayTensorProduct(
a,
CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(b, c),
CodegenArrayTensorProduct(c, b),
)
), (2, 4)), [0, 1, 3, 2])
assert recognize_matrix_expression(cg) == a*(b.T*c + c.T*b)
za = ZeroArray(m, n)
assert recognize_matrix_expression(za) == ZeroMatrix(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))
cg = CodegenArrayElementwiseAdd(M, N)
cg2 = CodegenArrayElementwiseAdd(cg, P)
assert isinstance(cg2, CodegenArrayElementwiseAdd)
assert cg2.args == (M, N, P)
assert cg2.shape == (k, k)
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]))
assert recognize_matrix_expression(expr) == M + Transpose(M)
expr = M[i,j] + N[i,j]
p1, p2 = _codegen_array_parse(expr)
assert recognize_matrix_expression(p1) == M + N
expr = M[i,j] + N[j,i]
p1, p2 = _codegen_array_parse(expr)
assert recognize_matrix_expression(p1) == M + N.T
expr = M[i,j]*N[k,l] + N[i,j]*M[k,l]
p1, p2 = _codegen_array_parse(expr)
assert recognize_matrix_expression(p1) == CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayTensorProduct(N, M))
expr = (M*N*P)[i, j]
p1, p2 = _codegen_array_parse(expr)
assert recognize_matrix_expression(p1) == M*N*P
expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1))
p1, p2 = _codegen_array_parse(expr)
assert recognize_matrix_expression(p1) == 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)
assert recognize_matrix_expression(p1) == M*P*N + M*P.T*N + N*P*M + N*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) == CodegenArrayTensorProduct(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) == CodegenArrayTensorProduct(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) == CodegenArrayTensorProduct(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 == rexpr
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*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) == CodegenArrayTensorProduct(M, N.T)
assert recognize_matrix_expression(cg2) == CodegenArrayTensorProduct(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) == CodegenArrayTensorProduct(M*P.T*Trace(N), Q.T)
assert recognize_matrix_expression(cg2) == CodegenArrayTensorProduct(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
def test_array_wrong_permutation_size():
cg = CodegenArrayTensorProduct(M, N)
raises(ValueError, lambda: CodegenArrayPermuteDims(cg, [1, 0]))
raises(ValueError, lambda: CodegenArrayPermuteDims(cg, [1, 0, 2, 3, 5, 4]))
def test_nested_array_elementwise_add():
cg = CodegenArrayContraction(CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayTensorProduct(N, M)
), (1, 2))
result = CodegenArrayElementwiseAdd(
CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2)),
CodegenArrayContraction(CodegenArrayTensorProduct(N, M), (1, 2))
)
assert cg == result
cg = CodegenArrayDiagonal(CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayTensorProduct(N, M)
), (1, 2))
result = CodegenArrayElementwiseAdd(
CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2)),
CodegenArrayDiagonal(CodegenArrayTensorProduct(N, M), (1, 2))
)
assert cg == result
def test_array_expr_zero_array():
za1 = ZeroArray(k, l, m, n)
zm1 = ZeroMatrix(m, n)
za2 = ZeroArray(k, m, m, n)
zm2 = ZeroMatrix(m, m)
zm3 = ZeroMatrix(k, k)
assert CodegenArrayTensorProduct(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n)
assert CodegenArrayTensorProduct(M, N, zm1) == ZeroArray(k, k, k, k, m, n)
assert CodegenArrayContraction(za1, (3,)) == ZeroArray(k, l, m)
assert CodegenArrayContraction(zm1, (1,)) == ZeroArray(m)
assert CodegenArrayContraction(za2, (1, 2)) == ZeroArray(k, n)
assert CodegenArrayContraction(zm2, (0, 1)) == 0
assert CodegenArrayDiagonal(za2, (1, 2)) == ZeroArray(k, n, m)
assert CodegenArrayDiagonal(zm2, (0, 1)) == ZeroArray(m)
assert CodegenArrayPermuteDims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k)
assert CodegenArrayPermuteDims(zm1, [1, 0]) == ZeroArray(n, m)
assert CodegenArrayElementwiseAdd(za1) == za1
assert CodegenArrayElementwiseAdd(zm1) == ZeroArray(m, n)
tp1 = CodegenArrayTensorProduct(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n))
assert CodegenArrayElementwiseAdd(tp1, za1) == tp1
tp2 = CodegenArrayTensorProduct(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n))
assert CodegenArrayElementwiseAdd(tp1, za1, tp2) == CodegenArrayElementwiseAdd(tp1, tp2)
assert CodegenArrayElementwiseAdd(M, zm3) == M
assert CodegenArrayElementwiseAdd(M, N, zm3) == CodegenArrayElementwiseAdd(M, N)
def test_contraction_tp_additions():
a = CodegenArrayElementwiseAdd(
CodegenArrayTensorProduct(M, N),
CodegenArrayTensorProduct(N, M)
)
tp = CodegenArrayTensorProduct(P, a, Q)
expr = CodegenArrayContraction(tp, (3, 4))
expected = CodegenArrayTensorProduct(
P,
CodegenArrayElementwiseAdd(
CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2)),
CodegenArrayContraction(CodegenArrayTensorProduct(N, M), (1, 2)),
),
Q
)
assert expr == expected
assert recognize_matrix_expression(expr) == CodegenArrayTensorProduct(P, M*N + N*M, Q)
expr = CodegenArrayContraction(tp, (1, 2), (3, 4), (5, 6))
result = CodegenArrayContraction(
CodegenArrayTensorProduct(
P,
CodegenArrayElementwiseAdd(
CodegenArrayContraction(CodegenArrayTensorProduct(M, N), (1, 2)),
CodegenArrayContraction(CodegenArrayTensorProduct(N, M), (1, 2)),
),
Q
), (1, 2), (3, 4))
assert expr == result
assert recognize_matrix_expression(expr) == P*(M*N + N*M)*Q
|
c2f14d1527f44b87a06d8ed1130d15d00342d370ae89153d3cb99d8b5e957c7a | from sympy.assumptions import Predicate
from sympy.multipledispatch import Dispatcher
class PrimePredicate(Predicate):
"""
Prime number predicate.
Explanation
===========
``ask(Q.prime(x))`` is true iff ``x`` is a natural number greater
than 1 that has no positive divisors other than ``1`` and the
number itself.
Examples
========
>>> from sympy import Q, ask
>>> ask(Q.prime(0))
False
>>> ask(Q.prime(1))
False
>>> ask(Q.prime(2))
True
>>> ask(Q.prime(20))
False
>>> ask(Q.prime(-3))
False
"""
name = 'prime'
handler = Dispatcher(
"PrimeHandler",
doc=("Handler for key 'prime'. 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.")
)
class CompositePredicate(Predicate):
"""
Composite number predicate.
Explanation
===========
``ask(Q.composite(x))`` is true iff ``x`` is a positive integer and has
at least one positive divisor other than ``1`` and the number itself.
Examples
========
>>> from sympy import Q, ask
>>> ask(Q.composite(0))
False
>>> ask(Q.composite(1))
False
>>> ask(Q.composite(2))
False
>>> ask(Q.composite(20))
True
"""
name = 'composite'
handler = Dispatcher("CompositeHandler", doc="Handler for key 'composite'.")
class EvenPredicate(Predicate):
"""
Even number predicate.
Explanation
===========
``ask(Q.even(x))`` is true iff ``x`` belongs to the set of even
integers.
Examples
========
>>> from sympy import Q, ask, pi
>>> ask(Q.even(0))
True
>>> ask(Q.even(2))
True
>>> ask(Q.even(3))
False
>>> ask(Q.even(pi))
False
"""
name = 'even'
handler = Dispatcher("EvenHandler", doc="Handler for key 'even'.")
class OddPredicate(Predicate):
"""
Odd number predicate.
Explanation
===========
``ask(Q.odd(x))`` is true iff ``x`` belongs to the set of odd numbers.
Examples
========
>>> from sympy import Q, ask, pi
>>> ask(Q.odd(0))
False
>>> ask(Q.odd(2))
False
>>> ask(Q.odd(3))
True
>>> ask(Q.odd(pi))
False
"""
name = 'odd'
handler = Dispatcher(
"OddHandler",
doc=("Handler for key 'odd'. Test that an expression represents an odd"
" number.")
)
|
1edce9839a8a00fe961dc584446ba2c4f42cfdbb820cfb570887baf6ca03d115 | from sympy.assumptions import Predicate
from sympy.multipledispatch import Dispatcher
class CommutativePredicate(Predicate):
"""
Commutative predicate.
Explanation
===========
``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other
object with respect to multiplication operation.
"""
# TODO: Add examples
name = 'commutative'
handler = Dispatcher("FiniteHandler", doc="Handler for key 'commutative'.")
class IsTruePredicate(Predicate):
"""
Generic predicate.
Explanation
===========
``ask(Q.is_true(x))`` is true iff ``x`` is true. This only makes
sense if ``x`` is a predicate.
Examples
========
>>> from sympy import ask, Q, symbols
>>> x = symbols('x')
>>> ask(Q.is_true(True))
True
"""
name = 'is_true'
handler = Dispatcher(
"FiniteHandler",
doc="Wrapper allowing to query the truth value of a boolean expression."
)
|
8c3c61af69dd0e369d3600c2f1009b1bf63374f6c61adf7eb57d6a859b1e67e7 | from sympy.assumptions import Predicate
from sympy.multipledispatch import Dispatcher
class SquarePredicate(Predicate):
"""
Square matrix predicate.
Explanation
===========
``Q.square(x)`` is true iff ``x`` is a square matrix. A square matrix
is a matrix with the same number of rows and columns.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('X', 2, 3)
>>> ask(Q.square(X))
True
>>> ask(Q.square(Y))
False
>>> ask(Q.square(ZeroMatrix(3, 3)))
True
>>> ask(Q.square(Identity(3)))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Square_matrix
"""
name = 'square'
handler = Dispatcher("SquareHandler", doc="Handler for Q.square.")
class SymmetricPredicate(Predicate):
"""
Symmetric matrix predicate.
Explanation
===========
``Q.symmetric(x)`` is true iff ``x`` is a square matrix and is equal to
its transpose. Every square diagonal matrix is a symmetric matrix.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('Y', 2, 3)
>>> Z = MatrixSymbol('Z', 2, 2)
>>> ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z))
True
>>> ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z))
True
>>> ask(Q.symmetric(Y))
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Symmetric_matrix
"""
# TODO: Add handlers to make these keys work with
# actual matrices and add more examples in the docstring.
name = 'symmetric'
handler = Dispatcher("SymmetricHandler", doc="Handler for Q.symmetric.")
class InvertiblePredicate(Predicate):
"""
Invertible matrix predicate.
Explanation
===========
``Q.invertible(x)`` is true iff ``x`` is an invertible matrix.
A square matrix is called invertible only if its determinant is 0.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('Y', 2, 3)
>>> Z = MatrixSymbol('Z', 2, 2)
>>> ask(Q.invertible(X*Y), Q.invertible(X))
False
>>> ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z))
True
>>> ask(Q.invertible(X), Q.fullrank(X) & Q.square(X))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Invertible_matrix
"""
name = 'invertible'
handler = Dispatcher("InvertibleHandler", doc="Handler for Q.invertible.")
class OrthogonalPredicate(Predicate):
"""
Orthogonal matrix predicate.
Explanation
===========
``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix.
A square matrix ``M`` is an orthogonal matrix if it satisfies
``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of
``M`` and ``I`` is an identity matrix. Note that an orthogonal
matrix is necessarily invertible.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, Identity
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('Y', 2, 3)
>>> Z = MatrixSymbol('Z', 2, 2)
>>> ask(Q.orthogonal(Y))
False
>>> ask(Q.orthogonal(X*Z*X), Q.orthogonal(X) & Q.orthogonal(Z))
True
>>> ask(Q.orthogonal(Identity(3)))
True
>>> ask(Q.invertible(X), Q.orthogonal(X))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Orthogonal_matrix
"""
name = 'orthogonal'
handler = Dispatcher("OrthogonalHandler", doc="Handler for key 'orthogonal'.")
class UnitaryPredicate(Predicate):
"""
Unitary matrix predicate.
Explanation
===========
``Q.unitary(x)`` is true iff ``x`` is a unitary matrix.
Unitary matrix is an analogue to orthogonal matrix. A square
matrix ``M`` with complex elements is unitary if :math:``M^TM = MM^T= I``
where :math:``M^T`` is the conjugate transpose matrix of ``M``.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, Identity
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('Y', 2, 3)
>>> Z = MatrixSymbol('Z', 2, 2)
>>> ask(Q.unitary(Y))
False
>>> ask(Q.unitary(X*Z*X), Q.unitary(X) & Q.unitary(Z))
True
>>> ask(Q.unitary(Identity(3)))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Unitary_matrix
"""
name = 'unitary'
handler = Dispatcher("UnitaryHandler", doc="Handler for key 'unitary'.")
class FullRankPredicate(Predicate):
"""
Fullrank matrix predicate.
Explanation
===========
``Q.fullrank(x)`` is true iff ``x`` is a full rank matrix.
A matrix is full rank if all rows and columns of the matrix
are linearly independent. A square matrix is full rank iff
its determinant is nonzero.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity
>>> X = MatrixSymbol('X', 2, 2)
>>> ask(Q.fullrank(X.T), Q.fullrank(X))
True
>>> ask(Q.fullrank(ZeroMatrix(3, 3)))
False
>>> ask(Q.fullrank(Identity(3)))
True
"""
name = 'fullrank'
handler = Dispatcher("FullRankHandler", doc="Handler for key 'fullrank'.")
class PositiveDefinitePredicate(Predicate):
r"""
Positive definite matrix predicate.
Explanation
===========
If ``M`` is a :math:``n \times n`` symmetric real matrix, it is said
to be positive definite if :math:`Z^TMZ` is positive for
every non-zero column vector ``Z`` of ``n`` real numbers.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, Identity
>>> X = MatrixSymbol('X', 2, 2)
>>> Y = MatrixSymbol('Y', 2, 3)
>>> Z = MatrixSymbol('Z', 2, 2)
>>> ask(Q.positive_definite(Y))
False
>>> ask(Q.positive_definite(Identity(3)))
True
>>> ask(Q.positive_definite(X + Z), Q.positive_definite(X) &
... Q.positive_definite(Z))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Positive-definite_matrix
"""
name = "positive_definite"
handler = Dispatcher("PositiveDefiniteHandler", doc="Handler for key 'positive_definite'.")
class UpperTriangularPredicate(Predicate):
"""
Upper triangular matrix predicate.
Explanation
===========
A matrix ``M`` is called upper triangular matrix if :math:`M_{ij}=0`
for :math:`i<j`.
Examples
========
>>> from sympy import Q, ask, ZeroMatrix, Identity
>>> ask(Q.upper_triangular(Identity(3)))
True
>>> ask(Q.upper_triangular(ZeroMatrix(3, 3)))
True
References
==========
.. [1] http://mathworld.wolfram.com/UpperTriangularMatrix.html
"""
name = "upper_triangular"
handler = Dispatcher("UpperTriangularHandler", doc="Handler for key 'upper_triangular'.")
class LowerTriangularPredicate(Predicate):
"""
Lower triangular matrix predicate.
Explanation
===========
A matrix ``M`` is called lower triangular matrix if :math:`a_{ij}=0`
for :math:`i>j`.
Examples
========
>>> from sympy import Q, ask, ZeroMatrix, Identity
>>> ask(Q.lower_triangular(Identity(3)))
True
>>> ask(Q.lower_triangular(ZeroMatrix(3, 3)))
True
References
==========
.. [1] http://mathworld.wolfram.com/LowerTriangularMatrix.html
"""
name = "lower_triangular"
handler = Dispatcher("LowerTriangularHandler", doc="Handler for key 'lower_triangular'.")
class DiagonalPredicate(Predicate):
"""
Diagonal matrix predicate.
Explanation
===========
``Q.diagonal(x)`` is true iff ``x`` is a diagonal matrix. A diagonal
matrix is a matrix in which the entries outside the main diagonal
are all zero.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix
>>> X = MatrixSymbol('X', 2, 2)
>>> ask(Q.diagonal(ZeroMatrix(3, 3)))
True
>>> ask(Q.diagonal(X), Q.lower_triangular(X) &
... Q.upper_triangular(X))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Diagonal_matrix
"""
name = "diagonal"
handler = Dispatcher("DiagonalHandler", doc="Handler for key 'diagonal'.")
class IntegerElementsPredicate(Predicate):
"""
Integer elements matrix predicate.
Explanation
===========
``Q.integer_elements(x)`` is true iff all the elements of ``x``
are integers.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.integer(X[1, 2]), Q.integer_elements(X))
True
"""
name = "integer_elements"
handler = Dispatcher("IntegerElementsHandler", doc="Handler for key 'integer_elements'.")
class RealElementsPredicate(Predicate):
"""
Real elements matrix predicate.
Explanation
===========
``Q.real_elements(x)`` is true iff all the elements of ``x``
are real numbers.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.real(X[1, 2]), Q.real_elements(X))
True
"""
name = "real_elements"
handler = Dispatcher("RealElementsHandler", doc="Handler for key 'real_elements'.")
class ComplexElementsPredicate(Predicate):
"""
Complex elements matrix predicate.
Explanation
===========
``Q.complex_elements(x)`` is true iff all the elements of ``x``
are complex numbers.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.complex(X[1, 2]), Q.complex_elements(X))
True
>>> ask(Q.complex_elements(X), Q.integer_elements(X))
True
"""
name = "complex_elements"
handler = Dispatcher("ComplexElementsHandler", doc="Handler for key 'complex_elements'.")
class SingularPredicate(Predicate):
"""
Singular matrix predicate.
A matrix is singular iff the value of its determinant is 0.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.singular(X), Q.invertible(X))
False
>>> ask(Q.singular(X), ~Q.invertible(X))
True
References
==========
.. [1] http://mathworld.wolfram.com/SingularMatrix.html
"""
name = "singular"
handler = Dispatcher("SingularHandler", doc="Predicate fore key 'singular'.")
class NormalPredicate(Predicate):
"""
Normal matrix predicate.
A matrix is normal if it commutes with its conjugate transpose.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.normal(X), Q.unitary(X))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Normal_matrix
"""
name = "normal"
handler = Dispatcher("NormalHandler", doc="Predicate fore key 'normal'.")
class TriangularPredicate(Predicate):
"""
Triangular matrix predicate.
Explanation
===========
``Q.triangular(X)`` is true if ``X`` is one that is either lower
triangular or upper triangular.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.triangular(X), Q.upper_triangular(X))
True
>>> ask(Q.triangular(X), Q.lower_triangular(X))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Triangular_matrix
"""
name = "triangular"
handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.")
class UnitTriangularPredicate(Predicate):
"""
Unit triangular matrix predicate.
Explanation
===========
A unit triangular matrix is a triangular matrix with 1s
on the diagonal.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.triangular(X), Q.unit_triangular(X))
True
"""
name = "unit_triangular"
handler = Dispatcher("UnitTriangularHandler", doc="Predicate fore key 'unit_triangular'.")
|
062c44b0fdad63429266bb4596e4b1ba35809a532dc3e4f8e8d2fe2692d09a6d | from sympy.assumptions import Predicate
from sympy.multipledispatch import Dispatcher
class NegativePredicate(Predicate):
r"""
Negative number predicate.
Explanation
===========
``Q.negative(x)`` is true iff ``x`` is a real number and :math:`x < 0`, that is,
it is in the interval :math:`(-\infty, 0)`. Note in particular that negative
infinity is not negative.
A few important facts about negative numbers:
- Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same
thing. ``~Q.negative(x)`` simply means that ``x`` is not negative,
whereas ``Q.nonnegative(x)`` means that ``x`` is real and not
negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to
``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is
true, whereas ``Q.nonnegative(I)`` is false.
- See the documentation of ``Q.real`` for more information about
related facts.
Examples
========
>>> from sympy import Q, ask, symbols, I
>>> x = symbols('x')
>>> ask(Q.negative(x), Q.real(x) & ~Q.positive(x) & ~Q.zero(x))
True
>>> ask(Q.negative(-1))
True
>>> ask(Q.nonnegative(I))
False
>>> ask(~Q.negative(I))
True
"""
name = 'negative'
handler = Dispatcher(
"NegativeHandler",
doc=("Handler for Q.negative. Test that an expression is strictly less"
" than zero.")
)
class NonNegativePredicate(Predicate):
"""
Nonnegative real number predicate.
Explanation
===========
``ask(Q.nonnegative(x))`` is true iff ``x`` belongs to the set of
positive numbers including zero.
- Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same
thing. ``~Q.negative(x)`` simply means that ``x`` is not negative,
whereas ``Q.nonnegative(x)`` means that ``x`` is real and not
negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to
``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is
true, whereas ``Q.nonnegative(I)`` is false.
Examples
========
>>> from sympy import Q, ask, I
>>> ask(Q.nonnegative(1))
True
>>> ask(Q.nonnegative(0))
True
>>> ask(Q.nonnegative(-1))
False
>>> ask(Q.nonnegative(I))
False
>>> ask(Q.nonnegative(-I))
False
"""
name = 'nonnegative'
handler = Dispatcher(
"NonNegativeHandler",
doc=("Handler for Q.nonnegative.")
)
class NonZeroPredicate(Predicate):
"""
Nonzero real number predicate.
Explanation
===========
``ask(Q.nonzero(x))`` is true iff ``x`` is real and ``x`` is not zero. Note in
particular that ``Q.nonzero(x)`` is false if ``x`` is not real. Use
``~Q.zero(x)`` if you want the negation of being zero without any real
assumptions.
A few important facts about nonzero numbers:
- ``Q.nonzero`` is logically equivalent to ``Q.positive | Q.negative``.
- See the documentation of ``Q.real`` for more information about
related facts.
Examples
========
>>> from sympy import Q, ask, symbols, I, oo
>>> x = symbols('x')
>>> print(ask(Q.nonzero(x), ~Q.zero(x)))
None
>>> ask(Q.nonzero(x), Q.positive(x))
True
>>> ask(Q.nonzero(x), Q.zero(x))
False
>>> ask(Q.nonzero(0))
False
>>> ask(Q.nonzero(I))
False
>>> ask(~Q.zero(I))
True
>>> ask(Q.nonzero(oo))
False
"""
name = 'nonzero'
handler = Dispatcher(
"NonZeroHandler",
doc=("Handler for key 'zero'. Test that an expression is not identically"
" zero.")
)
class ZeroPredicate(Predicate):
"""
Zero number predicate.
Explanation
===========
``ask(Q.zero(x))`` is true iff the value of ``x`` is zero.
Examples
========
>>> from sympy import ask, Q, oo, symbols
>>> x, y = symbols('x, y')
>>> ask(Q.zero(0))
True
>>> ask(Q.zero(1/oo))
True
>>> ask(Q.zero(0*oo))
False
>>> ask(Q.zero(1))
False
>>> ask(Q.zero(x*y), Q.zero(x) | Q.zero(y))
True
"""
name = 'zero'
handler = Dispatcher(
"ZeroHandler",
doc="Handler for key 'zero'."
)
class NonPositivePredicate(Predicate):
"""
Nonpositive real number predicate.
Explanation
===========
``ask(Q.nonpositive(x))`` is true iff ``x`` belongs to the set of
negative numbers including zero.
- Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same
thing. ``~Q.positive(x)`` simply means that ``x`` is not positive,
whereas ``Q.nonpositive(x)`` means that ``x`` is real and not
positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to
`Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is
true, whereas ``Q.nonpositive(I)`` is false.
Examples
========
>>> from sympy import Q, ask, I
>>> ask(Q.nonpositive(-1))
True
>>> ask(Q.nonpositive(0))
True
>>> ask(Q.nonpositive(1))
False
>>> ask(Q.nonpositive(I))
False
>>> ask(Q.nonpositive(-I))
False
"""
name = 'nonpositive'
handler = Dispatcher(
"NonPositiveHandler",
doc="Handler for key 'nonpositive'."
)
class PositivePredicate(Predicate):
r"""
Positive real number predicate.
Explanation
===========
``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x``
is in the interval `(0, \infty)`. In particular, infinity is not
positive.
A few important facts about positive numbers:
- Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same
thing. ``~Q.positive(x)`` simply means that ``x`` is not positive,
whereas ``Q.nonpositive(x)`` means that ``x`` is real and not
positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to
`Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is
true, whereas ``Q.nonpositive(I)`` is false.
- See the documentation of ``Q.real`` for more information about
related facts.
Examples
========
>>> from sympy import Q, ask, symbols, I
>>> x = symbols('x')
>>> ask(Q.positive(x), Q.real(x) & ~Q.negative(x) & ~Q.zero(x))
True
>>> ask(Q.positive(1))
True
>>> ask(Q.nonpositive(I))
False
>>> ask(~Q.positive(I))
True
"""
name = 'positive'
handler = Dispatcher(
"PositiveHandler",
doc=("Handler for key 'positive'. Test that an expression is strictly"
" greater than zero.")
)
|
96f8c07cf773d0c0e34f18eecdb052181728d8e9a96518868b1486d286a2662d | """
Multipledispatch handlers for ``Predicate`` are implemented here.
Handlers in this module are not directly imported to other modules in
order to avoid circular import problem.
"""
from .common import (AskHandler, CommonHandler,
test_closed_group)
__all__ = [
'AskHandler', 'CommonHandler',
'test_closed_group'
]
|
0346dad29a6eaf38dc386583d1c478388922450510f6c0f3cb46a22fca72f769 | """
Handlers for keys related to number theory: prime, even, odd, etc.
"""
from sympy.assumptions import Q, ask
from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S
from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NegativeInfinity,
NumberSymbol, Rational)
from sympy.functions import Abs, im, re
from sympy.ntheory import isprime
from ..predicates.ntheory import (PrimePredicate, CompositePredicate,
EvenPredicate, OddPredicate)
# PrimePredicate
def _PrimePredicate_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
@PrimePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_prime
@PrimePredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
@PrimePredicate.register(Mul)
def _(expr, assumptions):
if expr.is_number:
return _PrimePredicate_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
@PrimePredicate.register(Pow)
def _(expr, assumptions):
"""
Integer**Integer -> !Prime
"""
if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions) and \
ask(Q.integer(expr.base), assumptions):
return False
@PrimePredicate.register(Integer)
def _(expr, assumptions):
return isprime(expr)
@PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
def _(expr, assumptions):
return False
@PrimePredicate.register(Float)
def _(expr, assumptions):
return _PrimePredicate_number(expr, assumptions)
@PrimePredicate.register(NumberSymbol)
def _(expr, assumptions):
return _PrimePredicate_number(expr, assumptions)
# CompositePredicate
@CompositePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_composite
@CompositePredicate.register(Basic)
def _(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
# EvenPredicate
def _EvenPredicate_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
@EvenPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_even
@EvenPredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
return _EvenPredicate_number(expr, assumptions)
@EvenPredicate.register(Mul)
def _(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 _EvenPredicate_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
@EvenPredicate.register(Add)
def _(expr, assumptions):
"""
Even + Odd -> Odd
Even + Even -> Even
Odd + Odd -> Even
"""
if expr.is_number:
return _EvenPredicate_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
@EvenPredicate.register(Pow)
def _(expr, assumptions):
if expr.is_number:
return _EvenPredicate_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
@EvenPredicate.register(Integer)
def _(expr, assumptions):
return not bool(expr.p & 1)
@EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
def _(expr, assumptions):
return False
@EvenPredicate.register(NumberSymbol)
def _(expr, assumptions):
return _EvenPredicate_number(expr, assumptions)
@EvenPredicate.register(Abs)
def _(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return ask(Q.even(expr.args[0]), assumptions)
@EvenPredicate.register(re)
def _(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return ask(Q.even(expr.args[0]), assumptions)
@EvenPredicate.register(im)
def _(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
# OddPredicate
@OddPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_odd
@OddPredicate.register(Basic)
def _(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
|
25b9e85bd07ec6059d15fc099d2d1c09981c8a99deb07041732757a3620d578c | """
This module defines base class for handlers and some core handlers:
``Q.commutative`` and ``Q.is_true``.
"""
from sympy.assumptions import Q, ask, AppliedPredicate
from sympy.core import Basic, Symbol
from sympy.core.logic import _fuzzy_group
from sympy.core.numbers import NaN, Number
from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts,
Equivalent, Implies, Not, Or)
from sympy.utilities.exceptions import SymPyDeprecationWarning
from ..predicates.common import CommutativePredicate, IsTruePredicate
class AskHandler:
"""Base class that all Ask Handlers must inherit."""
def __new__(cls, *args, **kwargs):
SymPyDeprecationWarning(
feature="AskHandler() class",
useinstead="multipledispatch handler",
issue=20873,
deprecated_since_version="1.8"
).warn()
return super().__new__(cls, *args, **kwargs)
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
# CommutativePredicate
@CommutativePredicate.register(Symbol)
def _(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
@CommutativePredicate.register(Basic)
def _(expr, assumptions):
for arg in expr.args:
if not ask(Q.commutative(arg), assumptions):
return False
return True
@CommutativePredicate.register(Number)
def _(expr, assumptions):
return True
@CommutativePredicate.register(NaN)
def _(expr, assumptions):
return True
# IsTruePredicate
@IsTruePredicate.register(bool)
def _(expr, assumptions):
return expr
@IsTruePredicate.register(BooleanTrue)
def _(expr, assumptions):
return True
@IsTruePredicate.register(BooleanFalse)
def _(expr, assumptions):
return False
@IsTruePredicate.register(AppliedPredicate)
def _(expr, assumptions):
return ask(expr, assumptions)
@IsTruePredicate.register(Not)
def _(expr, assumptions):
value = ask(expr.args[0], assumptions=assumptions)
if value in (True, False):
return not value
else:
return None
@IsTruePredicate.register(Or)
def _(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
@IsTruePredicate.register(And)
def _(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
@IsTruePredicate.register(Implies)
def _(expr, assumptions):
p, q = expr.args
return ask(~p | q, assumptions=assumptions)
@IsTruePredicate.register(Equivalent)
def _(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)
|
56190651573ba7a6e4c35595c48b1ebde5c4ada2bb96a86e488ae86174918881 | """
This module contains query handlers responsible for Matrices queries:
Square, Symmetric, Invertible etc.
"""
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import test_closed_group
from sympy.matrices import MatrixBase
from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant,
DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul,
MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose,
ZeroMatrix)
from sympy.matrices.expressions.factorizations import Factorization
from sympy.matrices.expressions.fourier import DFT
from sympy.core.logic import fuzzy_and
from sympy.utilities.iterables import sift
from sympy.core import Basic
from ..predicates.matrices import (SquarePredicate, SymmetricPredicate,
InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate,
FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate,
LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate,
RealElementsPredicate, ComplexElementsPredicate)
def _Factorization(predicate, expr, assumptions):
if predicate in expr.predicates:
return True
# SquarePredicate
@SquarePredicate.register(MatrixExpr)
def _(expr, assumptions):
return expr.shape[0] == expr.shape[1]
# SymmetricPredicate
@SymmetricPredicate.register(MatMul)
def _(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)
@SymmetricPredicate.register(MatPow)
def _(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
@SymmetricPredicate.register(MatAdd)
def _(expr, assumptions):
return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args)
@SymmetricPredicate.register(MatrixSymbol)
def _(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
@SymmetricPredicate.register_many(OneMatrix, ZeroMatrix)
def _(expr, assumptions):
return ask(Q.square(expr), assumptions)
@SymmetricPredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.symmetric(expr.arg), assumptions)
@SymmetricPredicate.register(MatrixSlice)
def _(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)
@SymmetricPredicate.register(Identity)
def _(expr, assumptions):
return True
# InvertiblePredicate
@InvertiblePredicate.register(MatMul)
def _(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
@InvertiblePredicate.register(MatPow)
def _(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
@InvertiblePredicate.register(MatAdd)
def _(expr, assumptions):
return None
@InvertiblePredicate.register(MatrixSymbol)
def _(expr, assumptions):
if not expr.is_square:
return False
if Q.invertible(expr) in conjuncts(assumptions):
return True
@InvertiblePredicate.register_many(Identity, Inverse)
def _(expr, assumptions):
return True
@InvertiblePredicate.register(ZeroMatrix)
def _(expr, assumptions):
return False
@InvertiblePredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@InvertiblePredicate.register(Transpose)
def _(expr, assumptions):
return ask(Q.invertible(expr.arg), assumptions)
@InvertiblePredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.invertible(expr.parent), assumptions)
@InvertiblePredicate.register(MatrixBase)
def _(expr, assumptions):
if not expr.is_square:
return False
return expr.rank() == expr.rows
@InvertiblePredicate.register(MatrixExpr)
def _(expr, assumptions):
if not expr.is_square:
return False
return None
@InvertiblePredicate.register(BlockMatrix)
def _(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
@InvertiblePredicate.register(BlockDiagMatrix)
def _(expr, assumptions):
if expr.rowblocksizes != expr.colblocksizes:
return None
return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag])
# OrthogonalPredicate
@OrthogonalPredicate.register(MatMul)
def _(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
@OrthogonalPredicate.register(MatPow)
def _(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
@OrthogonalPredicate.register(MatAdd)
def _(expr, assumptions):
if (len(expr.args) == 1 and
ask(Q.orthogonal(expr.args[0]), assumptions)):
return True
@OrthogonalPredicate.register(MatrixSymbol)
def _(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
@OrthogonalPredicate.register(Identity)
def _(expr, assumptions):
return True
@OrthogonalPredicate.register(ZeroMatrix)
def _(expr, assumptions):
return False
@OrthogonalPredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.orthogonal(expr.arg), assumptions)
@OrthogonalPredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.orthogonal(expr.parent), assumptions)
@OrthogonalPredicate.register(Factorization)
def _(expr, assumptions):
return _Factorization(Q.orthogonal, expr, assumptions)
# UnitaryPredicate
@UnitaryPredicate.register(MatMul)
def _(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
@UnitaryPredicate.register(MatPow)
def _(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
@UnitaryPredicate.register(MatrixSymbol)
def _(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
@UnitaryPredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.unitary(expr.arg), assumptions)
@UnitaryPredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.unitary(expr.parent), assumptions)
@UnitaryPredicate.register_many(DFT, Identity)
def _(expr, assumptions):
return True
@UnitaryPredicate.register(ZeroMatrix)
def _(expr, assumptions):
return False
@UnitaryPredicate.register(Factorization)
def _(expr, assumptions):
return _Factorization(Q.unitary, expr, assumptions)
# FullRankPredicate
@FullRankPredicate.register(MatMul)
def _(expr, assumptions):
if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args):
return True
@FullRankPredicate.register(MatPow)
def _(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
@FullRankPredicate.register(Identity)
def _(expr, assumptions):
return True
@FullRankPredicate.register(ZeroMatrix)
def _(expr, assumptions):
return False
@FullRankPredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@FullRankPredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.fullrank(expr.arg), assumptions)
@FullRankPredicate.register(MatrixSlice)
def _(expr, assumptions):
if ask(Q.orthogonal(expr.parent), assumptions):
return True
# PositiveDefinitePredicate
@PositiveDefinitePredicate.register(MatMul)
def _(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)
@PositiveDefinitePredicate.register(MatPow)
def _(expr, assumptions):
# a power of a positive definite matrix is positive definite
if ask(Q.positive_definite(expr.args[0]), assumptions):
return True
@PositiveDefinitePredicate.register(MatAdd)
def _(expr, assumptions):
if all(ask(Q.positive_definite(arg), assumptions)
for arg in expr.args):
return True
@PositiveDefinitePredicate.register(MatrixSymbol)
def _(expr, assumptions):
if not expr.is_square:
return False
if Q.positive_definite(expr) in conjuncts(assumptions):
return True
@PositiveDefinitePredicate.register(Identity)
def _(expr, assumptions):
return True
@PositiveDefinitePredicate.register(ZeroMatrix)
def _(expr, assumptions):
return False
@PositiveDefinitePredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@PositiveDefinitePredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.positive_definite(expr.arg), assumptions)
@PositiveDefinitePredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.positive_definite(expr.parent), assumptions)
# UpperTriangularPredicate
@UpperTriangularPredicate.register(MatMul)
def _(expr, assumptions):
factor, matrices = expr.as_coeff_matrices()
if all(ask(Q.upper_triangular(m), assumptions) for m in matrices):
return True
@UpperTriangularPredicate.register(MatAdd)
def _(expr, assumptions):
if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args):
return True
@UpperTriangularPredicate.register(MatPow)
def _(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
@UpperTriangularPredicate.register(MatrixSymbol)
def _(expr, assumptions):
if Q.upper_triangular(expr) in conjuncts(assumptions):
return True
@UpperTriangularPredicate.register_many(Identity, ZeroMatrix)
def _(expr, assumptions):
return True
@UpperTriangularPredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@UpperTriangularPredicate.register(Transpose)
def _(expr, assumptions):
return ask(Q.lower_triangular(expr.arg), assumptions)
@UpperTriangularPredicate.register(Inverse)
def _(expr, assumptions):
return ask(Q.upper_triangular(expr.arg), assumptions)
@UpperTriangularPredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.upper_triangular(expr.parent), assumptions)
@UpperTriangularPredicate.register(Factorization)
def _(expr, assumptions):
return _Factorization(Q.upper_triangular, expr, assumptions)
# LowerTriangularPredicate
@LowerTriangularPredicate.register(MatMul)
def _(expr, assumptions):
factor, matrices = expr.as_coeff_matrices()
if all(ask(Q.lower_triangular(m), assumptions) for m in matrices):
return True
@LowerTriangularPredicate.register(MatAdd)
def _(expr, assumptions):
if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args):
return True
@LowerTriangularPredicate.register(MatPow)
def _(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
@LowerTriangularPredicate.register(MatrixSymbol)
def _(expr, assumptions):
if Q.lower_triangular(expr) in conjuncts(assumptions):
return True
@LowerTriangularPredicate.register_many(Identity, ZeroMatrix)
def _(expr, assumptions):
return True
@LowerTriangularPredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@LowerTriangularPredicate.register(Transpose)
def _(expr, assumptions):
return ask(Q.upper_triangular(expr.arg), assumptions)
@LowerTriangularPredicate.register(Inverse)
def _(expr, assumptions):
return ask(Q.lower_triangular(expr.arg), assumptions)
@LowerTriangularPredicate.register(MatrixSlice)
def _(expr, assumptions):
if not expr.on_diag:
return None
else:
return ask(Q.lower_triangular(expr.parent), assumptions)
@LowerTriangularPredicate.register(Factorization)
def _(expr, assumptions):
return _Factorization(Q.lower_triangular, expr, assumptions)
# DiagonalPredicate
def _is_empty_or_1x1(expr):
return expr.shape == (0, 0) or expr.shape == (1, 1)
@DiagonalPredicate.register(MatMul)
def _(expr, assumptions):
if _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
@DiagonalPredicate.register(MatPow)
def _(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
@DiagonalPredicate.register(MatAdd)
def _(expr, assumptions):
if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args):
return True
@DiagonalPredicate.register(MatrixSymbol)
def _(expr, assumptions):
if _is_empty_or_1x1(expr):
return True
if Q.diagonal(expr) in conjuncts(assumptions):
return True
@DiagonalPredicate.register(OneMatrix)
def _(expr, assumptions):
return expr.shape[0] == 1 and expr.shape[1] == 1
@DiagonalPredicate.register_many(Inverse, Transpose)
def _(expr, assumptions):
return ask(Q.diagonal(expr.arg), assumptions)
@DiagonalPredicate.register(MatrixSlice)
def _(expr, assumptions):
if _is_empty_or_1x1(expr):
return True
if not expr.on_diag:
return None
else:
return ask(Q.diagonal(expr.parent), assumptions)
@DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix)
def _(expr, assumptions):
return True
@DiagonalPredicate.register(Factorization)
def _(expr, assumptions):
return _Factorization(Q.diagonal, expr, assumptions)
# IntegerElementsPredicate
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)])
@IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd,
Trace, Transpose)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.integer_elements)
@IntegerElementsPredicate.register(MatPow)
def _(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
@IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix)
def _(expr, assumptions):
return True
@IntegerElementsPredicate.register(MatMul)
def _(expr, assumptions):
return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions)
@IntegerElementsPredicate.register(MatrixSlice)
def _(expr, assumptions):
return MS_elements(Q.integer_elements, expr, assumptions)
@IntegerElementsPredicate.register(BlockMatrix)
def _(expr, assumptions):
return BM_elements(Q.integer_elements, expr, assumptions)
# RealElementsPredicate
@RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
MatAdd, Trace, Transpose)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.real_elements)
@RealElementsPredicate.register(MatPow)
def _(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
@RealElementsPredicate.register(MatMul)
def _(expr, assumptions):
return MatMul_elements(Q.real_elements, Q.real, expr, assumptions)
@RealElementsPredicate.register(MatrixSlice)
def _(expr, assumptions):
return MS_elements(Q.real_elements, expr, assumptions)
@RealElementsPredicate.register(BlockMatrix)
def _(expr, assumptions):
return BM_elements(Q.real_elements, expr, assumptions)
# ComplexElementsPredicate
@ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
Inverse, MatAdd, Trace, Transpose)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.complex_elements)
@ComplexElementsPredicate.register(MatPow)
def _(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
@ComplexElementsPredicate.register(MatMul)
def _(expr, assumptions):
return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions)
@ComplexElementsPredicate.register(MatrixSlice)
def _(expr, assumptions):
return MS_elements(Q.complex_elements, expr, assumptions)
@ComplexElementsPredicate.register(BlockMatrix)
def _(expr, assumptions):
return BM_elements(Q.complex_elements, expr, assumptions)
@ComplexElementsPredicate.register(DFT)
def _(expr, assumptions):
return True
|
4e5a75885f566cd8648ea2b9a15d9e1ce62c1775bc1af6c8534f12428cfcef06 | """
Handlers related to order relations: positive, negative, etc.
"""
from sympy.assumptions import Q, ask
from sympy.core import Add, Basic, Expr, Mul, Pow
from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or
from sympy.core.numbers import ImaginaryUnit, NaN
from sympy.functions import Abs, acos, acot, asin, atan, exp, factorial, log
from sympy.matrices import Determinant, Trace
from sympy.matrices.expressions.matexpr import MatrixElement
from ..predicates.order import (NegativePredicate, NonNegativePredicate,
NonZeroPredicate, ZeroPredicate, NonPositivePredicate, PositivePredicate)
# NegativePredicate
def _NegativePredicate_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
@NegativePredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
return _NegativePredicate_number(expr, assumptions)
@NegativePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_negative
@NegativePredicate.register(Add)
def _(expr, assumptions):
"""
Positive + Positive -> Positive,
Negative + Negative -> Negative
"""
if expr.is_number:
return _NegativePredicate_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
@NegativePredicate.register(Mul)
def _(expr, assumptions):
if expr.is_number:
return _NegativePredicate_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
@NegativePredicate.register(Pow)
def _(expr, assumptions):
"""
Real ** Even -> NonNegative
Real ** Odd -> same_as_base
NonNegative ** Positive -> NonNegative
"""
if expr.is_number:
return _NegativePredicate_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)
@NegativePredicate.register_many(Abs, ImaginaryUnit)
def _(expr, assumptions):
return False
@NegativePredicate.register(exp)
def _(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return False
# NonNegativePredicate
@NonNegativePredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
notnegative = fuzzy_not(_NegativePredicate_number(expr, assumptions))
if notnegative:
return ask(Q.real(expr), assumptions)
else:
return notnegative
@NonNegativePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_nonnegative
# NonZeroPredicate
@NonZeroPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_nonzero
@NonZeroPredicate.register(Basic)
def _(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())
@NonZeroPredicate.register(Add)
def _(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
@NonZeroPredicate.register(Mul)
def _(expr, assumptions):
for arg in expr.args:
result = ask(Q.nonzero(arg), assumptions)
if result:
continue
return result
return True
@NonZeroPredicate.register(Pow)
def _(expr, assumptions):
return ask(Q.nonzero(expr.base), assumptions)
@NonZeroPredicate.register(NaN)
def _(expr, assumptions):
return True
@NonZeroPredicate.register(Abs)
def _(expr, assumptions):
return ask(Q.nonzero(expr.args[0]), assumptions)
# ZeroPredicate
@ZeroPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_zero
@ZeroPredicate.register(Basic)
def _(expr, assumptions):
return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)),
ask(Q.real(expr), assumptions)])
@ZeroPredicate.register(Mul)
def _(expr, assumptions):
# TODO: This should be deducible from the nonzero handler
return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args)
# NonPositivePredicate
@NonPositivePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_nonpositive
@NonPositivePredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
notpositive = fuzzy_not(_PositivePredicate_number(expr, assumptions))
if notpositive:
return ask(Q.real(expr), assumptions)
else:
return notpositive
# PositivePredicate
def _PositivePredicate_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
@PositivePredicate.register(Expr)
def _(expr, assumptions):
return expr.is_positive
@PositivePredicate.register(Basic)
def _(expr, assumptions):
if expr.is_number:
return _PositivePredicate_number(expr, assumptions)
@PositivePredicate.register(Mul)
def _(expr, assumptions):
if expr.is_number:
return _PositivePredicate_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
@PositivePredicate.register(Add)
def _(expr, assumptions):
if expr.is_number:
return _PositivePredicate_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
@PositivePredicate.register(Pow)
def _(expr, assumptions):
if expr.is_number:
return _PositivePredicate_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
@PositivePredicate.register(exp)
def _(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)
@PositivePredicate.register(log)
def _(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
@PositivePredicate.register(factorial)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.integer(x) & Q.positive(x), assumptions):
return True
@PositivePredicate.register(ImaginaryUnit)
def _(expr, assumptions):
return False
@PositivePredicate.register(Abs)
def _(expr, assumptions):
return ask(Q.nonzero(expr), assumptions)
@PositivePredicate.register(Trace)
def _(expr, assumptions):
if ask(Q.positive_definite(expr.arg), assumptions):
return True
@PositivePredicate.register(Determinant)
def _(expr, assumptions):
if ask(Q.positive_definite(expr.arg), assumptions):
return True
@PositivePredicate.register(MatrixElement)
def _(expr, assumptions):
if (expr.i == expr.j
and ask(Q.positive_definite(expr.parent), assumptions)):
return True
@PositivePredicate.register(atan)
def _(expr, assumptions):
return ask(Q.positive(expr.args[0]), assumptions)
@PositivePredicate.register(asin)
def _(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
@PositivePredicate.register(acos)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions):
return True
@PositivePredicate.register(acot)
def _(expr, assumptions):
return ask(Q.real(expr.args[0]), assumptions)
|
4b1bb53084d0a1743c9a4c968ebf64084b37610e5ede5998467333e3b1b3dfda | """
Handlers for predicates related to set membership: integer, rational, etc.
"""
from sympy.assumptions import Q, ask
from sympy.core import Add, Basic, Expr, Mul, Pow
from sympy.core.numbers import (AlgebraicNumber, ComplexInfinity, Exp1, Float,
GoldenRatio, ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity,
Number, NumberSymbol, Pi, pi, Rational, TribonacciConstant)
from sympy.core.logic import fuzzy_bool
from sympy.functions import (Abs, acos, acot, asin, atan, cos, cot, exp, im,
log, re, sin, tan)
from sympy import I, Eq, conjugate
from sympy.matrices import Determinant, MatrixBase, Trace
from sympy.matrices.expressions.matexpr import MatrixElement
from .common import test_closed_group
from ..predicates.sets import (IntegerPredicate, RationalPredicate,
IrrationalPredicate, RealPredicate, ExtendedRealPredicate,
HermitianPredicate, ComplexPredicate, ImaginaryPredicate,
AntihermitianPredicate, AlgebraicPredicate)
# IntegerPredicate
def _IntegerPredicate_number(expr, assumptions):
# helper function
try:
i = int(expr.round())
if not (expr - i).equals(0):
raise TypeError
return True
except TypeError:
return False
@IntegerPredicate.register_many(int, Integer)
def _(expr, assumptions):
return True
@IntegerPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, NaN,
NegativeInfinity, Pi, Rational, TribonacciConstant)
def _(expr, assumptions):
return False
@IntegerPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_integer
@IntegerPredicate.register_many(Add, Pow)
def _(expr, assumptions):
"""
* Integer + Integer -> Integer
* Integer + !Integer -> !Integer
* !Integer + !Integer -> ?
"""
if expr.is_number:
return _IntegerPredicate_number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.integer)
@IntegerPredicate.register(Mul)
def _(expr, assumptions):
"""
* Integer*Integer -> Integer
* Integer*Irrational -> !Integer
* Odd/Even -> !Integer
* Integer*Rational -> ?
"""
if expr.is_number:
return _IntegerPredicate_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
@IntegerPredicate.register(Abs)
def _(expr, assumptions):
return ask(Q.integer(expr.args[0]), assumptions)
@IntegerPredicate.register_many(Determinant, MatrixElement, Trace)
def _(expr, assumptions):
return ask(Q.integer_elements(expr.args[0]), assumptions)
# RationalPredicate
@RationalPredicate.register(Rational)
def _(expr, assumptions):
return True
@RationalPredicate.register(Float)
def _(expr, assumptions):
return None
@RationalPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity,
NaN, NegativeInfinity, Pi, TribonacciConstant)
def _(expr, assumptions):
return False
@RationalPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_rational
@RationalPredicate.register_many(Add, Mul)
def _(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)
@RationalPredicate.register(Pow)
def _(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
@RationalPredicate.register_many(asin, atan, cos, exp, sin, tan)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@RationalPredicate.register_many(acot, cot)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return False
@RationalPredicate.register_many(acos, log)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
# IrrationalPredicate
@IrrationalPredicate.register(NaN)
def _(expr, assumptions):
return False
@IrrationalPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_irrational
@IrrationalPredicate.register(Basic)
def _(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
# RealPredicate
def _RealPredicate_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
@RealPredicate.register_many(Abs, Exp1, Float, GoldenRatio, im, Pi, Rational,
re, TribonacciConstant)
def _(expr, assumptions):
return True
@RealPredicate.register_many(ImaginaryUnit, Infinity, NaN, NegativeInfinity)
def _(expr, assumptions):
return False
@RealPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_real
@RealPredicate.register(Add)
def _(expr, assumptions):
"""
* Real + Real -> Real
* Real + (Complex & !Real) -> !Real
"""
if expr.is_number:
return _RealPredicate_number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.real)
@RealPredicate.register(Mul)
def _(expr, assumptions):
"""
* Real*Real -> Real
* Real*Imaginary -> !Real
* Imaginary*Imaginary -> Real
"""
if expr.is_number:
return _RealPredicate_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
@RealPredicate.register(Pow)
def _(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 _RealPredicate_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
@RealPredicate.register_many(cos, sin)
def _(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
@RealPredicate.register(exp)
def _(expr, assumptions):
return ask(
Q.integer(expr.args[0]/I/pi) | Q.real(expr.args[0]), assumptions
)
@RealPredicate.register(log)
def _(expr, assumptions):
return ask(Q.positive(expr.args[0]), assumptions)
@RealPredicate.register_many(Determinant, MatrixElement, Trace)
def _(expr, assumptions):
return ask(Q.real_elements(expr.args[0]), assumptions)
# ExtendedRealPredicate
@ExtendedRealPredicate.register(object)
def _(expr, assumptions):
return ask(Q.real(expr), assumptions)
@ExtendedRealPredicate.register_many(Infinity, NegativeInfinity)
def _(expr, assumptions):
return True
@ExtendedRealPredicate.register(NaN)
def _(expr, assumptions):
return False
@ExtendedRealPredicate.register_many(Add, Mul, Pow)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.extended_real)
# HermitianPredicate
@HermitianPredicate.register(NaN)
def _(expr, assumptions):
return False
@HermitianPredicate.register(object)
def _(expr, assumptions):
if isinstance(expr, MatrixBase):
return None
return ask(Q.real(expr), assumptions)
@HermitianPredicate.register(Add)
def _(expr, assumptions):
"""
* Hermitian + Hermitian -> Hermitian
* Hermitian + !Hermitian -> !Hermitian
"""
if expr.is_number:
return None
return test_closed_group(expr, assumptions, Q.hermitian)
@HermitianPredicate.register(Mul)
def _(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 None
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
@HermitianPredicate.register(Pow)
def _(expr, assumptions):
"""
* Hermitian**Integer -> Hermitian
"""
if expr.is_number:
return None
if ask(Q.hermitian(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
return True
@HermitianPredicate.register_many(cos, exp, sin)
def _(expr, assumptions):
if ask(Q.hermitian(expr.args[0]), assumptions):
return True
@HermitianPredicate.register(MatrixBase)
def _(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
# ComplexPredicate
@ComplexPredicate.register_many(Abs, cos, exp, im, ImaginaryUnit, log, Number,
NumberSymbol, re, sin)
def _(expr, assumptions):
return True
@ComplexPredicate.register_many(Infinity, NaN, NegativeInfinity)
def _(expr, assumptions):
return False
@ComplexPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_complex
@ComplexPredicate.register_many(Add, Mul, Pow)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.complex)
@ComplexPredicate.register_many(Determinant, MatrixElement, Trace)
def _(expr, assumptions):
return ask(Q.complex_elements(expr.args[0]), assumptions)
# ImaginaryPredicate
def _Imaginary_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
@ImaginaryPredicate.register(ImaginaryUnit)
def _(expr, assumptions):
return True
@ImaginaryPredicate.register(NaN)
def _(expr, assumptions):
return False
@ImaginaryPredicate.register(Expr)
def _(expr, assumptions):
return expr.is_imaginary
@ImaginaryPredicate.register(Add)
def _(expr, assumptions):
"""
* Imaginary + Imaginary -> Imaginary
* Imaginary + Complex -> ?
* Imaginary + Real -> !Imaginary
"""
if expr.is_number:
return _Imaginary_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
@ImaginaryPredicate.register(Mul)
def _(expr, assumptions):
"""
* Real*Imaginary -> Imaginary
* Imaginary*Imaginary -> Real
"""
if expr.is_number:
return _Imaginary_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
@ImaginaryPredicate.register(Pow)
def _(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 _Imaginary_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:
# I**i -> real; (2*I)**i -> complex ==> not imaginary
return False
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
@ImaginaryPredicate.register(log)
def _(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
@ImaginaryPredicate.register(exp)
def _(expr, assumptions):
a = expr.args[0]/I/pi
return ask(Q.integer(2*a) & ~Q.integer(a), assumptions)
@ImaginaryPredicate.register_many(Number, NumberSymbol)
def _(expr, assumptions):
return not (expr.as_real_imag()[1] == 0)
# AntihermitianPredicate
@AntihermitianPredicate.register(NaN)
def _(expr, assumptions):
return False
@AntihermitianPredicate.register(object)
def _(expr, assumptions):
if isinstance(expr, MatrixBase):
return None
return ask(Q.imaginary(expr), assumptions)
@AntihermitianPredicate.register(Add)
def _(expr, assumptions):
"""
* Antihermitian + Antihermitian -> Antihermitian
* Antihermitian + !Antihermitian -> !Antihermitian
"""
if expr.is_number:
return None
return test_closed_group(expr, assumptions, Q.antihermitian)
@AntihermitianPredicate.register(Mul)
def _(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 None
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
@AntihermitianPredicate.register(Pow)
def _(expr, assumptions):
"""
* Hermitian**Integer -> !Antihermitian
* Antihermitian**Even -> !Antihermitian
* Antihermitian**Odd -> Antihermitian
"""
if expr.is_number:
return None
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
@AntihermitianPredicate.register(MatrixBase)
def _(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
# AlgebraicPredicate
@AlgebraicPredicate.register_many(AlgebraicNumber, Float, GoldenRatio,
ImaginaryUnit, TribonacciConstant)
def _(expr, assumptions):
return True
@AlgebraicPredicate.register_many(ComplexInfinity, Exp1, Infinity, NaN,
NegativeInfinity, Pi)
def _(expr, assumptions):
return False
@AlgebraicPredicate.register_many(Add, Mul)
def _(expr, assumptions):
return test_closed_group(expr, assumptions, Q.algebraic)
@AlgebraicPredicate.register(Pow)
def _(expr, assumptions):
return expr.exp.is_Rational and ask(Q.algebraic(expr.base), assumptions)
@AlgebraicPredicate.register(Rational)
def _(expr, assumptions):
return expr.q != 0
@AlgebraicPredicate.register_many(asin, atan, cos, exp, sin, tan)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@AlgebraicPredicate.register_many(acot, cot)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return False
@AlgebraicPredicate.register_many(acos, log)
def _(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
|
ffd41c2e345ca5afd7eb91091d8917d633c254b81a120e1170f159724c5f8907 | from sympy import (Abs, exp, Expr, I, pi, Q, Rational, refine, S, sqrt,
atan, atan2, nan, Symbol, re, im, sign)
from sympy.abc import w, x, y, z
from sympy.core.relational import Eq, Ne
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices.expressions.matexpr import MatrixSymbol
def test_Abs():
assert refine(Abs(x), Q.positive(x)) == x
assert refine(1 + Abs(x), Q.positive(x)) == 1 + x
assert refine(Abs(x), Q.negative(x)) == -x
assert refine(1 + Abs(x), Q.negative(x)) == 1 - x
assert refine(Abs(x**2)) != x**2
assert refine(Abs(x**2), Q.real(x)) == x**2
def test_pow1():
assert refine((-1)**x, Q.even(x)) == 1
assert refine((-1)**x, Q.odd(x)) == -1
assert refine((-2)**x, Q.even(x)) == 2**x
# nested powers
assert refine(sqrt(x**2)) != Abs(x)
assert refine(sqrt(x**2), Q.complex(x)) != Abs(x)
assert refine(sqrt(x**2), Q.real(x)) == Abs(x)
assert refine(sqrt(x**2), Q.positive(x)) == x
assert refine((x**3)**Rational(1, 3)) != x
assert refine((x**3)**Rational(1, 3), Q.real(x)) != x
assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x
assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x)
assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x)
# powers of (-1)
assert refine((-1)**(x + y), Q.even(x)) == (-1)**y
assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y
assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y
assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1)
assert refine((-1)**(x + 3)) == (-1)**(x + 1)
# continuation
assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x
assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1)
assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1)
def test_pow2():
assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1)
assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x
# powers of Abs
assert refine(Abs(x)**2, Q.real(x)) == x**2
assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3
assert refine(Abs(x)**2) == Abs(x)**2
def test_exp():
x = Symbol('x', integer=True)
assert refine(exp(pi*I*2*x)) == 1
assert refine(exp(pi*I*2*(x + S.Half))) == -1
assert refine(exp(pi*I*2*(x + Rational(1, 4)))) == I
assert refine(exp(pi*I*2*(x + Rational(3, 4)))) == -I
def test_Piecewise():
assert refine(Piecewise((1, x < 0), (3, True)), Q.is_true(x < 0)) == 1
assert refine(Piecewise((1, x < 0), (3, True)), ~Q.is_true(x < 0)) == 3
assert refine(Piecewise((1, x < 0), (3, True)), Q.is_true(y < 0)) == \
Piecewise((1, x < 0), (3, True))
assert refine(Piecewise((1, x > 0), (3, True)), Q.is_true(x > 0)) == 1
assert refine(Piecewise((1, x > 0), (3, True)), ~Q.is_true(x > 0)) == 3
assert refine(Piecewise((1, x > 0), (3, True)), Q.is_true(y > 0)) == \
Piecewise((1, x > 0), (3, True))
assert refine(Piecewise((1, x <= 0), (3, True)), Q.is_true(x <= 0)) == 1
assert refine(Piecewise((1, x <= 0), (3, True)), ~Q.is_true(x <= 0)) == 3
assert refine(Piecewise((1, x <= 0), (3, True)), Q.is_true(y <= 0)) == \
Piecewise((1, x <= 0), (3, True))
assert refine(Piecewise((1, x >= 0), (3, True)), Q.is_true(x >= 0)) == 1
assert refine(Piecewise((1, x >= 0), (3, True)), ~Q.is_true(x >= 0)) == 3
assert refine(Piecewise((1, x >= 0), (3, True)), Q.is_true(y >= 0)) == \
Piecewise((1, x >= 0), (3, True))
assert refine(Piecewise((1, Eq(x, 0)), (3, True)), Q.is_true(Eq(x, 0)))\
== 1
assert refine(Piecewise((1, Eq(x, 0)), (3, True)), Q.is_true(Eq(0, x)))\
== 1
assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~Q.is_true(Eq(x, 0)))\
== 3
assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~Q.is_true(Eq(0, x)))\
== 3
assert refine(Piecewise((1, Eq(x, 0)), (3, True)), Q.is_true(Eq(y, 0)))\
== Piecewise((1, Eq(x, 0)), (3, True))
assert refine(Piecewise((1, Ne(x, 0)), (3, True)), Q.is_true(Ne(x, 0)))\
== 1
assert refine(Piecewise((1, Ne(x, 0)), (3, True)), ~Q.is_true(Ne(x, 0)))\
== 3
assert refine(Piecewise((1, Ne(x, 0)), (3, True)), Q.is_true(Ne(y, 0)))\
== Piecewise((1, Ne(x, 0)), (3, True))
def test_atan2():
assert refine(atan2(y, x), Q.real(y) & Q.positive(x)) == atan(y/x)
assert refine(atan2(y, x), Q.negative(y) & Q.positive(x)) == atan(y/x)
assert refine(atan2(y, x), Q.negative(y) & Q.negative(x)) == atan(y/x) - pi
assert refine(atan2(y, x), Q.positive(y) & Q.negative(x)) == atan(y/x) + pi
assert refine(atan2(y, x), Q.zero(y) & Q.negative(x)) == pi
assert refine(atan2(y, x), Q.positive(y) & Q.zero(x)) == pi/2
assert refine(atan2(y, x), Q.negative(y) & Q.zero(x)) == -pi/2
assert refine(atan2(y, x), Q.zero(y) & Q.zero(x)) is nan
def test_re():
assert refine(re(x), Q.real(x)) == x
assert refine(re(x), Q.imaginary(x)) is S.Zero
assert refine(re(x+y), Q.real(x) & Q.real(y)) == x + y
assert refine(re(x+y), Q.real(x) & Q.imaginary(y)) == x
assert refine(re(x*y), Q.real(x) & Q.real(y)) == x * y
assert refine(re(x*y), Q.real(x) & Q.imaginary(y)) == 0
assert refine(re(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) == x * y * z
def test_im():
assert refine(im(x), Q.imaginary(x)) == -I*x
assert refine(im(x), Q.real(x)) is S.Zero
assert refine(im(x+y), Q.imaginary(x) & Q.imaginary(y)) == -I*x - I*y
assert refine(im(x+y), Q.real(x) & Q.imaginary(y)) == -I*y
assert refine(im(x*y), Q.imaginary(x) & Q.real(y)) == -I*x*y
assert refine(im(x*y), Q.imaginary(x) & Q.imaginary(y)) == 0
assert refine(im(1/x), Q.imaginary(x)) == -I/x
assert refine(im(x*y*z), Q.imaginary(x) & Q.imaginary(y)
& Q.imaginary(z)) == -I*x*y*z
def test_complex():
assert refine(re(1/(x + I*y)), Q.real(x) & Q.real(y)) == \
x/(x**2 + y**2)
assert refine(im(1/(x + I*y)), Q.real(x) & Q.real(y)) == \
-y/(x**2 + y**2)
assert refine(re((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y)
& Q.real(z)) == w*y - x*z
assert refine(im((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y)
& Q.real(z)) == w*z + x*y
def test_sign():
x = Symbol('x', real = True)
assert refine(sign(x), Q.positive(x)) == 1
assert refine(sign(x), Q.negative(x)) == -1
assert refine(sign(x), Q.zero(x)) == 0
assert refine(sign(x), True) == sign(x)
assert refine(sign(Abs(x)), Q.nonzero(x)) == 1
x = Symbol('x', imaginary=True)
assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit
assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit
assert refine(sign(x), True) == sign(x)
x = Symbol('x', complex=True)
assert refine(sign(x), Q.zero(x)) == 0
def test_func_args():
class MyClass(Expr):
# A class with nontrivial .func
def __init__(self, *args):
self.my_member = ""
@property
def func(self):
def my_func(*args):
obj = MyClass(*args)
obj.my_member = self.my_member
return obj
return my_func
x = MyClass()
x.my_member = "A very important value"
assert x.my_member == refine(x).my_member
def test_eval_refine():
from sympy.core.expr import Expr
class MockExpr(Expr):
def _eval_refine(self, assumptions):
return True
mock_obj = MockExpr()
assert refine(mock_obj)
def test_refine_issue_12724():
expr1 = refine(Abs(x * y), Q.positive(x))
expr2 = refine(Abs(x * y * z), Q.positive(x))
assert expr1 == x * Abs(y)
assert expr2 == x * Abs(y * z)
y1 = Symbol('y1', real = True)
expr3 = refine(Abs(x * y1**2 * z), Q.positive(x))
assert expr3 == x * y1**2 * Abs(z)
def test_matrixelement():
x = MatrixSymbol('x', 3, 3)
i = Symbol('i', positive = True)
j = Symbol('j', positive = True)
assert refine(x[0, 1], Q.symmetric(x)) == x[0, 1]
assert refine(x[1, 0], Q.symmetric(x)) == x[0, 1]
assert refine(x[i, j], Q.symmetric(x)) == x[j, i]
assert refine(x[j, i], Q.symmetric(x)) == x[j, i]
|
ec2352c79fa52679b02f91e34ab0fd70c92987d7c5c7e78bde5a5055f2f807b6 | from sympy.abc import t, w, x, y, z, n, k, m, p, i
from sympy.assumptions import (ask, AssumptionsContext, Q, register_handler,
remove_handler)
from sympy.assumptions.assume import assuming, global_assumptions, Predicate
from sympy.assumptions.ask import compute_known_facts, single_fact_lookup
from sympy.assumptions.handlers import AskHandler
from sympy.core.add import Add
from sympy.core.numbers import (I, Integer, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.power import Pow
from sympy.core.symbol import symbols, Symbol
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, im, re, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (
acos, acot, asin, atan, cos, cot, sin, tan)
from sympy.logic.boolalg import Equivalent, Implies, Xor, And, to_cnf
from sympy.matrices import Matrix, SparseMatrix
from sympy.testing.pytest import XFAIL, slow, raises, warns_deprecated_sympy
import math
def test_int_1():
z = 1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_int_11():
z = 11
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is True
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_int_12():
z = 12
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is True
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is True
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_float_1():
z = 1.0
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is None
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is None
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = 7.2123
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is None
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is None
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
# test for issue #12168
assert ask(Q.rational(math.pi)) is None
def test_zero_0():
z = Integer(0)
assert ask(Q.nonzero(z)) is False
assert ask(Q.zero(z)) is True
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is True
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_negativeone():
z = Integer(-1)
assert ask(Q.nonzero(z)) is True
assert ask(Q.zero(z)) is False
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is True
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_infinity():
assert ask(Q.commutative(oo)) is True
assert ask(Q.integer(oo)) is False
assert ask(Q.rational(oo)) is False
assert ask(Q.algebraic(oo)) is False
assert ask(Q.real(oo)) is False
assert ask(Q.extended_real(oo)) is True
assert ask(Q.complex(oo)) is False
assert ask(Q.irrational(oo)) is False
assert ask(Q.imaginary(oo)) is False
assert ask(Q.positive(oo)) is False
#assert ask(Q.extended_positive(oo)) is True
assert ask(Q.negative(oo)) is False
assert ask(Q.even(oo)) is False
assert ask(Q.odd(oo)) is False
assert ask(Q.finite(oo)) is False
assert ask(Q.prime(oo)) is False
assert ask(Q.composite(oo)) is False
assert ask(Q.hermitian(oo)) is False
assert ask(Q.antihermitian(oo)) is False
def test_neg_infinity():
mm = S.NegativeInfinity
assert ask(Q.commutative(mm)) is True
assert ask(Q.integer(mm)) is False
assert ask(Q.rational(mm)) is False
assert ask(Q.algebraic(mm)) is False
assert ask(Q.real(mm)) is False
assert ask(Q.extended_real(mm)) is True
assert ask(Q.complex(mm)) is False
assert ask(Q.irrational(mm)) is False
assert ask(Q.imaginary(mm)) is False
assert ask(Q.positive(mm)) is False
assert ask(Q.negative(mm)) is False
#assert ask(Q.extended_negative(mm)) is True
assert ask(Q.even(mm)) is False
assert ask(Q.odd(mm)) is False
assert ask(Q.finite(mm)) is False
assert ask(Q.prime(mm)) is False
assert ask(Q.composite(mm)) is False
assert ask(Q.hermitian(mm)) is False
assert ask(Q.antihermitian(mm)) is False
def test_nan():
nan = S.NaN
assert ask(Q.commutative(nan)) is True
assert ask(Q.integer(nan)) is False
assert ask(Q.rational(nan)) is False
assert ask(Q.algebraic(nan)) is False
assert ask(Q.real(nan)) is False
assert ask(Q.extended_real(nan)) is False
assert ask(Q.complex(nan)) is False
assert ask(Q.irrational(nan)) is False
assert ask(Q.imaginary(nan)) is False
assert ask(Q.positive(nan)) is False
assert ask(Q.nonzero(nan)) is True
assert ask(Q.zero(nan)) is False
assert ask(Q.even(nan)) is False
assert ask(Q.odd(nan)) is False
assert ask(Q.finite(nan)) is False
assert ask(Q.prime(nan)) is False
assert ask(Q.composite(nan)) is False
assert ask(Q.hermitian(nan)) is False
assert ask(Q.antihermitian(nan)) is False
def test_Rational_number():
r = Rational(3, 4)
assert ask(Q.commutative(r)) is True
assert ask(Q.integer(r)) is False
assert ask(Q.rational(r)) is True
assert ask(Q.real(r)) is True
assert ask(Q.complex(r)) is True
assert ask(Q.irrational(r)) is False
assert ask(Q.imaginary(r)) is False
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
assert ask(Q.even(r)) is False
assert ask(Q.odd(r)) is False
assert ask(Q.finite(r)) is True
assert ask(Q.prime(r)) is False
assert ask(Q.composite(r)) is False
assert ask(Q.hermitian(r)) is True
assert ask(Q.antihermitian(r)) is False
r = Rational(1, 4)
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
r = Rational(5, 4)
assert ask(Q.negative(r)) is False
assert ask(Q.positive(r)) is True
r = Rational(5, 3)
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
r = Rational(-3, 4)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
r = Rational(-1, 4)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
r = Rational(-5, 4)
assert ask(Q.negative(r)) is True
assert ask(Q.positive(r)) is False
r = Rational(-5, 3)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
def test_sqrt_2():
z = sqrt(2)
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_pi():
z = S.Pi
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = S.Pi + 1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = 2*S.Pi
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = S.Pi ** 2
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = (1 + S.Pi) ** 2
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_E():
z = S.Exp1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_GoldenRatio():
z = S.GoldenRatio
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_TribonacciConstant():
z = S.TribonacciConstant
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_I():
z = I
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is True
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is True
z = 1 + I
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is False
z = I*(1 + I)
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is False
z = I**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (-I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (3*I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (1)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (-1)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (1+I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (I)**(I+3)
assert ask(Q.imaginary(z)) is True
assert ask(Q.real(z)) is False
z = (I)**(I+2)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (I)**(2)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (I)**(3)
assert ask(Q.imaginary(z)) is True
assert ask(Q.real(z)) is False
z = (3)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (I)**(0)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
def test_bounded():
x, y, z = symbols('x,y,z')
assert ask(Q.finite(x)) is None
assert ask(Q.finite(x), Q.finite(x)) is True
assert ask(Q.finite(x), Q.finite(y)) is None
assert ask(Q.finite(x), Q.complex(x)) is None
assert ask(Q.finite(x + 1)) is None
assert ask(Q.finite(x + 1), Q.finite(x)) is True
a = x + y
x, y = a.args
# B + B
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive(x)) is True
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive(y)) is True
assert ask(Q.finite(a),
Q.finite(x) & Q.finite(y) & Q.positive(x) & Q.positive(y)) is True
assert ask(Q.finite(a),
Q.finite(x) & Q.finite(y) & Q.positive(x) & ~Q.positive(y)) is True
assert ask(Q.finite(a),
Q.finite(x) & Q.finite(y) & ~Q.positive(x) & Q.positive(y)) is True
assert ask(Q.finite(a),
Q.finite(x) & Q.finite(y) & ~Q.positive(x) & ~Q.positive(y)) is True
# B + U
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive(x)) is False
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive(x) &
Q.positive(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive(x) &
~Q.positive(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.positive(x) &
Q.positive(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.positive(x) &
~Q.positive(y)) is False
# B + ?
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(x)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.positive(x) & Q.positive(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.positive(x) & ~Q.positive(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.positive(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.positive(y)) is None
# U + U
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.positive(x)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.positive(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.positive(x) &
Q.positive(y)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.positive(x) &
~Q.positive(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.positive(x) &
Q.positive(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.positive(x) &
~Q.positive(y)) is False
# U + ?
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(y) & Q.positive(x)) is None
assert ask(Q.finite(a), ~Q.finite(y) & Q.positive(y)) is None
assert ask(
Q.finite(a), ~Q.finite(y) & Q.positive(x) & Q.positive(y)) is False
assert ask(
Q.finite(a), ~Q.finite(y) & Q.positive(x) & ~Q.positive(y)) is None
assert ask(
Q.finite(a), ~Q.finite(y) & ~Q.positive(x) & Q.positive(y)) is None
assert ask(
Q.finite(a), ~Q.finite(y) & ~Q.positive(x) & ~Q.positive(y)) is False
# ? + ?
assert ask(Q.finite(a),) is None
assert ask(Q.finite(a), Q.positive(x)) is None
assert ask(Q.finite(a), Q.positive(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.positive(y)) is None
assert ask(Q.finite(a), ~Q.positive(x) & Q.positive(y)) is None
assert ask(Q.finite(a), ~Q.positive(x) & ~Q.positive(y)) is None
x, y, z = symbols('x,y,z')
a = x + y + z
x, y, z = a.args
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
Q.finite(y) & Q.negative(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & Q.finite(y) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.negative(y) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.finite(y) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.finite(x) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.positive(y) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.negative(z)) is False
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.negative(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is False
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.finite(x) & Q.negative(y)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(x)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.finite(x) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.finite(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True
assert ask(Q.finite(a),
Q.finite(x) & Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.finite(x) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) &
Q.positive(y) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.positive(y) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.negative(z)) is False
assert ask(
Q.finite(a), Q.finite(x) & Q.negative(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is False
assert ask(
Q.finite(a), Q.finite(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(z)) is None
assert ask(
Q.finite(a), Q.finite(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & Q.finite(z)) is True
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.positive(y) &
Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.positive(y) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.positive(y) & Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.negative(z)) is False
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.negative(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.positive(x) & Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is False
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.positive(x) & Q.finite(x) & Q.negative(y)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.finite(x)) is None
assert ask(
Q.finite(a), Q.positive(x) & Q.finite(x) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
Q.finite(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.negative(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) & Q.negative(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.negative(z)) is False
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & Q.negative(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
Q.negative(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.negative(x) & ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & Q.negative(y) & Q.negative(z)) is False
assert ask(
Q.finite(a), Q.negative(x) & ~Q.finite(x) & Q.negative(y)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(x)) is None
assert ask(
Q.finite(a), Q.negative(x) & ~Q.finite(x) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
~Q.finite(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.negative(y)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive(z)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(x) & Q.positive(y) &
~Q.finite(y) & Q.positive(z) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
~Q.finite(x) & Q.positive(y) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(x) &
Q.positive(y) & ~Q.finite(y) & Q.positive(z)) is False
assert ask(Q.finite(a), Q.positive(x) &
~Q.finite(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(
Q.finite(a), Q.positive(x) & ~Q.finite(x) & Q.negative(y)) is None
assert ask(Q.finite(a), Q.positive(x) &
~Q.finite(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(x)) is None
assert ask(
Q.finite(a), Q.positive(x) & ~Q.finite(x) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) &
~Q.finite(x) & Q.positive(y) & Q.positive(z)) is False
assert ask(
Q.finite(a), Q.negative(x) & Q.negative(y) & Q.negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.negative(y) & Q.positive(z)) is None
assert ask(Q.finite(a), Q.negative(x)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.positive(z)) is None
assert ask(
Q.finite(a), Q.negative(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(Q.finite(a)) is None
assert ask(Q.finite(a), Q.positive(z)) is None
assert ask(Q.finite(a), Q.positive(y) & Q.positive(z)) is None
assert ask(
Q.finite(a), Q.positive(x) & Q.positive(y) & Q.positive(z)) is None
assert ask(Q.finite(2*x)) is None
assert ask(Q.finite(2*x), Q.finite(x)) is True
x, y, z = symbols('x,y,z')
a = x*y
x, y = a.args
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a)) is None
a = x*y*z
x, y, z = a.args
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True
assert ask(
Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False
assert ask(
Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & Q.finite(y) & Q.finite(z)) is False
assert ask(
Q.finite(a), ~Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False
assert ask(
Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(y) & Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(y) & Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(z) &
Q.nonzero(x) & Q.nonzero(y) & Q.nonzero(z)) is None
assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z) &
Q.nonzero(x) & Q.nonzero(y) & Q.nonzero(z)) is False
x, y, z = symbols('x,y,z')
assert ask(Q.finite(x**2)) is None
assert ask(Q.finite(2**x)) is None
assert ask(Q.finite(2**x), Q.finite(x)) is True
assert ask(Q.finite(x**x)) is None
assert ask(Q.finite(S.Half ** x)) is None
assert ask(Q.finite(S.Half ** x), Q.positive(x)) is True
assert ask(Q.finite(S.Half ** x), Q.negative(x)) is None
assert ask(Q.finite(2**x), Q.negative(x)) is True
assert ask(Q.finite(sqrt(x))) is None
assert ask(Q.finite(2**x), ~Q.finite(x)) is False
assert ask(Q.finite(x**2), ~Q.finite(x)) is False
# sign function
assert ask(Q.finite(sign(x))) is True
assert ask(Q.finite(sign(x)), ~Q.finite(x)) is True
# exponential functions
assert ask(Q.finite(log(x))) is None
assert ask(Q.finite(log(x)), Q.finite(x)) is None
assert ask(Q.finite(log(x)), Q.nonzero(x)) is True
assert ask(Q.finite(log(x)), Q.infinite(x)) is False
assert ask(Q.finite(log(x)), Q.zero(x)) is False
assert ask(Q.finite(exp(x))) is None
assert ask(Q.finite(exp(x)), Q.finite(x)) is True
assert ask(Q.finite(exp(2))) is True
# trigonometric functions
assert ask(Q.finite(sin(x))) is True
assert ask(Q.finite(sin(x)), ~Q.finite(x)) is True
assert ask(Q.finite(cos(x))) is True
assert ask(Q.finite(cos(x)), ~Q.finite(x)) is True
assert ask(Q.finite(2*sin(x))) is True
assert ask(Q.finite(sin(x)**2)) is True
assert ask(Q.finite(cos(x)**2)) is True
assert ask(Q.finite(cos(x) + sin(x))) is True
@XFAIL
def test_bounded_xfail():
"""We need to support relations in ask for this to work"""
assert ask(Q.finite(sin(x)**x)) is True
assert ask(Q.finite(cos(x)**x)) is True
def test_commutative():
"""By default objects are Q.commutative that is why it returns True
for both key=True and key=False"""
assert ask(Q.commutative(x)) is True
assert ask(Q.commutative(x), ~Q.commutative(x)) is False
assert ask(Q.commutative(x), Q.complex(x)) is True
assert ask(Q.commutative(x), Q.imaginary(x)) is True
assert ask(Q.commutative(x), Q.real(x)) is True
assert ask(Q.commutative(x), Q.positive(x)) is True
assert ask(Q.commutative(x), ~Q.commutative(y)) is True
assert ask(Q.commutative(2*x)) is True
assert ask(Q.commutative(2*x), ~Q.commutative(x)) is False
assert ask(Q.commutative(x + 1)) is True
assert ask(Q.commutative(x + 1), ~Q.commutative(x)) is False
assert ask(Q.commutative(x**2)) is True
assert ask(Q.commutative(x**2), ~Q.commutative(x)) is False
assert ask(Q.commutative(log(x))) is True
def test_complex():
assert ask(Q.complex(x)) is None
assert ask(Q.complex(x), Q.complex(x)) is True
assert ask(Q.complex(x), Q.complex(y)) is None
assert ask(Q.complex(x), ~Q.complex(x)) is False
assert ask(Q.complex(x), Q.real(x)) is True
assert ask(Q.complex(x), ~Q.real(x)) is None
assert ask(Q.complex(x), Q.rational(x)) is True
assert ask(Q.complex(x), Q.irrational(x)) is True
assert ask(Q.complex(x), Q.positive(x)) is True
assert ask(Q.complex(x), Q.imaginary(x)) is True
assert ask(Q.complex(x), Q.algebraic(x)) is True
# a+b
assert ask(Q.complex(x + 1), Q.complex(x)) is True
assert ask(Q.complex(x + 1), Q.real(x)) is True
assert ask(Q.complex(x + 1), Q.rational(x)) is True
assert ask(Q.complex(x + 1), Q.irrational(x)) is True
assert ask(Q.complex(x + 1), Q.imaginary(x)) is True
assert ask(Q.complex(x + 1), Q.integer(x)) is True
assert ask(Q.complex(x + 1), Q.even(x)) is True
assert ask(Q.complex(x + 1), Q.odd(x)) is True
assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) is True
assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) is True
# a*x +b
assert ask(Q.complex(2*x + 1), Q.complex(x)) is True
assert ask(Q.complex(2*x + 1), Q.real(x)) is True
assert ask(Q.complex(2*x + 1), Q.positive(x)) is True
assert ask(Q.complex(2*x + 1), Q.rational(x)) is True
assert ask(Q.complex(2*x + 1), Q.irrational(x)) is True
assert ask(Q.complex(2*x + 1), Q.imaginary(x)) is True
assert ask(Q.complex(2*x + 1), Q.integer(x)) is True
assert ask(Q.complex(2*x + 1), Q.even(x)) is True
assert ask(Q.complex(2*x + 1), Q.odd(x)) is True
# x**2
assert ask(Q.complex(x**2), Q.complex(x)) is True
assert ask(Q.complex(x**2), Q.real(x)) is True
assert ask(Q.complex(x**2), Q.positive(x)) is True
assert ask(Q.complex(x**2), Q.rational(x)) is True
assert ask(Q.complex(x**2), Q.irrational(x)) is True
assert ask(Q.complex(x**2), Q.imaginary(x)) is True
assert ask(Q.complex(x**2), Q.integer(x)) is True
assert ask(Q.complex(x**2), Q.even(x)) is True
assert ask(Q.complex(x**2), Q.odd(x)) is True
# 2**x
assert ask(Q.complex(2**x), Q.complex(x)) is True
assert ask(Q.complex(2**x), Q.real(x)) is True
assert ask(Q.complex(2**x), Q.positive(x)) is True
assert ask(Q.complex(2**x), Q.rational(x)) is True
assert ask(Q.complex(2**x), Q.irrational(x)) is True
assert ask(Q.complex(2**x), Q.imaginary(x)) is True
assert ask(Q.complex(2**x), Q.integer(x)) is True
assert ask(Q.complex(2**x), Q.even(x)) is True
assert ask(Q.complex(2**x), Q.odd(x)) is True
assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) is True
# trigonometric expressions
assert ask(Q.complex(sin(x))) is True
assert ask(Q.complex(sin(2*x + 1))) is True
assert ask(Q.complex(cos(x))) is True
assert ask(Q.complex(cos(2*x + 1))) is True
# exponential
assert ask(Q.complex(exp(x))) is True
assert ask(Q.complex(exp(x))) is True
# Q.complexes
assert ask(Q.complex(Abs(x))) is True
assert ask(Q.complex(re(x))) is True
assert ask(Q.complex(im(x))) is True
def test_even_query():
assert ask(Q.even(x)) is None
assert ask(Q.even(x), Q.integer(x)) is None
assert ask(Q.even(x), ~Q.integer(x)) is False
assert ask(Q.even(x), Q.rational(x)) is None
assert ask(Q.even(x), Q.positive(x)) is None
assert ask(Q.even(2*x)) is None
assert ask(Q.even(2*x), Q.integer(x)) is True
assert ask(Q.even(2*x), Q.even(x)) is True
assert ask(Q.even(2*x), Q.irrational(x)) is False
assert ask(Q.even(2*x), Q.odd(x)) is True
assert ask(Q.even(2*x), ~Q.integer(x)) is None
assert ask(Q.even(3*x), Q.integer(x)) is None
assert ask(Q.even(3*x), Q.even(x)) is True
assert ask(Q.even(3*x), Q.odd(x)) is False
assert ask(Q.even(x + 1), Q.odd(x)) is True
assert ask(Q.even(x + 1), Q.even(x)) is False
assert ask(Q.even(x + 2), Q.odd(x)) is False
assert ask(Q.even(x + 2), Q.even(x)) is True
assert ask(Q.even(7 - x), Q.odd(x)) is True
assert ask(Q.even(7 + x), Q.odd(x)) is True
assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) is True
assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) is False
assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) is True
assert ask(Q.even(2*x + 1), Q.integer(x)) is False
assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) is None
assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) is None
assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is True
assert ask(Q.even(x + y + z + t),
Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None
assert ask(Q.even(Abs(x)), Q.even(x)) is True
assert ask(Q.even(Abs(x)), ~Q.even(x)) is None
assert ask(Q.even(re(x)), Q.even(x)) is True
assert ask(Q.even(re(x)), ~Q.even(x)) is None
assert ask(Q.even(im(x)), Q.even(x)) is True
assert ask(Q.even(im(x)), Q.real(x)) is True
assert ask(Q.even((-1)**n), Q.integer(n)) is False
assert ask(Q.even(k**2), Q.even(k)) is True
assert ask(Q.even(n**2), Q.odd(n)) is False
assert ask(Q.even(2**k), Q.even(k)) is None
assert ask(Q.even(x**2)) is None
assert ask(Q.even(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is False
assert ask(Q.even(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is True
assert ask(Q.even(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is False
assert ask(Q.even(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.even(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.even(k**x), Q.even(k)) is None
assert ask(Q.even(n**x), Q.odd(n)) is None
assert ask(Q.even(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.even(x*x), Q.integer(x)) is None
assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.odd(y)) is True
assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.even(y)) is None
@XFAIL
def test_evenness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True
assert ask(Q.even(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True
def test_evenness_in_ternary_integer_product_with_even():
assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None
def test_extended_real():
assert ask(Q.extended_real(x), Q.positive(x)) is True
assert ask(Q.extended_real(-x), Q.positive(x)) is True
assert ask(Q.extended_real(-x), Q.negative(x)) is True
assert ask(Q.extended_real(x + S.Infinity), Q.real(x)) is True
def test_rational():
assert ask(Q.rational(x), Q.integer(x)) is True
assert ask(Q.rational(x), Q.irrational(x)) is False
assert ask(Q.rational(x), Q.real(x)) is None
assert ask(Q.rational(x), Q.positive(x)) is None
assert ask(Q.rational(x), Q.negative(x)) is None
assert ask(Q.rational(x), Q.nonzero(x)) is None
assert ask(Q.rational(x), ~Q.algebraic(x)) is False
assert ask(Q.rational(2*x), Q.rational(x)) is True
assert ask(Q.rational(2*x), Q.integer(x)) is True
assert ask(Q.rational(2*x), Q.even(x)) is True
assert ask(Q.rational(2*x), Q.odd(x)) is True
assert ask(Q.rational(2*x), Q.irrational(x)) is False
assert ask(Q.rational(x/2), Q.rational(x)) is True
assert ask(Q.rational(x/2), Q.integer(x)) is True
assert ask(Q.rational(x/2), Q.even(x)) is True
assert ask(Q.rational(x/2), Q.odd(x)) is True
assert ask(Q.rational(x/2), Q.irrational(x)) is False
assert ask(Q.rational(1/x), Q.rational(x)) is True
assert ask(Q.rational(1/x), Q.integer(x)) is True
assert ask(Q.rational(1/x), Q.even(x)) is True
assert ask(Q.rational(1/x), Q.odd(x)) is True
assert ask(Q.rational(1/x), Q.irrational(x)) is False
assert ask(Q.rational(2/x), Q.rational(x)) is True
assert ask(Q.rational(2/x), Q.integer(x)) is True
assert ask(Q.rational(2/x), Q.even(x)) is True
assert ask(Q.rational(2/x), Q.odd(x)) is True
assert ask(Q.rational(2/x), Q.irrational(x)) is False
assert ask(Q.rational(x), ~Q.algebraic(x)) is False
# with multiple symbols
assert ask(Q.rational(x*y), Q.irrational(x) & Q.irrational(y)) is None
assert ask(Q.rational(y/x), Q.rational(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.integer(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.even(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.odd(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.irrational(x) & Q.rational(y)) is False
for f in [exp, sin, tan, asin, atan, cos]:
assert ask(Q.rational(f(7))) is False
assert ask(Q.rational(f(7, evaluate=False))) is False
assert ask(Q.rational(f(0, evaluate=False))) is True
assert ask(Q.rational(f(x)), Q.rational(x)) is None
assert ask(Q.rational(f(x)), Q.rational(x) & Q.nonzero(x)) is False
for g in [log, acos]:
assert ask(Q.rational(g(7))) is False
assert ask(Q.rational(g(7, evaluate=False))) is False
assert ask(Q.rational(g(1, evaluate=False))) is True
assert ask(Q.rational(g(x)), Q.rational(x)) is None
assert ask(Q.rational(g(x)), Q.rational(x) & Q.nonzero(x - 1)) is False
for h in [cot, acot]:
assert ask(Q.rational(h(7))) is False
assert ask(Q.rational(h(7, evaluate=False))) is False
assert ask(Q.rational(h(x)), Q.rational(x)) is False
def test_hermitian():
assert ask(Q.hermitian(x)) is None
assert ask(Q.hermitian(x), Q.antihermitian(x)) is False
assert ask(Q.hermitian(x), Q.imaginary(x)) is False
assert ask(Q.hermitian(x), Q.prime(x)) is True
assert ask(Q.hermitian(x), Q.real(x)) is True
assert ask(Q.hermitian(x + 1), Q.antihermitian(x)) is False
assert ask(Q.hermitian(x + 1), Q.complex(x)) is None
assert ask(Q.hermitian(x + 1), Q.hermitian(x)) is True
assert ask(Q.hermitian(x + 1), Q.imaginary(x)) is False
assert ask(Q.hermitian(x + 1), Q.real(x)) is True
assert ask(Q.hermitian(x + I), Q.antihermitian(x)) is None
assert ask(Q.hermitian(x + I), Q.complex(x)) is None
assert ask(Q.hermitian(x + I), Q.hermitian(x)) is False
assert ask(Q.hermitian(x + I), Q.imaginary(x)) is None
assert ask(Q.hermitian(x + I), Q.real(x)) is False
assert ask(
Q.hermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)) is None
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None
assert ask(
Q.hermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is False
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is None
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.real(y)) is False
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.hermitian(y)) is True
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.real(y)) is True
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is None
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.hermitian(x + y), Q.real(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.real(x) & Q.real(y)) is True
assert ask(Q.hermitian(I*x), Q.antihermitian(x)) is True
assert ask(Q.hermitian(I*x), Q.complex(x)) is None
assert ask(Q.hermitian(I*x), Q.hermitian(x)) is False
assert ask(Q.hermitian(I*x), Q.imaginary(x)) is True
assert ask(Q.hermitian(I*x), Q.real(x)) is False
assert ask(Q.hermitian(x*y), Q.hermitian(x) & Q.real(y)) is True
assert ask(
Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True
assert ask(Q.hermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is False
assert ask(Q.hermitian(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is None
assert ask(Q.hermitian(x + y + z),
Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is None
assert ask(Q.antihermitian(x)) is None
assert ask(Q.antihermitian(x), Q.real(x)) is False
assert ask(Q.antihermitian(x), Q.prime(x)) is False
assert ask(Q.antihermitian(x + 1), Q.antihermitian(x)) is False
assert ask(Q.antihermitian(x + 1), Q.complex(x)) is None
assert ask(Q.antihermitian(x + 1), Q.hermitian(x)) is None
assert ask(Q.antihermitian(x + 1), Q.imaginary(x)) is False
assert ask(Q.antihermitian(x + 1), Q.real(x)) is False
assert ask(Q.antihermitian(x + I), Q.antihermitian(x)) is True
assert ask(Q.antihermitian(x + I), Q.complex(x)) is None
assert ask(Q.antihermitian(x + I), Q.hermitian(x)) is False
assert ask(Q.antihermitian(x + I), Q.imaginary(x)) is True
assert ask(Q.antihermitian(x + I), Q.real(x)) is False
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)
) is True
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is False
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is True
assert ask(Q.antihermitian(x + y), Q.antihermitian(x) & Q.real(y)
) is False
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.hermitian(y)
) is None
assert ask(
Q.antihermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.real(y)) is None
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is True
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.antihermitian(x + y), Q.real(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.real(x) & Q.real(y)) is False
assert ask(Q.antihermitian(I*x), Q.real(x)) is True
assert ask(Q.antihermitian(I*x), Q.antihermitian(x)) is False
assert ask(Q.antihermitian(I*x), Q.complex(x)) is None
assert ask(Q.antihermitian(x*y), Q.antihermitian(x) & Q.real(y)) is True
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.real(z)) is False
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is None
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False
assert ask(Q.antihermitian(x + y + z),
Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is True
def test_imaginary():
assert ask(Q.imaginary(x)) is None
assert ask(Q.imaginary(x), Q.real(x)) is False
assert ask(Q.imaginary(x), Q.prime(x)) is False
assert ask(Q.imaginary(x + 1), Q.real(x)) is False
assert ask(Q.imaginary(x + 1), Q.imaginary(x)) is False
assert ask(Q.imaginary(x + I), Q.real(x)) is False
assert ask(Q.imaginary(x + I), Q.imaginary(x)) is True
assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.imaginary(y)) is True
assert ask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False
assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.imaginary(x + y), Q.complex(x) & Q.real(y)) is None
assert ask(
Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is False
assert ask(Q.imaginary(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is None
assert ask(Q.imaginary(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False
assert ask(Q.imaginary(I*x), Q.real(x)) is True
assert ask(Q.imaginary(I*x), Q.imaginary(x)) is False
assert ask(Q.imaginary(I*x), Q.complex(x)) is None
assert ask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True
assert ask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False
assert ask(Q.imaginary(I**x), Q.negative(x)) is None
assert ask(Q.imaginary(I**x), Q.positive(x)) is None
assert ask(Q.imaginary(I**x), Q.even(x)) is False
assert ask(Q.imaginary(I**x), Q.odd(x)) is True
assert ask(Q.imaginary(I**x), Q.imaginary(x)) is False
assert ask(Q.imaginary((2*I)**x), Q.imaginary(x)) is False
assert ask(Q.imaginary(x**0), Q.imaginary(x)) is False
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.integer(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(y) & Q.integer(x)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.odd(y)) is True
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.rational(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.even(y)) is False
assert ask(Q.imaginary(x**y), Q.real(x) & Q.integer(y)) is False
assert ask(Q.imaginary(x**y), Q.positive(x) & Q.real(y)) is False
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y) & ~Q.rational(y)) is False
assert ask(Q.imaginary(x**y), Q.integer(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & Q.integer(2*y)) is True
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & ~Q.integer(2*y)) is False
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & ~Q.integer(2*y)) is False
assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & Q.integer(2*y)) is None
# logarithm
assert ask(Q.imaginary(log(I))) is True
assert ask(Q.imaginary(log(2*I))) is False
assert ask(Q.imaginary(log(I + 1))) is False
assert ask(Q.imaginary(log(x)), Q.complex(x)) is None
assert ask(Q.imaginary(log(x)), Q.imaginary(x)) is None
assert ask(Q.imaginary(log(x)), Q.positive(x)) is False
assert ask(Q.imaginary(log(exp(x))), Q.complex(x)) is None
assert ask(Q.imaginary(log(exp(x))), Q.imaginary(x)) is None # zoo/I/a+I*b
assert ask(Q.imaginary(log(exp(I)))) is True
# exponential
assert ask(Q.imaginary(exp(x)**x), Q.imaginary(x)) is False
eq = Pow(exp(pi*I*x, evaluate=False), x, evaluate=False)
assert ask(Q.imaginary(eq), Q.even(x)) is False
eq = Pow(exp(pi*I*x/2, evaluate=False), x, evaluate=False)
assert ask(Q.imaginary(eq), Q.odd(x)) is True
assert ask(Q.imaginary(exp(3*I*pi*x)**x), Q.integer(x)) is False
assert ask(Q.imaginary(exp(2*pi*I, evaluate=False))) is False
assert ask(Q.imaginary(exp(pi*I/2, evaluate=False))) is True
# issue 7886
assert ask(Q.imaginary(Pow(x, Rational(1, 4))), Q.real(x) & Q.negative(x)) is False
def test_integer():
assert ask(Q.integer(x)) is None
assert ask(Q.integer(x), Q.integer(x)) is True
assert ask(Q.integer(x), ~Q.integer(x)) is False
assert ask(Q.integer(x), ~Q.real(x)) is False
assert ask(Q.integer(x), ~Q.positive(x)) is None
assert ask(Q.integer(x), Q.even(x) | Q.odd(x)) is True
assert ask(Q.integer(2*x), Q.integer(x)) is True
assert ask(Q.integer(2*x), Q.even(x)) is True
assert ask(Q.integer(2*x), Q.prime(x)) is True
assert ask(Q.integer(2*x), Q.rational(x)) is None
assert ask(Q.integer(2*x), Q.real(x)) is None
assert ask(Q.integer(sqrt(2)*x), Q.integer(x)) is False
assert ask(Q.integer(sqrt(2)*x), Q.irrational(x)) is None
assert ask(Q.integer(x/2), Q.odd(x)) is False
assert ask(Q.integer(x/2), Q.even(x)) is True
assert ask(Q.integer(x/3), Q.odd(x)) is None
assert ask(Q.integer(x/3), Q.even(x)) is None
def test_negative():
assert ask(Q.negative(x), Q.negative(x)) is True
assert ask(Q.negative(x), Q.positive(x)) is False
assert ask(Q.negative(x), ~Q.real(x)) is False
assert ask(Q.negative(x), Q.prime(x)) is False
assert ask(Q.negative(x), ~Q.prime(x)) is None
assert ask(Q.negative(-x), Q.positive(x)) is True
assert ask(Q.negative(-x), ~Q.positive(x)) is None
assert ask(Q.negative(-x), Q.negative(x)) is False
assert ask(Q.negative(-x), Q.positive(x)) is True
assert ask(Q.negative(x - 1), Q.negative(x)) is True
assert ask(Q.negative(x + y)) is None
assert ask(Q.negative(x + y), Q.negative(x)) is None
assert ask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True
assert ask(Q.negative(x + y), Q.negative(x) & Q.nonpositive(y)) is True
assert ask(Q.negative(2 + I)) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.negative(cos(I)**2 + sin(I)**2 - 1)) is None
assert ask(Q.negative(-I + I*(cos(2)**2 + sin(2)**2))) is None
assert ask(Q.negative(x**2)) is None
assert ask(Q.negative(x**2), Q.real(x)) is False
assert ask(Q.negative(x**1.4), Q.real(x)) is None
assert ask(Q.negative(x**I), Q.positive(x)) is None
assert ask(Q.negative(x*y)) is None
assert ask(Q.negative(x*y), Q.positive(x) & Q.positive(y)) is False
assert ask(Q.negative(x*y), Q.positive(x) & Q.negative(y)) is True
assert ask(Q.negative(x*y), Q.complex(x) & Q.complex(y)) is None
assert ask(Q.negative(x**y)) is None
assert ask(Q.negative(x**y), Q.negative(x) & Q.even(y)) is False
assert ask(Q.negative(x**y), Q.negative(x) & Q.odd(y)) is True
assert ask(Q.negative(x**y), Q.positive(x) & Q.integer(y)) is False
assert ask(Q.negative(Abs(x))) is False
def test_nonzero():
assert ask(Q.nonzero(x)) is None
assert ask(Q.nonzero(x), Q.real(x)) is None
assert ask(Q.nonzero(x), Q.positive(x)) is True
assert ask(Q.nonzero(x), Q.negative(x)) is True
assert ask(Q.nonzero(x), Q.negative(x) | Q.positive(x)) is True
assert ask(Q.nonzero(x + y)) is None
assert ask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True
assert ask(Q.nonzero(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.nonzero(x + y), Q.negative(x) & Q.negative(y)) is True
assert ask(Q.nonzero(2*x)) is None
assert ask(Q.nonzero(2*x), Q.positive(x)) is True
assert ask(Q.nonzero(2*x), Q.negative(x)) is True
assert ask(Q.nonzero(x*y), Q.nonzero(x)) is None
assert ask(Q.nonzero(x*y), Q.nonzero(x) & Q.nonzero(y)) is True
assert ask(Q.nonzero(x**y), Q.nonzero(x)) is True
assert ask(Q.nonzero(Abs(x))) is None
assert ask(Q.nonzero(Abs(x)), Q.nonzero(x)) is True
assert ask(Q.nonzero(log(exp(2*I)))) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.nonzero(cos(1)**2 + sin(1)**2 - 1)) is None
def test_zero():
assert ask(Q.zero(x)) is None
assert ask(Q.zero(x), Q.real(x)) is None
assert ask(Q.zero(x), Q.positive(x)) is False
assert ask(Q.zero(x), Q.negative(x)) is False
assert ask(Q.zero(x), Q.negative(x) | Q.positive(x)) is False
assert ask(Q.zero(x), Q.nonnegative(x) & Q.nonpositive(x)) is True
assert ask(Q.zero(x + y)) is None
assert ask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False
assert ask(Q.zero(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.zero(x + y), Q.negative(x) & Q.negative(y)) is False
assert ask(Q.zero(2*x)) is None
assert ask(Q.zero(2*x), Q.positive(x)) is False
assert ask(Q.zero(2*x), Q.negative(x)) is False
assert ask(Q.zero(x*y), Q.nonzero(x)) is None
assert ask(Q.zero(Abs(x))) is None
assert ask(Q.zero(Abs(x)), Q.zero(x)) is True
assert ask(Q.integer(x), Q.zero(x)) is True
assert ask(Q.even(x), Q.zero(x)) is True
assert ask(Q.odd(x), Q.zero(x)) is False
assert ask(Q.zero(x), Q.even(x)) is None
assert ask(Q.zero(x), Q.odd(x)) is False
assert ask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True
def test_odd_query():
assert ask(Q.odd(x)) is None
assert ask(Q.odd(x), Q.odd(x)) is True
assert ask(Q.odd(x), Q.integer(x)) is None
assert ask(Q.odd(x), ~Q.integer(x)) is False
assert ask(Q.odd(x), Q.rational(x)) is None
assert ask(Q.odd(x), Q.positive(x)) is None
assert ask(Q.odd(-x), Q.odd(x)) is True
assert ask(Q.odd(2*x)) is None
assert ask(Q.odd(2*x), Q.integer(x)) is False
assert ask(Q.odd(2*x), Q.odd(x)) is False
assert ask(Q.odd(2*x), Q.irrational(x)) is False
assert ask(Q.odd(2*x), ~Q.integer(x)) is None
assert ask(Q.odd(3*x), Q.integer(x)) is None
assert ask(Q.odd(x/3), Q.odd(x)) is None
assert ask(Q.odd(x/3), Q.even(x)) is None
assert ask(Q.odd(x + 1), Q.even(x)) is True
assert ask(Q.odd(x + 2), Q.even(x)) is False
assert ask(Q.odd(x + 2), Q.odd(x)) is True
assert ask(Q.odd(3 - x), Q.odd(x)) is False
assert ask(Q.odd(3 - x), Q.even(x)) is True
assert ask(Q.odd(3 + x), Q.odd(x)) is False
assert ask(Q.odd(3 + x), Q.even(x)) is True
assert ask(Q.odd(x + y), Q.odd(x) & Q.odd(y)) is False
assert ask(Q.odd(x + y), Q.odd(x) & Q.even(y)) is True
assert ask(Q.odd(x - y), Q.even(x) & Q.odd(y)) is True
assert ask(Q.odd(x - y), Q.odd(x) & Q.odd(y)) is False
assert ask(Q.odd(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is False
assert ask(Q.odd(x + y + z + t),
Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None
assert ask(Q.odd(2*x + 1), Q.integer(x)) is True
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.odd(y)) is True
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.even(y)) is False
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.odd(x*y), Q.odd(x) & Q.even(y)) is False
assert ask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True
assert ask(Q.odd(2*x*y), Q.rational(x) & Q.rational(x)) is None
assert ask(Q.odd(2*x*y), Q.irrational(x) & Q.irrational(x)) is None
assert ask(Q.odd(Abs(x)), Q.odd(x)) is True
assert ask(Q.odd((-1)**n), Q.integer(n)) is True
assert ask(Q.odd(k**2), Q.even(k)) is False
assert ask(Q.odd(n**2), Q.odd(n)) is True
assert ask(Q.odd(3**k), Q.even(k)) is None
assert ask(Q.odd(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is True
assert ask(Q.odd(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is False
assert ask(Q.odd(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is True
assert ask(Q.odd(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.odd(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.odd(k**x), Q.even(k)) is None
assert ask(Q.odd(n**x), Q.odd(n)) is None
assert ask(Q.odd(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.odd(x*x), Q.integer(x)) is None
assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.odd(y)) is False
assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.even(y)) is None
@XFAIL
def test_oddness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False
assert ask(Q.odd(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False
def test_oddness_in_ternary_integer_product_with_even():
assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None
def test_prime():
assert ask(Q.prime(x), Q.prime(x)) is True
assert ask(Q.prime(x), ~Q.prime(x)) is False
assert ask(Q.prime(x), Q.integer(x)) is None
assert ask(Q.prime(x), ~Q.integer(x)) is False
assert ask(Q.prime(2*x), Q.integer(x)) is None
assert ask(Q.prime(x*y)) is None
assert ask(Q.prime(x*y), Q.prime(x)) is None
assert ask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.prime(4*x), Q.integer(x)) is False
assert ask(Q.prime(4*x)) is None
assert ask(Q.prime(x**2), Q.integer(x)) is False
assert ask(Q.prime(x**2), Q.prime(x)) is False
assert ask(Q.prime(x**y), Q.integer(x) & Q.integer(y)) is False
def test_positive():
assert ask(Q.positive(x), Q.positive(x)) is True
assert ask(Q.positive(x), Q.negative(x)) is False
assert ask(Q.positive(x), Q.nonzero(x)) is None
assert ask(Q.positive(-x), Q.positive(x)) is False
assert ask(Q.positive(-x), Q.negative(x)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.nonnegative(y)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.positive(x + y), Q.positive(x) & Q.imaginary(y)) is False
assert ask(Q.positive(2*x), Q.positive(x)) is True
assumptions = Q.positive(x) & Q.negative(y) & Q.negative(z) & Q.positive(w)
assert ask(Q.positive(x*y*z)) is None
assert ask(Q.positive(x*y*z), assumptions) is True
assert ask(Q.positive(-x*y*z), assumptions) is False
assert ask(Q.positive(x**I), Q.positive(x)) is None
assert ask(Q.positive(x**2), Q.positive(x)) is True
assert ask(Q.positive(x**2), Q.negative(x)) is True
assert ask(Q.positive(x**3), Q.negative(x)) is False
assert ask(Q.positive(1/(1 + x**2)), Q.real(x)) is True
assert ask(Q.positive(2**I)) is False
assert ask(Q.positive(2 + I)) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.positive(cos(I)**2 + sin(I)**2 - 1)) is None
assert ask(Q.positive(-I + I*(cos(2)**2 + sin(2)**2))) is None
#exponential
assert ask(Q.positive(exp(x)), Q.real(x)) is True
assert ask(~Q.negative(exp(x)), Q.real(x)) is True
assert ask(Q.positive(x + exp(x)), Q.real(x)) is None
assert ask(Q.positive(exp(x)), Q.imaginary(x)) is None
assert ask(Q.positive(exp(2*pi*I, evaluate=False)), Q.imaginary(x)) is True
assert ask(Q.negative(exp(pi*I, evaluate=False)), Q.imaginary(x)) is True
assert ask(Q.positive(exp(x*pi*I)), Q.even(x)) is True
assert ask(Q.positive(exp(x*pi*I)), Q.odd(x)) is False
assert ask(Q.positive(exp(x*pi*I)), Q.real(x)) is None
# logarithm
assert ask(Q.positive(log(x)), Q.imaginary(x)) is False
assert ask(Q.positive(log(x)), Q.negative(x)) is False
assert ask(Q.positive(log(x)), Q.positive(x)) is None
assert ask(Q.positive(log(x + 2)), Q.positive(x)) is True
# factorial
assert ask(Q.positive(factorial(x)), Q.integer(x) & Q.positive(x))
assert ask(Q.positive(factorial(x)), Q.integer(x)) is None
#absolute value
assert ask(Q.positive(Abs(x))) is None # Abs(0) = 0
assert ask(Q.positive(Abs(x)), Q.positive(x)) is True
def test_nonpositive():
assert ask(Q.nonpositive(-1))
assert ask(Q.nonpositive(0))
assert ask(Q.nonpositive(1)) is False
assert ask(~Q.positive(x), Q.nonpositive(x))
assert ask(Q.nonpositive(x), Q.positive(x)) is False
assert ask(Q.nonpositive(sqrt(-1))) is False
assert ask(Q.nonpositive(x), Q.imaginary(x)) is False
def test_nonnegative():
assert ask(Q.nonnegative(-1)) is False
assert ask(Q.nonnegative(0))
assert ask(Q.nonnegative(1))
assert ask(~Q.negative(x), Q.nonnegative(x))
assert ask(Q.nonnegative(x), Q.negative(x)) is False
assert ask(Q.nonnegative(sqrt(-1))) is False
assert ask(Q.nonnegative(x), Q.imaginary(x)) is False
def test_real_basic():
assert ask(Q.real(x)) is None
assert ask(Q.real(x), Q.real(x)) is True
assert ask(Q.real(x), Q.nonzero(x)) is True
assert ask(Q.real(x), Q.positive(x)) is True
assert ask(Q.real(x), Q.negative(x)) is True
assert ask(Q.real(x), Q.integer(x)) is True
assert ask(Q.real(x), Q.even(x)) is True
assert ask(Q.real(x), Q.prime(x)) is True
assert ask(Q.real(x/sqrt(2)), Q.real(x)) is True
assert ask(Q.real(x/sqrt(-2)), Q.real(x)) is False
assert ask(Q.real(x + 1), Q.real(x)) is True
assert ask(Q.real(x + I), Q.real(x)) is False
assert ask(Q.real(x + I), Q.complex(x)) is None
assert ask(Q.real(2*x), Q.real(x)) is True
assert ask(Q.real(I*x), Q.real(x)) is False
assert ask(Q.real(I*x), Q.imaginary(x)) is True
assert ask(Q.real(I*x), Q.complex(x)) is None
def test_real_pow():
assert ask(Q.real(x**2), Q.real(x)) is True
assert ask(Q.real(sqrt(x)), Q.negative(x)) is False
assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) is None
assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True
assert ask(Q.real(x**y), Q.imaginary(x) & Q.imaginary(y)) is None # I**I or (2*I)**I
assert ask(Q.real(x**y), Q.imaginary(x) & Q.real(y)) is None # I**1 or I**0
assert ask(Q.real(x**y), Q.real(x) & Q.imaginary(y)) is None # could be exp(2*pi*I) or 2**I
assert ask(Q.real(x**0), Q.imaginary(x)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True
assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.rational(y)) is None
assert ask(Q.real(x**y), Q.imaginary(x) & Q.integer(y)) is None
assert ask(Q.real(x**y), Q.imaginary(x) & Q.odd(y)) is False
assert ask(Q.real(x**y), Q.imaginary(x) & Q.even(y)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.rational(y/z) & Q.even(z) & Q.positive(x)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.rational(y/z) & Q.even(z) & Q.negative(x)) is False
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.integer(y/z)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.positive(x)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.negative(x)) is False
assert ask(Q.real((-I)**i), Q.imaginary(i)) is True
assert ask(Q.real(I**i), Q.imaginary(i)) is True
assert ask(Q.real(i**i), Q.imaginary(i)) is None # i might be 2*I
assert ask(Q.real(x**i), Q.imaginary(i)) is None # x could be 0
assert ask(Q.real(x**(I*pi/log(x))), Q.real(x)) is True
def test_real_functions():
# trigonometric functions
assert ask(Q.real(sin(x))) is None
assert ask(Q.real(cos(x))) is None
assert ask(Q.real(sin(x)), Q.real(x)) is True
assert ask(Q.real(cos(x)), Q.real(x)) is True
# exponential function
assert ask(Q.real(exp(x))) is None
assert ask(Q.real(exp(x)), Q.real(x)) is True
assert ask(Q.real(x + exp(x)), Q.real(x)) is True
assert ask(Q.real(exp(2*pi*I, evaluate=False))) is True
assert ask(Q.real(exp(pi*I, evaluate=False))) is True
assert ask(Q.real(exp(pi*I/2, evaluate=False))) is False
# logarithm
assert ask(Q.real(log(I))) is False
assert ask(Q.real(log(2*I))) is False
assert ask(Q.real(log(I + 1))) is False
assert ask(Q.real(log(x)), Q.complex(x)) is None
assert ask(Q.real(log(x)), Q.imaginary(x)) is False
assert ask(Q.real(log(exp(x))), Q.imaginary(x)) is None # exp(2*pi*I) is 1, log(exp(pi*I)) is pi*I (disregarding periodicity)
assert ask(Q.real(log(exp(x))), Q.complex(x)) is None
eq = Pow(exp(2*pi*I*x, evaluate=False), x, evaluate=False)
assert ask(Q.real(eq), Q.integer(x)) is True
assert ask(Q.real(exp(x)**x), Q.imaginary(x)) is True
assert ask(Q.real(exp(x)**x), Q.complex(x)) is None
# Q.complexes
assert ask(Q.real(re(x))) is True
assert ask(Q.real(im(x))) is True
def test_matrix():
# hermitian
assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 - I, 3, I], [4, -I, 1]]))) == True
assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 + I, 3, I], [4, -I, 1]]))) == False
z = symbols('z', complex=True)
assert ask(Q.hermitian(Matrix([[2, 2 + I, z], [2 - I, 3, I], [4, -I, 1]]))) == None
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))))) == True
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, I, 0), (-5, 0, 11))))) == False
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, z, 0), (-5, 0, 11))))) == None
# antihermitian
A = Matrix([[0, -2 - I, 0], [2 - I, 0, -I], [0, -I, 0]])
B = Matrix([[-I, 2 + I, 0], [-2 + I, 0, 2 + I], [0, -2 + I, -I]])
assert ask(Q.antihermitian(A)) is True
assert ask(Q.antihermitian(B)) is True
assert ask(Q.antihermitian(A**2)) is False
C = (B**3)
C.simplify()
assert ask(Q.antihermitian(C)) is True
_A = Matrix([[0, -2 - I, 0], [z, 0, -I], [0, -I, 0]])
assert ask(Q.antihermitian(_A)) is None
def test_algebraic():
assert ask(Q.algebraic(x)) is None
assert ask(Q.algebraic(I)) is True
assert ask(Q.algebraic(2*I)) is True
assert ask(Q.algebraic(I/3)) is True
assert ask(Q.algebraic(sqrt(7))) is True
assert ask(Q.algebraic(2*sqrt(7))) is True
assert ask(Q.algebraic(sqrt(7)/3)) is True
assert ask(Q.algebraic(I*sqrt(3))) is True
assert ask(Q.algebraic(sqrt(1 + I*sqrt(3)))) is True
assert ask(Q.algebraic(1 + I*sqrt(3)**Rational(17, 31))) is True
assert ask(Q.algebraic(1 + I*sqrt(3)**(17/pi))) is False
for f in [exp, sin, tan, asin, atan, cos]:
assert ask(Q.algebraic(f(7))) is False
assert ask(Q.algebraic(f(7, evaluate=False))) is False
assert ask(Q.algebraic(f(0, evaluate=False))) is True
assert ask(Q.algebraic(f(x)), Q.algebraic(x)) is None
assert ask(Q.algebraic(f(x)), Q.algebraic(x) & Q.nonzero(x)) is False
for g in [log, acos]:
assert ask(Q.algebraic(g(7))) is False
assert ask(Q.algebraic(g(7, evaluate=False))) is False
assert ask(Q.algebraic(g(1, evaluate=False))) is True
assert ask(Q.algebraic(g(x)), Q.algebraic(x)) is None
assert ask(Q.algebraic(g(x)), Q.algebraic(x) & Q.nonzero(x - 1)) is False
for h in [cot, acot]:
assert ask(Q.algebraic(h(7))) is False
assert ask(Q.algebraic(h(7, evaluate=False))) is False
assert ask(Q.algebraic(h(x)), Q.algebraic(x)) is False
assert ask(Q.algebraic(sqrt(sin(7)))) is False
assert ask(Q.algebraic(sqrt(y + I*sqrt(7)))) is None
assert ask(Q.algebraic(2.47)) is True
assert ask(Q.algebraic(x), Q.transcendental(x)) is False
assert ask(Q.transcendental(x), Q.algebraic(x)) is False
def test_global():
"""Test ask with global assumptions"""
assert ask(Q.integer(x)) is None
global_assumptions.add(Q.integer(x))
assert ask(Q.integer(x)) is True
global_assumptions.clear()
assert ask(Q.integer(x)) is None
def test_custom_context():
"""Test ask with custom assumptions context"""
assert ask(Q.integer(x)) is None
local_context = AssumptionsContext()
local_context.add(Q.integer(x))
assert ask(Q.integer(x), context=local_context) is True
assert ask(Q.integer(x)) is None
def test_functions_in_assumptions():
assert ask(Q.negative(x), Q.real(x) >> Q.positive(x)) is False
assert ask(Q.negative(x), Equivalent(Q.real(x), Q.positive(x))) is False
assert ask(Q.negative(x), Xor(Q.real(x), Q.negative(x))) is False
def test_composite_ask():
assert ask(Q.negative(x) & Q.integer(x),
assumptions=Q.real(x) >> Q.positive(x)) is False
def test_composite_proposition():
assert ask(True) is True
assert ask(False) is False
assert ask(~Q.negative(x), Q.positive(x)) is True
assert ask(~Q.real(x), Q.commutative(x)) is None
assert ask(Q.negative(x) & Q.integer(x), Q.positive(x)) is False
assert ask(Q.negative(x) & Q.integer(x)) is None
assert ask(Q.real(x) | Q.integer(x), Q.positive(x)) is True
assert ask(Q.real(x) | Q.integer(x)) is None
assert ask(Q.real(x) >> Q.positive(x), Q.negative(x)) is False
assert ask(Implies(
Q.real(x), Q.positive(x), evaluate=False), Q.negative(x)) is False
assert ask(Implies(Q.real(x), Q.positive(x), evaluate=False)) is None
assert ask(Equivalent(Q.integer(x), Q.even(x)), Q.even(x)) is True
assert ask(Equivalent(Q.integer(x), Q.even(x))) is None
assert ask(Equivalent(Q.positive(x), Q.integer(x)), Q.integer(x)) is None
assert ask(Q.real(x) | Q.integer(x), Q.real(x) | Q.integer(x)) is True
def test_tautology():
assert ask(Q.real(x) | ~Q.real(x)) is True
assert ask(Q.real(x) & ~Q.real(x)) is False
def test_composite_assumptions():
assert ask(Q.real(x), Q.real(x) & Q.real(y)) is True
assert ask(Q.positive(x), Q.positive(x) | Q.positive(y)) is None
assert ask(Q.positive(x), Q.real(x) >> Q.positive(y)) is None
assert ask(Q.real(x), ~(Q.real(x) >> Q.real(y))) is True
def test_key_extensibility():
"""test that you can add keys to the ask system at runtime"""
# make sure the key is not defined
raises(AttributeError, lambda: ask(Q.my_key(x)))
# Old handler system
class MyAskHandler(AskHandler):
@staticmethod
def Symbol(expr, assumptions):
return True
try:
with warns_deprecated_sympy():
register_handler('my_key', MyAskHandler)
with warns_deprecated_sympy():
assert ask(Q.my_key(x)) is True
with warns_deprecated_sympy():
assert ask(Q.my_key(x + 1)) is None
finally:
with warns_deprecated_sympy():
remove_handler('my_key', MyAskHandler)
del Q.my_key
raises(AttributeError, lambda: ask(Q.my_key(x)))
# New handler system
class MyPredicate(Predicate):
pass
try:
Q.my_key = MyPredicate()
@Q.my_key.register(Symbol)
def _(expr, assumptions):
return True
assert ask(Q.my_key(x)) is True
assert ask(Q.my_key(x+1)) is None
finally:
del Q.my_key
raises(AttributeError, lambda: ask(Q.my_key(x)))
def test_type_extensibility():
"""test that new types can be added to the ask system at runtime
"""
from sympy.core import Basic
class MyType(Basic):
pass
@Q.prime.register(MyType)
def _(expr, assumptions):
return True
assert ask(Q.prime(MyType())) is True
def test_single_fact_lookup():
known_facts = And(Implies(Q.integer, Q.rational),
Implies(Q.rational, Q.real),
Implies(Q.real, Q.complex))
known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex}
known_facts_cnf = to_cnf(known_facts)
mapping = single_fact_lookup(known_facts_keys, known_facts_cnf)
assert mapping[Q.rational] == {Q.real, Q.rational, Q.complex}
def test_compute_known_facts():
known_facts = And(Implies(Q.integer, Q.rational),
Implies(Q.rational, Q.real),
Implies(Q.real, Q.complex))
known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex}
compute_known_facts(known_facts, known_facts_keys)
@slow
def test_known_facts_consistent():
""""Test that ask_generated.py is up-to-date"""
from sympy.assumptions.ask import get_known_facts, get_known_facts_keys
from os.path import abspath, dirname, join
filename = join(dirname(dirname(abspath(__file__))), 'ask_generated.py')
with open(filename) as f:
assert f.read() == \
compute_known_facts(get_known_facts(), get_known_facts_keys())
def test_Add_queries():
assert ask(Q.prime(12345678901234567890 + (cos(1)**2 + sin(1)**2))) is True
assert ask(Q.even(Add(S(2), S(2), evaluate=0))) is True
assert ask(Q.prime(Add(S(2), S(2), evaluate=0))) is False
assert ask(Q.integer(Add(S(2), S(2), evaluate=0))) is True
def test_positive_assuming():
with assuming(Q.positive(x + 1)):
assert not ask(Q.positive(x))
def test_issue_5421():
raises(TypeError, lambda: ask(pi/log(x), Q.real))
def test_issue_3906():
raises(TypeError, lambda: ask(Q.positive))
def test_issue_5833():
assert ask(Q.positive(log(x)**2), Q.positive(x)) is None
assert ask(~Q.negative(log(x)**2), Q.positive(x)) is True
def test_issue_6732():
raises(ValueError, lambda: ask(Q.positive(x), Q.positive(x) & Q.negative(x)))
raises(ValueError, lambda: ask(Q.negative(x), Q.positive(x) & Q.negative(x)))
def test_issue_7246():
assert ask(Q.positive(atan(p)), Q.positive(p)) is True
assert ask(Q.positive(atan(p)), Q.negative(p)) is False
assert ask(Q.positive(atan(p)), Q.zero(p)) is False
assert ask(Q.positive(atan(x))) is None
assert ask(Q.positive(asin(p)), Q.positive(p)) is None
assert ask(Q.positive(asin(p)), Q.zero(p)) is None
assert ask(Q.positive(asin(Rational(1, 7)))) is True
assert ask(Q.positive(asin(x)), Q.positive(x) & Q.nonpositive(x - 1)) is True
assert ask(Q.positive(asin(x)), Q.negative(x) & Q.nonnegative(x + 1)) is False
assert ask(Q.positive(acos(p)), Q.positive(p)) is None
assert ask(Q.positive(acos(Rational(1, 7)))) is True
assert ask(Q.positive(acos(x)), Q.nonnegative(x + 1) & Q.nonpositive(x - 1)) is True
assert ask(Q.positive(acos(x)), Q.nonnegative(x - 1)) is None
assert ask(Q.positive(acot(x)), Q.positive(x)) is True
assert ask(Q.positive(acot(x)), Q.real(x)) is True
assert ask(Q.positive(acot(x)), Q.imaginary(x)) is False
assert ask(Q.positive(acot(x))) is None
@XFAIL
def test_issue_7246_failing():
#Move this test to test_issue_7246 once
#the new assumptions module is improved.
assert ask(Q.positive(acos(x)), Q.zero(x)) is True
def test_check_old_assumption():
x = symbols('x', real=True)
assert ask(Q.real(x)) is True
assert ask(Q.imaginary(x)) is False
assert ask(Q.complex(x)) is True
x = symbols('x', imaginary=True)
assert ask(Q.real(x)) is False
assert ask(Q.imaginary(x)) is True
assert ask(Q.complex(x)) is True
x = symbols('x', complex=True)
assert ask(Q.real(x)) is None
assert ask(Q.complex(x)) is True
x = symbols('x', positive=True, finite=True)
assert ask(Q.positive(x)) is True
assert ask(Q.negative(x)) is False
assert ask(Q.real(x)) is True
x = symbols('x', commutative=False)
assert ask(Q.commutative(x)) is False
x = symbols('x', negative=True)
assert ask(Q.positive(x)) is False
assert ask(Q.negative(x)) is True
x = symbols('x', nonnegative=True)
assert ask(Q.negative(x)) is False
assert ask(Q.positive(x)) is None
assert ask(Q.zero(x)) is None
x = symbols('x', finite=True)
assert ask(Q.finite(x)) is True
x = symbols('x', prime=True)
assert ask(Q.prime(x)) is True
assert ask(Q.composite(x)) is False
x = symbols('x', composite=True)
assert ask(Q.prime(x)) is False
assert ask(Q.composite(x)) is True
x = symbols('x', even=True)
assert ask(Q.even(x)) is True
assert ask(Q.odd(x)) is False
x = symbols('x', odd=True)
assert ask(Q.even(x)) is False
assert ask(Q.odd(x)) is True
x = symbols('x', nonzero=True)
assert ask(Q.nonzero(x)) is True
assert ask(Q.zero(x)) is False
x = symbols('x', zero=True)
assert ask(Q.zero(x)) is True
x = symbols('x', integer=True)
assert ask(Q.integer(x)) is True
x = symbols('x', rational=True)
assert ask(Q.rational(x)) is True
assert ask(Q.irrational(x)) is False
x = symbols('x', irrational=True)
assert ask(Q.irrational(x)) is True
assert ask(Q.rational(x)) is False
def test_issue_9636():
assert ask(Q.integer(1.0)) is False
assert ask(Q.prime(3.0)) is False
assert ask(Q.composite(4.0)) is False
assert ask(Q.even(2.0)) is False
assert ask(Q.odd(3.0)) is False
def test_autosimp_used_to_fail():
# See issue #9807
assert ask(Q.imaginary(0**I)) is False
assert ask(Q.imaginary(0**(-I))) is False
assert ask(Q.real(0**I)) is False
assert ask(Q.real(0**(-I))) is False
def test_custom_AskHandler():
from sympy.logic.boolalg import conjuncts
# Old handler system
class MersenneHandler(AskHandler):
@staticmethod
def Integer(expr, assumptions):
from sympy import log
if ask(Q.integer(log(expr + 1, 2))):
return True
@staticmethod
def Symbol(expr, assumptions):
if expr in conjuncts(assumptions):
return True
try:
with warns_deprecated_sympy():
register_handler('mersenne', MersenneHandler)
n = Symbol('n', integer=True)
with warns_deprecated_sympy():
assert ask(Q.mersenne(7))
with warns_deprecated_sympy():
assert ask(Q.mersenne(n), Q.mersenne(n))
finally:
del Q.mersenne
# New handler system
class MersennePredicate(Predicate):
pass
try:
Q.mersenne = MersennePredicate()
@Q.mersenne.register(Integer)
def _(expr, assumptions):
from sympy import log
if ask(Q.integer(log(expr + 1, 2))):
return True
@Q.mersenne.register(Symbol)
def _(expr, assumptions):
if expr in conjuncts(assumptions):
return True
assert ask(Q.mersenne(7))
assert ask(Q.mersenne(n), Q.mersenne(n))
finally:
del Q.mersenne
def test_polyadic_predicate():
class SexyPredicate(Predicate):
pass
try:
Q.sexyprime = SexyPredicate()
@Q.sexyprime.register(Integer, Integer)
def _(int1, int2, assumptions):
args = sorted([int1, int2])
if not all(ask(Q.prime(a), assumptions) for a in args):
return False
return args[1] - args[0] == 6
@Q.sexyprime.register(Integer, Integer, Integer)
def _(int1, int2, int3, assumptions):
args = sorted([int1, int2, int3])
if not all(ask(Q.prime(a), assumptions) for a in args):
return False
return args[2] - args[1] == 6 and args[1] - args[0] == 6
assert ask(Q.sexyprime(5, 11))
assert ask(Q.sexyprime(7, 13, 19))
finally:
del Q.sexyprime
def test_Predicate_handler_is_unique():
# Undefined predicate does not have a handler
assert Predicate('mypredicate').handler is None
# Handler of defined predicate is unique to the class
class MyPredicate(Predicate):
pass
mp1 = MyPredicate('mp1')
mp2 = MyPredicate('mp2')
assert mp1.handler is mp2.handler
|
bfccc74308c7a6b0c90aee0b0d7934f8df8a2876ff837c33ebd55051e4cfd495 | """
This module implements some special functions that commonly appear in
combinatorial contexts (e.g. in power series); in particular,
sequences of rational numbers such as Bernoulli and Fibonacci numbers.
Factorials, binomial coefficients and related functions are located in
the separate 'factorials' module.
"""
from typing import Callable, Dict
from sympy.core import S, Symbol, Rational, Integer, Add, Dummy
from sympy.core.cache import cacheit
from sympy.core.compatibility import as_int, SYMPY_INTS
from sympy.core.function import Function, expand_mul
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import E, pi
from sympy.core.relational import LessThan, StrictGreaterThan
from sympy.functions.combinatorial.factorials import binomial, factorial
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.trigonometric import sin, cos, cot
from sympy.ntheory import isprime
from sympy.ntheory.primetest import is_square
from sympy.utilities.memoization import recurrence_memo
from mpmath import bernfrac, workprec
from mpmath.libmp import ifib as _ifib
def _product(a, b):
p = 1
for k in range(a, b + 1):
p *= k
return p
# Dummy symbol used for computing polynomial sequences
_sym = Symbol('x')
#----------------------------------------------------------------------------#
# #
# Carmichael numbers #
# #
#----------------------------------------------------------------------------#
class carmichael(Function):
"""
Carmichael Numbers:
Certain cryptographic algorithms make use of big prime numbers.
However, checking whether a big number is prime is not so easy.
Randomized prime number checking tests exist that offer a high degree of confidence of
accurate determination at low cost, such as the Fermat test.
Let 'a' be a random number between 2 and n - 1, where n is the number whose primality we are testing.
Then, n is probably prime if it satisfies the modular arithmetic congruence relation :
a^(n-1) = 1(mod n).
(where mod refers to the modulo operation)
If a number passes the Fermat test several times, then it is prime with a
high probability.
Unfortunately, certain composite numbers (non-primes) still pass the Fermat test
with every number smaller than themselves.
These numbers are called Carmichael numbers.
A Carmichael number will pass a Fermat primality test to every base b relatively prime to the number,
even though it is not actually prime. This makes tests based on Fermat's Little Theorem less effective than
strong probable prime tests such as the Baillie-PSW primality test and the Miller-Rabin primality test.
mr functions given in sympy/sympy/ntheory/primetest.py will produce wrong results for each and every
carmichael number.
Examples
========
>>> from sympy import carmichael
>>> carmichael.find_first_n_carmichaels(5)
[561, 1105, 1729, 2465, 2821]
>>> carmichael.is_prime(2465)
False
>>> carmichael.is_prime(1729)
False
>>> carmichael.find_carmichael_numbers_in_range(0, 562)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,1000)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,2000)
[561, 1105, 1729]
References
==========
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
.. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
.. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
"""
@staticmethod
def is_perfect_square(n):
return is_square(n)
@staticmethod
def divides(p, n):
return n % p == 0
@staticmethod
def is_prime(n):
return isprime(n)
@staticmethod
def is_carmichael(n):
if n >= 0:
if (n == 1) or (carmichael.is_prime(n)) or (n % 2 == 0):
return False
divisors = list([1, n])
# get divisors
for i in range(3, n // 2 + 1, 2):
if n % i == 0:
divisors.append(i)
for i in divisors:
if carmichael.is_perfect_square(i) and i != 1:
return False
if carmichael.is_prime(i):
if not carmichael.divides(i - 1, n - 1):
return False
return True
else:
raise ValueError('The provided number must be greater than or equal to 0')
@staticmethod
def find_carmichael_numbers_in_range(x, y):
if 0 <= x <= y:
if x % 2 == 0:
return list([i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)])
else:
return list([i for i in range(x, y, 2) if carmichael.is_carmichael(i)])
else:
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
@staticmethod
def find_first_n_carmichaels(n):
i = 1
carmichaels = list()
while len(carmichaels) < n:
if carmichael.is_carmichael(i):
carmichaels.append(i)
i += 2
return carmichaels
#----------------------------------------------------------------------------#
# #
# Fibonacci numbers #
# #
#----------------------------------------------------------------------------#
class fibonacci(Function):
r"""
Fibonacci numbers / Fibonacci polynomials
The Fibonacci numbers are the integer sequence defined by the
initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
relation `F_n = F_{n-1} + F_{n-2}`. This definition
extended to arbitrary real and complex arguments using
the formula
.. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
The Fibonacci polynomials are defined by `F_1(x) = 1`,
`F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
For all positive integers `n`, `F_n(1) = F_n`.
* ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
* ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
Examples
========
>>> from sympy import fibonacci, Symbol
>>> [fibonacci(x) for x in range(11)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fibonacci(5, Symbol('t'))
t**4 + 3*t**2 + 1
See Also
========
bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Fibonacci_number
.. [2] http://mathworld.wolfram.com/FibonacciNumber.html
"""
@staticmethod
def _fib(n):
return _ifib(n)
@staticmethod
@recurrence_memo([None, S.One, _sym])
def _fibpoly(n, prev):
return (prev[-2] + _sym*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
if sym is None:
n = int(n)
if n < 0:
return S.NegativeOne**(n + 1) * fibonacci(-n)
else:
return Integer(cls._fib(n))
else:
if n < 1:
raise ValueError("Fibonacci polynomials are defined "
"only for positive integer indices.")
return cls._fibpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
#----------------------------------------------------------------------------#
# #
# Lucas numbers #
# #
#----------------------------------------------------------------------------#
class lucas(Function):
"""
Lucas numbers
Lucas numbers satisfy a recurrence relation similar to that of
the Fibonacci sequence, in which each term is the sum of the
preceding two. They are generated by choosing the initial
values `L_0 = 2` and `L_1 = 1`.
* ``lucas(n)`` gives the `n^{th}` Lucas number
Examples
========
>>> from sympy import lucas
>>> [lucas(x) for x in range(11)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Lucas_number
.. [2] http://mathworld.wolfram.com/LucasNumber.html
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
return fibonacci(n + 1) + fibonacci(n - 1)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
#----------------------------------------------------------------------------#
# #
# Tribonacci numbers #
# #
#----------------------------------------------------------------------------#
class tribonacci(Function):
r"""
Tribonacci numbers / Tribonacci polynomials
The Tribonacci numbers are the integer sequence defined by the
initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
`T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
* ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
* ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
Examples
========
>>> from sympy import tribonacci, Symbol
>>> [tribonacci(x) for x in range(11)]
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
>>> tribonacci(5, Symbol('t'))
t**8 + 3*t**5 + 3*t**2
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
.. [2] http://mathworld.wolfram.com/TribonacciNumber.html
.. [3] https://oeis.org/A000073
"""
@staticmethod
@recurrence_memo([S.Zero, S.One, S.One])
def _trib(n, prev):
return (prev[-3] + prev[-2] + prev[-1])
@staticmethod
@recurrence_memo([S.Zero, S.One, _sym**2])
def _tribpoly(n, prev):
return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
n = int(n)
if n < 0:
raise ValueError("Tribonacci polynomials are defined "
"only for non-negative integer indices.")
if sym is None:
return Integer(cls._trib(n))
else:
return cls._tribpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
Tn = (a**(n + 1)/((a - b)*(a - c))
+ b**(n + 1)/((b - a)*(b - c))
+ c**(n + 1)/((c - a)*(c - b)))
return Tn
def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
b = cbrt(586 + 102*sqrt(33))
Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
return floor(Tn + S.Half)
#----------------------------------------------------------------------------#
# #
# Bernoulli numbers #
# #
#----------------------------------------------------------------------------#
class bernoulli(Function):
r"""
Bernoulli numbers / Bernoulli polynomials
The Bernoulli numbers are a sequence of rational numbers
defined by `B_0 = 1` and the recursive relation (`n > 0`):
.. math :: 0 = \sum_{k=0}^n \binom{n+1}{k} B_k
They are also commonly defined by their exponential generating
function, which is `\frac{x}{e^x - 1}`. For odd indices > 1, the
Bernoulli numbers are zero.
The Bernoulli polynomials satisfy the analogous formula:
.. math :: B_n(x) = \sum_{k=0}^n \binom{n}{k} B_k x^{n-k}
Bernoulli numbers and Bernoulli polynomials are related as
`B_n(0) = B_n`.
We compute Bernoulli numbers using Ramanujan's formula:
.. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
where:
.. math :: A(n) = \begin{cases} \frac{n+3}{3} &
n \equiv 0\ \text{or}\ 2 \pmod{6} \\
-\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
and:
.. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
This formula is similar to the sum given in the definition, but
cuts 2/3 of the terms. For Bernoulli polynomials, we use the
formula in the definition.
* ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
* ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
Examples
========
>>> from sympy import bernoulli
>>> [bernoulli(n) for n in range(11)]
[1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> bernoulli(1000001)
0
See Also
========
bell, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_number
.. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
.. [3] http://mathworld.wolfram.com/BernoulliNumber.html
.. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html
"""
# Calculates B_n for positive even n
@staticmethod
def _calc_bernoulli(n):
s = 0
a = int(binomial(n + 3, n - 6))
for j in range(1, n//6 + 1):
s += a * bernoulli(n - 6*j)
# Avoid computing each binomial coefficient from scratch
a *= _product(n - 6 - 6*j + 1, n - 6*j)
a //= _product(6*j + 4, 6*j + 9)
if n % 6 == 4:
s = -Rational(n + 3, 6) - s
else:
s = Rational(n + 3, 3) - s
return s / binomial(n + 3, n)
# We implement a specialized memoization scheme to handle each
# case modulo 6 separately
_cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
_highest = {0: 0, 2: 2, 4: 4}
@classmethod
def eval(cls, n, sym=None):
if n.is_Number:
if n.is_Integer and n.is_nonnegative:
if n.is_zero:
return S.One
elif n is S.One:
if sym is None:
return Rational(-1, 2)
else:
return sym - S.Half
# Bernoulli numbers
elif sym is None:
if n.is_odd:
return S.Zero
n = int(n)
# Use mpmath for enormous Bernoulli numbers
if n > 500:
p, q = bernfrac(n)
return Rational(int(p), int(q))
case = n % 6
highest_cached = cls._highest[case]
if n <= highest_cached:
return cls._cache[n]
# To avoid excessive recursion when, say, bernoulli(1000) is
# requested, calculate and cache the entire sequence ... B_988,
# B_994, B_1000 in increasing order
for i in range(highest_cached + 6, n + 6, 6):
b = cls._calc_bernoulli(i)
cls._cache[i] = b
cls._highest[case] = i
return b
# Bernoulli polynomials
else:
n, result = int(n), []
for k in range(n + 1):
result.append(binomial(n, k)*cls(k)*sym**(n - k))
return Add(*result)
else:
raise ValueError("Bernoulli numbers are defined only"
" for nonnegative integer indices.")
if sym is None:
if n.is_odd and (n - 1).is_positive:
return S.Zero
#----------------------------------------------------------------------------#
# #
# Bell numbers #
# #
#----------------------------------------------------------------------------#
class bell(Function):
r"""
Bell numbers / Bell polynomials
The Bell numbers satisfy `B_0 = 1` and
.. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
They are also given by:
.. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
The Bell polynomials are given by `B_0(x) = 1` and
.. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
The second kind of Bell polynomials (are sometimes called "partial" Bell
polynomials or incomplete Bell polynomials) are defined as
.. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
\left(\frac{x_1}{1!} \right)^{j_1}
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
* ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
* ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
Notes
=====
Not to be confused with Bernoulli numbers and Bernoulli polynomials,
which use the same notation.
Examples
========
>>> from sympy import bell, Symbol, symbols
>>> [bell(n) for n in range(11)]
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
>>> bell(30)
846749014511809332450147
>>> bell(4, Symbol('t'))
t**4 + 6*t**3 + 7*t**2 + t
>>> bell(6, 2, symbols('x:6')[1:])
6*x1*x5 + 15*x2*x4 + 10*x3**2
See Also
========
bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Bell_number
.. [2] http://mathworld.wolfram.com/BellNumber.html
.. [3] http://mathworld.wolfram.com/BellPolynomial.html
"""
@staticmethod
@recurrence_memo([1, 1])
def _bell(n, prev):
s = 1
a = 1
for k in range(1, n):
a = a * (n - k) // k
s += a * prev[k]
return s
@staticmethod
@recurrence_memo([S.One, _sym])
def _bell_poly(n, prev):
s = 1
a = 1
for k in range(2, n + 1):
a = a * (n - k + 1) // (k - 1)
s += a * prev[k - 1]
return expand_mul(_sym * s)
@staticmethod
def _bell_incomplete_poly(n, k, symbols):
r"""
The second kind of Bell polynomials (incomplete Bell polynomials).
Calculated by recurrence formula:
.. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
\sum_{m=1}^{n-k+1}
\x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
where
`B_{0,0} = 1;`
`B_{n,0} = 0; for n \ge 1`
`B_{0,k} = 0; for k \ge 1`
"""
if (n == 0) and (k == 0):
return S.One
elif (n == 0) or (k == 0):
return S.Zero
s = S.Zero
a = S.One
for m in range(1, n - k + 2):
s += a * bell._bell_incomplete_poly(
n - m, k - 1, symbols) * symbols[m - 1]
a = a * (n - m) / m
return expand_mul(s)
@classmethod
def eval(cls, n, k_sym=None, symbols=None):
if n is S.Infinity:
if k_sym is None:
return S.Infinity
else:
raise ValueError("Bell polynomial is not defined")
if n.is_negative or n.is_integer is False:
raise ValueError("a non-negative integer expected")
if n.is_Integer and n.is_nonnegative:
if k_sym is None:
return Integer(cls._bell(int(n)))
elif symbols is None:
return cls._bell_poly(int(n)).subs(_sym, k_sym)
else:
r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
return r
def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
from sympy import Sum
if (k_sym is not None) or (symbols is not None):
return self
# Dobinski's formula
if not n.is_nonnegative:
return self
k = Dummy('k', integer=True, nonnegative=True)
return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
#----------------------------------------------------------------------------#
# #
# Harmonic numbers #
# #
#----------------------------------------------------------------------------#
class harmonic(Function):
r"""
Harmonic numbers
The nth harmonic number is given by `\operatorname{H}_{n} =
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
More generally:
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
the Riemann zeta function.
* ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
* ``harmonic(n, m)`` gives the nth generalized harmonic number
of order `m`, `\operatorname{H}_{n,m}`, where
``harmonic(n) == harmonic(n, 1)``
Examples
========
>>> from sympy import harmonic, oo
>>> [harmonic(n) for n in range(6)]
[0, 1, 3/2, 11/6, 25/12, 137/60]
>>> [harmonic(n, 2) for n in range(6)]
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
>>> harmonic(oo, 2)
pi**2/6
>>> from sympy import Symbol, Sum
>>> n = Symbol("n")
>>> harmonic(n).rewrite(Sum)
Sum(1/_k, (_k, 1, n))
We can evaluate harmonic numbers for all integral and positive
rational arguments:
>>> from sympy import S, expand_func, simplify
>>> harmonic(8)
761/280
>>> harmonic(11)
83711/27720
>>> H = harmonic(1/S(3))
>>> H
harmonic(1/3)
>>> He = expand_func(H)
>>> He
-log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
+ 3*Sum(1/(3*_k + 1), (_k, 0, 0))
>>> He.doit()
-log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
>>> H = harmonic(25/S(7))
>>> He = simplify(expand_func(H).doit())
>>> He
log(sin(pi/7)**(-2*cos(pi/7))*sin(2*pi/7)**(2*cos(16*pi/7))*cos(pi/14)**(-2*sin(pi/14))/14)
+ pi*tan(pi/14)/2 + 30247/9900
>>> He.n(40)
1.983697455232980674869851942390639915940
>>> harmonic(25/S(7)).n(40)
1.983697455232980674869851942390639915940
We can rewrite harmonic numbers in terms of polygamma functions:
>>> from sympy import digamma, polygamma
>>> m = Symbol("m")
>>> harmonic(n).rewrite(digamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n).rewrite(polygamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n,3).rewrite(polygamma)
polygamma(2, n + 1)/2 - polygamma(2, 1)/2
>>> harmonic(n,m).rewrite(polygamma)
(-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)
Integer offsets in the argument can be pulled out:
>>> from sympy import expand_func
>>> expand_func(harmonic(n+4))
harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
>>> expand_func(harmonic(n-4))
harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
Some limits can be computed as well:
>>> from sympy import limit, oo
>>> limit(harmonic(n), n, oo)
oo
>>> limit(harmonic(n, 2), n, oo)
pi**2/6
>>> limit(harmonic(n, 3), n, oo)
-polygamma(2, 1)/2
However we can not compute the general relation yet:
>>> limit(harmonic(n, m), n, oo)
harmonic(oo, m)
which equals ``zeta(m)`` for ``m > 1``.
See Also
========
bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Harmonic_number
.. [2] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
.. [3] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
"""
# Generate one memoized Harmonic number-generating function for each
# order and store it in a dictionary
_functions = {} # type: Dict[Integer, Callable[[int], Rational]]
@classmethod
def eval(cls, n, m=None):
from sympy import zeta
if m is S.One:
return cls(n)
if m is None:
m = S.One
if m.is_zero:
return n
if n is S.Infinity and m.is_Number:
# TODO: Fix for symbolic values of m
if m.is_negative:
return S.NaN
elif LessThan(m, S.One):
return S.Infinity
elif StrictGreaterThan(m, S.One):
return zeta(m)
else:
return cls
if n == 0:
return S.Zero
if n.is_Integer and n.is_nonnegative and m.is_Integer:
if not m in cls._functions:
@recurrence_memo([0])
def f(n, prev):
return prev[-1] + S.One / n**m
cls._functions[m] = f
return cls._functions[m](int(n))
def _eval_rewrite_as_polygamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return S.NegativeOne**m/factorial(m - 1) * (polygamma(m - 1, 1) - polygamma(m - 1, n + 1))
def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
from sympy import Sum
k = Dummy("k", integer=True)
if m is None:
m = S.One
return Sum(k**(-m), (k, 1, n))
def _eval_expand_func(self, **hints):
from sympy import Sum
n = self.args[0]
m = self.args[1] if len(self.args) == 2 else 1
if m == S.One:
if n.is_Add:
off = n.args[0]
nnew = n - off
if off.is_Integer and off.is_positive:
result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
return Add(*result)
elif off.is_Integer and off.is_negative:
result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
return Add(*result)
if n.is_Rational:
# Expansions for harmonic numbers at general rational arguments (u + p/q)
# Split n as u + p/q with p < q
p, q = n.as_numer_denom()
u = p // q
p = p - u * q
if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
k = Dummy("k")
t1 = q * Sum(1 / (q * k + p), (k, 0, u))
t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
log(sin((pi * k) / S(q))),
(k, 1, floor((q - 1) / S(2))))
t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
return t1 + t2 - t3
return self
def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
from sympy import polygamma
return self.rewrite(polygamma).rewrite("tractable", deep=True)
def _eval_evalf(self, prec):
from sympy import polygamma
if all(i.is_number for i in self.args):
return self.rewrite(polygamma)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Euler numbers #
# #
#----------------------------------------------------------------------------#
class euler(Function):
r"""
Euler numbers / Euler polynomials
The Euler numbers are given by:
.. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
\frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
.. math:: E_{2n+1} = 0
Euler numbers and Euler polynomials are related by
.. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
We compute symbolic Euler polynomials using [5]_
.. math:: E_n(x) = \sum_{k=0}^n \binom{n}{k} \frac{E_k}{2^k}
\left(x - \frac{1}{2}\right)^{n-k}.
However, numerical evaluation of the Euler polynomial is computed
more efficiently (and more accurately) using the mpmath library.
* ``euler(n)`` gives the `n^{th}` Euler number, `E_n`.
* ``euler(n, x)`` gives the `n^{th}` Euler polynomial, `E_n(x)`.
Examples
========
>>> from sympy import Symbol, S
>>> from sympy.functions import euler
>>> [euler(n) for n in range(10)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
>>> n = Symbol("n")
>>> euler(n + 2*n)
euler(3*n)
>>> x = Symbol("x")
>>> euler(n, x)
euler(n, x)
>>> euler(0, x)
1
>>> euler(1, x)
x - 1/2
>>> euler(2, x)
x**2 - x
>>> euler(3, x)
x**3 - 3*x**2/2 + 1/4
>>> euler(4, x)
x**4 - 2*x**3 + x
>>> euler(12, S.Half)
2702765/4096
>>> euler(12)
2702765
See Also
========
bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler_numbers
.. [2] http://mathworld.wolfram.com/EulerNumber.html
.. [3] https://en.wikipedia.org/wiki/Alternating_permutation
.. [4] http://mathworld.wolfram.com/AlternatingPermutation.html
.. [5] http://dlmf.nist.gov/24.2#ii
"""
@classmethod
def eval(cls, m, sym=None):
if m.is_Number:
if m.is_Integer and m.is_nonnegative:
# Euler numbers
if sym is None:
if m.is_odd:
return S.Zero
from mpmath import mp
m = m._to_mpmath(mp.prec)
res = mp.eulernum(m, exact=True)
return Integer(res)
# Euler polynomial
else:
from sympy.core.evalf import pure_complex
reim = pure_complex(sym, or_real=True)
# Evaluate polynomial numerically using mpmath
if reim and all(a.is_Float or a.is_Integer for a in reim) \
and any(a.is_Float for a in reim):
from mpmath import mp
from sympy import Expr
m = int(m)
# XXX ComplexFloat (#12192) would be nice here, above
prec = min([a._prec for a in reim if a.is_Float])
with workprec(prec):
res = mp.eulerpoly(m, sym)
return Expr._from_mpmath(res, prec)
# Construct polynomial symbolically from definition
m, result = int(m), []
for k in range(m + 1):
result.append(binomial(m, k)*cls(k)/(2**k)*(sym - S.Half)**(m - k))
return Add(*result).expand()
else:
raise ValueError("Euler numbers are defined only"
" for nonnegative integer indices.")
if sym is None:
if m.is_odd and m.is_positive:
return S.Zero
def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
from sympy import Sum
if x is None and n.is_even:
k = Dummy("k", integer=True)
j = Dummy("j", integer=True)
n = n / 2
Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * ((-1)**j * (k - 2*j)**(2*n + 1)) /
(2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
return Em
if x:
k = Dummy("k", integer=True)
return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
def _eval_evalf(self, prec):
m, x = (self.args[0], None) if len(self.args) == 1 else self.args
if x is None and m.is_Integer and m.is_nonnegative:
from mpmath import mp
from sympy import Expr
m = m._to_mpmath(prec)
with workprec(prec):
res = mp.eulernum(m)
return Expr._from_mpmath(res, prec)
if x and x.is_number and m.is_Integer and m.is_nonnegative:
from mpmath import mp
from sympy import Expr
m = int(m)
x = x._to_mpmath(prec)
with workprec(prec):
res = mp.eulerpoly(m, x)
return Expr._from_mpmath(res, prec)
#----------------------------------------------------------------------------#
# #
# Catalan numbers #
# #
#----------------------------------------------------------------------------#
class catalan(Function):
r"""
Catalan numbers
The `n^{th}` catalan number is given by:
.. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
* ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
Examples
========
>>> from sympy import (Symbol, binomial, gamma, hyper, catalan,
... diff, combsimp, Rational, I)
>>> [catalan(i) for i in range(1,10)]
[1, 2, 5, 14, 42, 132, 429, 1430, 4862]
>>> n = Symbol("n", integer=True)
>>> catalan(n)
catalan(n)
Catalan numbers can be transformed into several other, identical
expressions involving other mathematical functions
>>> catalan(n).rewrite(binomial)
binomial(2*n, n)/(n + 1)
>>> catalan(n).rewrite(gamma)
4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
>>> catalan(n).rewrite(hyper)
hyper((1 - n, -n), (2,), 1)
For some non-integer values of n we can get closed form
expressions by rewriting in terms of gamma functions:
>>> catalan(Rational(1, 2)).rewrite(gamma)
8/(3*pi)
We can differentiate the Catalan numbers C(n) interpreted as a
continuous real function in n:
>>> diff(catalan(n), n)
(polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
As a more advanced example consider the following ratio
between consecutive numbers:
>>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
2*(2*n + 1)/(n + 2)
The Catalan numbers can be generalized to complex numbers:
>>> catalan(I).rewrite(gamma)
4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
and evaluated with arbitrary precision:
>>> catalan(I).evalf(20)
0.39764993382373624267 - 0.020884341620842555705*I
See Also
========
bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
sympy.functions.combinatorial.factorials.binomial
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan_number
.. [2] http://mathworld.wolfram.com/CatalanNumber.html
.. [3] http://functions.wolfram.com/GammaBetaErf/CatalanNumber/
.. [4] http://geometer.org/mathcircles/catalan.pdf
"""
@classmethod
def eval(cls, n):
from sympy import gamma
if (n.is_Integer and n.is_nonnegative) or \
(n.is_noninteger and n.is_negative):
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
if (n.is_integer and n.is_negative):
if (n + 1).is_negative:
return S.Zero
if (n + 1).is_zero:
return Rational(-1, 2)
def fdiff(self, argindex=1):
from sympy import polygamma, log
n = self.args[0]
return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
def _eval_rewrite_as_binomial(self, n, **kwargs):
return binomial(2*n, n)/(n + 1)
def _eval_rewrite_as_factorial(self, n, **kwargs):
return factorial(2*n) / (factorial(n+1) * factorial(n))
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
from sympy import gamma
# The gamma function allows to generalize Catalan numbers to complex n
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
def _eval_rewrite_as_hyper(self, n, **kwargs):
from sympy import hyper
return hyper([1 - n, -n], [2], 1)
def _eval_rewrite_as_Product(self, n, **kwargs):
from sympy import Product
if not (n.is_integer and n.is_nonnegative):
return self
k = Dummy('k', integer=True, positive=True)
return Product((n + k) / k, (k, 2, n))
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_positive(self):
if self.args[0].is_nonnegative:
return True
def _eval_is_composite(self):
if self.args[0].is_integer and (self.args[0] - 3).is_positive:
return True
def _eval_evalf(self, prec):
from sympy import gamma
if self.args[0].is_number:
return self.rewrite(gamma)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Genocchi numbers #
# #
#----------------------------------------------------------------------------#
class genocchi(Function):
r"""
Genocchi numbers
The Genocchi numbers are a sequence of integers `G_n` that satisfy the
relation:
.. math:: \frac{2t}{e^t + 1} = \sum_{n=1}^\infty \frac{G_n t^n}{n!}
Examples
========
>>> from sympy import Symbol
>>> from sympy.functions import genocchi
>>> [genocchi(n) for n in range(1, 9)]
[1, -1, 0, 1, 0, -3, 0, 17]
>>> n = Symbol('n', integer=True, positive=True)
>>> genocchi(2*n + 1)
0
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Genocchi_number
.. [2] http://mathworld.wolfram.com/GenocchiNumber.html
"""
@classmethod
def eval(cls, n):
if n.is_Number:
if (not n.is_Integer) or n.is_nonpositive:
raise ValueError("Genocchi numbers are defined only for " +
"positive integers")
return 2 * (1 - S(2) ** n) * bernoulli(n)
if n.is_odd and (n - 1).is_positive:
return S.Zero
if (n - 1).is_zero:
return S.One
def _eval_rewrite_as_bernoulli(self, n, **kwargs):
if n.is_integer and n.is_nonnegative:
return (1 - S(2) ** n) * bernoulli(n) * 2
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_positive:
return True
def _eval_is_negative(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_odd:
return False
return (n / 2).is_odd
def _eval_is_positive(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_odd:
return fuzzy_not((n - 1).is_positive)
return (n / 2).is_even
def _eval_is_even(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_even:
return False
return (n - 1).is_positive
def _eval_is_odd(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_even:
return True
return fuzzy_not((n - 1).is_positive)
def _eval_is_prime(self):
n = self.args[0]
# only G_6 = -3 and G_8 = 17 are prime,
# but SymPy does not consider negatives as prime
# so only n=8 is tested
return (n - 8).is_zero
#----------------------------------------------------------------------------#
# #
# Partition numbers #
# #
#----------------------------------------------------------------------------#
_npartition = [1, 1]
class partition(Function):
r"""
Partition numbers
The Partition numbers are a sequence of integers `p_n` that represent the
number of distinct ways of representing `n` as a sum of natural numbers
(with order irrelevant). The generating function for `p_n` is given by:
.. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
Examples
========
>>> from sympy import Symbol
>>> from sympy.functions import partition
>>> [partition(n) for n in range(9)]
[1, 1, 2, 3, 5, 7, 11, 15, 22]
>>> n = Symbol('n', integer=True, negative=True)
>>> partition(n)
0
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
.. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
"""
@staticmethod
def _partition(n):
L = len(_npartition)
if n < L:
return _npartition[n]
# lengthen cache
for _n in range(L, n + 1):
v, p, i = 0, 0, 0
while 1:
s = 0
p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
if _n >= p:
s += _npartition[_n - p]
i += 1
gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
if _n >= gp:
s += _npartition[_n - gp]
if s == 0:
break
else:
v += s if i%2 == 1 else -s
_npartition.append(v)
return v
@classmethod
def eval(cls, n):
is_int = n.is_integer
if is_int == False:
raise ValueError("Partition numbers are defined only for "
"integers")
elif is_int:
if n.is_negative:
return S.Zero
if n.is_zero or (n - 1).is_zero:
return S.One
if n.is_Integer:
return Integer(cls._partition(n))
def _eval_is_integer(self):
if self.args[0].is_integer:
return True
def _eval_is_negative(self):
if self.args[0].is_integer:
return False
def _eval_is_positive(self):
n = self.args[0]
if n.is_nonnegative and n.is_integer:
return True
#######################################################################
###
### Functions for enumerating partitions, permutations and combinations
###
#######################################################################
class _MultisetHistogram(tuple):
pass
_N = -1
_ITEMS = -2
_M = slice(None, _ITEMS)
def _multiset_histogram(n):
"""Return tuple used in permutation and combination counting. Input
is a dictionary giving items with counts as values or a sequence of
items (which need not be sorted).
The data is stored in a class deriving from tuple so it is easily
recognized and so it can be converted easily to a list.
"""
if isinstance(n, dict): # item: count
if not all(isinstance(v, int) and v >= 0 for v in n.values()):
raise ValueError
tot = sum(n.values())
items = sum(1 for k in n if n[k] > 0)
return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
else:
n = list(n)
s = set(n)
if len(s) == len(n):
n = [1]*len(n)
n.extend([len(n), len(n)])
return _MultisetHistogram(n)
m = dict(zip(s, range(len(s))))
d = dict(zip(range(len(s)), [0]*len(s)))
for i in n:
d[m[i]] += 1
return _multiset_histogram(d)
def nP(n, k=None, replacement=False):
"""Return the number of permutations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all permutations of length 0
through the number of items represented by ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' permutations of 2 would
include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
``n`` is ignored when ``replacement`` is True but the total number
of elements is considered since no element can appear more times than
the number of elements in ``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nP
>>> from sympy.utilities.iterables import multiset_permutations, multiset
>>> nP(3, 2)
6
>>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
True
>>> nP('aab', 2)
3
>>> nP([1, 2, 2], 2)
3
>>> [nP(3, i) for i in range(4)]
[1, 3, 6, 6]
>>> nP(3) == sum(_)
True
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nP('aabc', replacement=True)
121
>>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 9, 27, 81]
>>> sum(_)
121
See Also
========
sympy.utilities.iterables.multiset_permutations
References
==========
.. [1] https://en.wikipedia.org/wiki/Permutation
"""
try:
n = as_int(n)
except ValueError:
return Integer(_nP(_multiset_histogram(n), k, replacement))
return Integer(_nP(n, k, replacement))
@cacheit
def _nP(n, k=None, replacement=False):
from sympy.functions.combinatorial.factorials import factorial
from sympy.core.mul import prod
if k == 0:
return 1
if isinstance(n, SYMPY_INTS): # n different items
# assert n >= 0
if k is None:
return sum(_nP(n, i, replacement) for i in range(n + 1))
elif replacement:
return n**k
elif k > n:
return 0
elif k == n:
return factorial(k)
elif k == 1:
return n
else:
# assert k >= 0
return _product(n - k + 1, n)
elif isinstance(n, _MultisetHistogram):
if k is None:
return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
elif replacement:
return n[_ITEMS]**k
elif k == n[_N]:
return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
elif k > n[_N]:
return 0
elif k == 1:
return n[_ITEMS]
else:
# assert k >= 0
tot = 0
n = list(n)
for i in range(len(n[_M])):
if not n[i]:
continue
n[_N] -= 1
if n[i] == 1:
n[i] = 0
n[_ITEMS] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[_ITEMS] += 1
n[i] = 1
else:
n[i] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[i] += 1
n[_N] += 1
return tot
@cacheit
def _AOP_product(n):
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
of the product of AOPs (all-one polynomials) or order given in n. The
resulting coefficient corresponding to x**r is the number of r-length
combinations of sum(n) elements with multiplicities given in n.
The coefficients are given as a default dictionary (so if a query is made
for a key that is not present, 0 will be returned).
Examples
========
>>> from sympy.functions.combinatorial.numbers import _AOP_product
>>> from sympy.abc import x
>>> n = (2, 2, 3) # e.g. aabbccc
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
>>> c = _AOP_product(n); dict(c)
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
True
The generating poly used here is the same as that listed in
http://tinyurl.com/cep849r, but in a refactored form.
"""
from collections import defaultdict
n = list(n)
ord = sum(n)
need = (ord + 2)//2
rv = [1]*(n.pop() + 1)
rv.extend([0]*(need - len(rv)))
rv = rv[:need]
while n:
ni = n.pop()
N = ni + 1
was = rv[:]
for i in range(1, min(N, len(rv))):
rv[i] += rv[i - 1]
for i in range(N, need):
rv[i] += rv[i - 1] - was[i - N]
rev = list(reversed(rv))
if ord % 2:
rv = rv + rev
else:
rv[-1:] = rev
d = defaultdict(int)
for i in range(len(rv)):
d[i] = rv[i]
return d
def nC(n, k=None, replacement=False):
"""Return the number of combinations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all combinations of length 0
through the number of items represented in ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
``replacement`` is True but the total number of elements is considered
since no element can appear more times than the number of elements in
``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nC
>>> from sympy.utilities.iterables import multiset_combinations
>>> nC(3, 2)
3
>>> nC('abc', 2)
3
>>> nC('aab', 2)
2
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nC('aabc', replacement=True)
35
>>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 6, 10, 15]
>>> sum(_)
35
If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
then the total of all combinations of length 0 through ``k`` is the
product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
of each item is 1 (i.e., k unique items) then there are 2**k
combinations. For example, if there are 4 unique items, the total number
of combinations is 16:
>>> sum(nC(4, i) for i in range(5))
16
See Also
========
sympy.utilities.iterables.multiset_combinations
References
==========
.. [1] https://en.wikipedia.org/wiki/Combination
.. [2] http://tinyurl.com/cep849r
"""
from sympy.functions.combinatorial.factorials import binomial
from sympy.core.mul import prod
if isinstance(n, SYMPY_INTS):
if k is None:
if not replacement:
return 2**n
return sum(nC(n, i, replacement) for i in range(n + 1))
if k < 0:
raise ValueError("k cannot be negative")
if replacement:
return binomial(n + k - 1, k)
return binomial(n, k)
if isinstance(n, _MultisetHistogram):
N = n[_N]
if k is None:
if not replacement:
return prod(m + 1 for m in n[_M])
return sum(nC(n, i, replacement) for i in range(N + 1))
elif replacement:
return nC(n[_ITEMS], k, replacement)
# assert k >= 0
elif k in (1, N - 1):
return n[_ITEMS]
elif k in (0, N):
return 1
return _AOP_product(tuple(n[_M]))[k]
else:
return nC(_multiset_histogram(n), k, replacement)
def _eval_stirling1(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == n - 2:
return (3*n - 1)*binomial(n, 3)/4
elif k == n - 3:
return binomial(n, 2)*binomial(n, 4)
return _stirling1(n, k)
@cacheit
def _stirling1(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = (i-1) * row[j] + row[j-1]
return Integer(row[k])
def _eval_stirling2(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == 1:
return S.One
elif k == 2:
return Integer(2**(n - 1) - 1)
return _stirling2(n, k)
@cacheit
def _stirling2(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = j * row[j] + row[j-1]
return Integer(row[k])
def stirling(n, k, d=None, kind=2, signed=False):
r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
The sum of all Stirling numbers of the second kind for $k = 1$
through $n$ is ``bell(n)``. The recurrence relationship for these numbers
is:
.. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
.. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
where $j$ is:
$n$ for Stirling numbers of the first kind,
$-n$ for signed Stirling numbers of the first kind,
$k$ for Stirling numbers of the second kind.
The first kind of Stirling number counts the number of permutations of
``n`` distinct items that have ``k`` cycles; the second kind counts the
ways in which ``n`` distinct items can be partitioned into ``k`` parts.
If ``d`` is given, the "reduced Stirling number of the second kind" is
returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
(This counts the ways to partition $n$ consecutive integers into $k$
groups with no pairwise difference less than $d$. See example below.)
To obtain the signed Stirling numbers of the first kind, use keyword
``signed=True``. Using this keyword automatically sets ``kind`` to 1.
Examples
========
>>> from sympy.functions.combinatorial.numbers import stirling, bell
>>> from sympy.combinatorics import Permutation
>>> from sympy.utilities.iterables import multiset_partitions, permutations
First kind (unsigned by default):
>>> [stirling(6, i, kind=1) for i in range(7)]
[0, 120, 274, 225, 85, 15, 1]
>>> perms = list(permutations(range(4)))
>>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
[0, 6, 11, 6, 1]
>>> [stirling(4, i, kind=1) for i in range(5)]
[0, 6, 11, 6, 1]
First kind (signed):
>>> [stirling(4, i, signed=True) for i in range(5)]
[0, -6, 11, -6, 1]
Second kind:
>>> [stirling(10, i) for i in range(12)]
[0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
>>> sum(_) == bell(10)
True
>>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
True
Reduced second kind:
>>> from sympy import subsets, oo
>>> def delta(p):
... if len(p) == 1:
... return oo
... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
>>> parts = multiset_partitions(range(5), 3)
>>> d = 2
>>> sum(1 for p in parts if all(delta(i) >= d for i in p))
7
>>> stirling(5, 3, 2)
7
See Also
========
sympy.utilities.iterables.multiset_partitions
References
==========
.. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
.. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
"""
# TODO: make this a class like bell()
n = as_int(n)
k = as_int(k)
if n < 0:
raise ValueError('n must be nonnegative')
if k > n:
return S.Zero
if d:
# assert k >= d
# kind is ignored -- only kind=2 is supported
return _eval_stirling2(n - d + 1, k - d + 1)
elif signed:
# kind is ignored -- only kind=1 is supported
return (-1)**(n - k)*_eval_stirling1(n, k)
if kind == 1:
return _eval_stirling1(n, k)
elif kind == 2:
return _eval_stirling2(n, k)
else:
raise ValueError('kind must be 1 or 2, not %s' % k)
@cacheit
def _nT(n, k):
"""Return the partitions of ``n`` items into ``k`` parts. This
is used by ``nT`` for the case when ``n`` is an integer."""
# really quick exits
if k > n or k < 0:
return 0
if k == n or k == 1:
return 1
if k == 0:
return 0
# exits that could be done below but this is quicker
if k == 2:
return n//2
d = n - k
if d <= 3:
return d
# quick exit
if 3*k >= n: # or, equivalently, 2*k >= d
# all the information needed in this case
# will be in the cache needed to calculate
# partition(d), so...
# update cache
tot = partition._partition(d)
# and correct for values not needed
if d - k > 0:
tot -= sum(_npartition[:d - k])
return tot
# regular exit
# nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
# calculate needed nT(i, j) values
p = [1]*d
for i in range(2, k + 1):
for m in range(i + 1, d):
p[m] += p[m - i]
d -= 1
# if p[0] were appended to the end of p then the last
# k values of p are the nT(n, j) values for 0 < j < k in reverse
# order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
# putting the 1 from p[0] there, however, it is simply added to
# the sum below which is valid for 1 < k <= n//2
return (1 + sum(p[1 - k:]))
def nT(n, k=None):
"""Return the number of ``k``-sized partitions of ``n`` items.
Possible values for ``n``:
integer - ``n`` identical items
sequence - converted to a multiset internally
multiset - {element: multiplicity}
Note: the convention for ``nT`` is different than that of ``nC`` and
``nP`` in that
here an integer indicates ``n`` *identical* items instead of a set of
length ``n``; this is in keeping with the ``partitions`` function which
treats its integer-``n`` input like a list of ``n`` 1s. One can use
``range(n)`` for ``n`` to indicate ``n`` distinct items.
If ``k`` is None then the total number of ways to partition the elements
represented in ``n`` will be returned.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nT
Partitions of the given multiset:
>>> [nT('aabbc', i) for i in range(1, 7)]
[1, 8, 11, 5, 1, 0]
>>> nT('aabbc') == sum(_)
True
>>> [nT("mississippi", i) for i in range(1, 12)]
[1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
Partitions when all items are identical:
>>> [nT(5, i) for i in range(1, 6)]
[1, 2, 2, 1, 1]
>>> nT('1'*5) == sum(_)
True
When all items are different:
>>> [nT(range(5), i) for i in range(1, 6)]
[1, 15, 25, 10, 1]
>>> nT(range(5)) == sum(_)
True
Partitions of an integer expressed as a sum of positive integers:
>>> from sympy.functions.combinatorial.numbers import partition
>>> partition(4)
5
>>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
5
>>> nT('1'*4)
5
See Also
========
sympy.utilities.iterables.partitions
sympy.utilities.iterables.multiset_partitions
sympy.functions.combinatorial.numbers.partition
References
==========
.. [1] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf
"""
from sympy.utilities.enumerative import MultisetPartitionTraverser
if isinstance(n, SYMPY_INTS):
# n identical items
if k is None:
return partition(n)
if isinstance(k, SYMPY_INTS):
n = as_int(n)
k = as_int(k)
return Integer(_nT(n, k))
if not isinstance(n, _MultisetHistogram):
try:
# if n contains hashable items there is some
# quick handling that can be done
u = len(set(n))
if u <= 1:
return nT(len(n), k)
elif u == len(n):
n = range(u)
raise TypeError
except TypeError:
n = _multiset_histogram(n)
N = n[_N]
if k is None and N == 1:
return 1
if k in (1, N):
return 1
if k == 2 or N == 2 and k is None:
m, r = divmod(N, 2)
rv = sum(nC(n, i) for i in range(1, m + 1))
if not r:
rv -= nC(n, m)//2
if k is None:
rv += 1 # for k == 1
return rv
if N == n[_ITEMS]:
# all distinct
if k is None:
return bell(N)
return stirling(N, k)
m = MultisetPartitionTraverser()
if k is None:
return m.count_partitions(n[_M])
# MultisetPartitionTraverser does not have a range-limited count
# method, so need to enumerate and count
tot = 0
for discard in m.enum_range(n[_M], k-1, k):
tot += 1
return tot
#-----------------------------------------------------------------------------#
# #
# Motzkin numbers #
# #
#-----------------------------------------------------------------------------#
class motzkin(Function):
"""
The nth Motzkin number is the number
of ways of drawing non-intersecting chords
between n points on a circle (not necessarily touching
every point by a chord). The Motzkin numbers are named
after Theodore Motzkin and have diverse applications
in geometry, combinatorics and number theory.
Motzkin numbers are the integer sequence defined by the
initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
`M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
Examples
========
>>> from sympy import motzkin
>>> motzkin.is_motzkin(5)
False
>>> motzkin.find_motzkin_numbers_in_range(2,300)
[2, 4, 9, 21, 51, 127]
>>> motzkin.find_motzkin_numbers_in_range(2,900)
[2, 4, 9, 21, 51, 127, 323, 835]
>>> motzkin.find_first_n_motzkins(10)
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
References
==========
.. [1] https://en.wikipedia.org/wiki/Motzkin_number
.. [2] https://mathworld.wolfram.com/MotzkinNumber.html
"""
@staticmethod
def is_motzkin(n):
try:
n = as_int(n)
except ValueError:
return False
if n > 0:
if n == 1 or n == 2:
return True
tn1 = 1
tn = 2
i = 3
while tn < n:
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = a
if tn == n:
return True
else:
return False
else:
return False
@staticmethod
def find_motzkin_numbers_in_range(x, y):
if 0 <= x <= y:
motzkins = list()
if x <= 1 <= y:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while tn <= y:
if tn >= x:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
else:
raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
@staticmethod
def find_first_n_motzkins(n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
motzkins = list()
if n >= 0:
motzkins.append(1)
if n >= 1:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while i <= n:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
@staticmethod
@recurrence_memo([S.One, S.One])
def _motzkin(n, prev):
return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
@classmethod
def eval(cls, n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
return Integer(cls._motzkin(n - 1))
|
762a6ab7e252cf5c3bededfaa01ddde55596c99ba22d3df61097fea2bb5259aa | 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))]
"""
exp_sets = []
U = domain
complex = not domain.is_subset(S.Reals)
cond_free = set()
for expr, cond in self.args:
cond_free |= cond.free_symbols
if len(cond_free) > 1:
raise NotImplementedError(filldedent('''
multivariate conditions are not handled.'''))
if complex:
for i in cond.atoms(Relational):
if not isinstance(i, (Equality, Unequality)):
raise ValueError(filldedent('''
Inequalities in the complex domain are
not supported. Try the real domain by
setting domain=S.Reals'''))
cond_int = U.intersect(cond.as_set())
U = U - cond_int
if cond_int != S.EmptySet:
exp_sets.append((expr, cond_int))
return exp_sets
def _eval_rewrite_as_ITE(self, *args, **kwargs):
byfree = {}
args = list(args)
default = any(c == True for b, c in args)
for i, (b, c) in enumerate(args):
if not isinstance(b, Boolean) and b != True:
raise TypeError(filldedent('''
Expecting Boolean or bool but got `%s`
''' % func_name(b)))
if c == True:
break
# loop over independent conditions for this b
for c in c.args if isinstance(c, Or) else [c]:
free = c.free_symbols
x = free.pop()
try:
byfree[x] = byfree.setdefault(
x, S.EmptySet).union(c.as_set())
except NotImplementedError:
if not default:
raise NotImplementedError(filldedent('''
A method to determine whether a multivariate
conditional is consistent with a complete coverage
of all variables has not been implemented so the
rewrite is being stopped after encountering `%s`.
This error would not occur if a default expression
like `(foo, True)` were given.
''' % c))
if byfree[x] in (S.UniversalSet, S.Reals):
# collapse the ith condition to True and break
args[i] = list(args[i])
c = args[i][1] = True
break
if c == True:
break
if c != True:
raise ValueError(filldedent('''
Conditions must cover all reals or a final default
condition `(foo, True)` must be given.
'''))
last, _ = args[i] # ignore all past ith arg
for a, c in reversed(args[:i]):
last = ITE(c, a, last)
return _canonical(last)
def _eval_rewrite_as_KroneckerDelta(self, *args):
from sympy import Ne, Eq, Not, KroneckerDelta
rules = {
And: [False, False],
Or: [True, True],
Not: [True, False],
Eq: [None, None],
Ne: [None, None]
}
class UnrecognizedCondition(Exception):
pass
def rewrite(cond):
if isinstance(cond, Eq):
return KroneckerDelta(*cond.args)
if isinstance(cond, Ne):
return 1 - KroneckerDelta(*cond.args)
cls, args = type(cond), cond.args
if cls not in rules:
raise UnrecognizedCondition(cls)
b1, b2 = rules[cls]
k = 1
for c in args:
if b1:
k *= 1 - rewrite(c)
else:
k *= rewrite(c)
if b2:
return 1 - k
return k
conditions = []
true_value = None
for value, cond in args:
if type(cond) in rules:
conditions.append((value, cond))
elif cond is S.true:
if true_value is None:
true_value = value
else:
return
if true_value is not None:
result = true_value
for value, cond in conditions[::-1]:
try:
k = rewrite(cond)
result = k * value + (1 - k) * result
except UnrecognizedCondition:
return
return result
def piecewise_fold(expr):
"""
Takes an expression containing a piecewise function and returns the
expression in piecewise form. In addition, any ITE conditions are
rewritten in negation normal form and simplified.
Examples
========
>>> from sympy import Piecewise, piecewise_fold, sympify as S
>>> from sympy.abc import x
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, True))
See Also
========
Piecewise
"""
if not isinstance(expr, Basic) or not expr.has(Piecewise):
return expr
new_args = []
if isinstance(expr, (ExprCondPair, Piecewise)):
for e, c in expr.args:
if not isinstance(e, Piecewise):
e = piecewise_fold(e)
# we don't keep Piecewise in condition because
# it has to be checked to see that it's complete
# and we convert it to ITE at that time
assert not c.has(Piecewise) # pragma: no cover
if isinstance(c, ITE):
c = c.to_nnf()
c = simplify_logic(c, form='cnf')
if isinstance(e, Piecewise):
new_args.extend([(piecewise_fold(ei), And(ci, c))
for ei, ci in e.args])
else:
new_args.append((e, c))
else:
from sympy.utilities.iterables import cartes, sift, common_prefix
# Given
# P1 = Piecewise((e11, c1), (e12, c2), A)
# P2 = Piecewise((e21, c1), (e22, c2), B)
# ...
# the folding of f(P1, P2) is trivially
# Piecewise(
# (f(e11, e21), c1),
# (f(e12, e22), c2),
# (f(Piecewise(A), Piecewise(B)), True))
# Certain objects end up rewriting themselves as thus, so
# we do that grouping before the more generic folding.
# The following applies this idea when f = Add or f = Mul
# (and the expression is commutative).
if expr.is_Add or expr.is_Mul and expr.is_commutative:
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
for c in list(ordered(pc)):
if len(pc[c]) > 1:
pargs = [list(i.args) for i in pc[c]]
# the first one is the same; there may be more
com = common_prefix(*[
[i.cond for i in j] for j in pargs])
n = len(com)
collected = []
for i in range(n):
collected.append((
expr.func(*[ai[i].expr for ai in pargs]),
com[i]))
remains = []
for a in pargs:
if n == len(a): # no more args
continue
if a[n].cond == True: # no longer Piecewise
remains.append(a[n].expr)
else: # restore the remaining Piecewise
remains.append(
Piecewise(*a[n:], evaluate=False))
if remains:
collected.append((expr.func(*remains), True))
args.append(Piecewise(*collected, evaluate=False))
continue
args.extend(pc[c])
else:
args = expr.args
# fold
folded = list(map(piecewise_fold, args))
for ec in cartes(*[
(i.args if isinstance(i, Piecewise) else
[(i, true)]) for i in folded]):
e, c = zip(*ec)
new_args.append((expr.func(*e), And(*c)))
return Piecewise(*new_args)
def _clip(A, B, k):
"""Return interval B as intervals that are covered by A (keyed
to k) and all other intervals of B not covered by A keyed to -1.
The reference point of each interval is the rhs; if the lhs is
greater than the rhs then an interval of zero width interval will
result, e.g. (4, 1) is treated like (1, 1).
Examples
========
>>> from sympy.functions.elementary.piecewise import _clip
>>> from sympy import Tuple
>>> A = Tuple(1, 3)
>>> B = Tuple(2, 4)
>>> _clip(A, B, 0)
[(2, 3, 0), (3, 4, -1)]
Interpretation: interval portion (2, 3) of interval (2, 4) is
covered by interval (1, 3) and is keyed to 0 as requested;
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
"""
a, b = B
c, d = A
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
a, b = Min(a, b), b
p = []
if a != c:
p.append((a, c, -1))
else:
pass
if c != d:
p.append((c, d, k))
else:
pass
if b != d:
if d == c and p and p[-1][-1] == -1:
p[-1] = p[-1][0], b, -1
else:
p.append((d, b, -1))
else:
pass
return p
def piecewise_simplify_arguments(expr, **kwargs):
from sympy import simplify
args = []
for e, c in expr.args:
if isinstance(e, Basic):
doit = kwargs.pop('doit', None)
# Skip doit to avoid growth at every call for some integrals
# and sums, see sympy/sympy#17165
newe = simplify(e, doit=False, **kwargs)
if newe != expr:
e = newe
if isinstance(c, Basic):
c = simplify(c, doit=doit, **kwargs)
args.append((e, c))
return Piecewise(*args)
def piecewise_simplify(expr, **kwargs):
expr = piecewise_simplify_arguments(expr, **kwargs)
if not isinstance(expr, Piecewise):
return expr
args = list(expr.args)
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
getattr(e.rhs, '_diff_wrt', None) or
isinstance(e.rhs, (Rational, NumberSymbol)))
for i, (expr, cond) in enumerate(args):
# try to simplify conditions and the expression for
# equalities that are part of the condition, e.g.
# Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
# -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Equality), binary=True)
elif isinstance(cond, Equality):
eqs, other = [cond], []
else:
eqs = other = []
if eqs:
eqs = list(ordered(eqs))
for j, e in enumerate(eqs):
# these blessed lhs objects behave like Symbols
# and the rhs are simple replacements for the "symbols"
if _blessed(e):
expr = expr.subs(*e.args)
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
other = [ei.subs(*e.args) for ei in other]
cond = And(*(eqs + other))
args[i] = args[i].func(expr, cond)
# See if expressions valid for an Equal expression happens to evaluate
# to the same function as in the next piecewise segment, see:
# https://github.com/sympy/sympy/issues/8458
prevexpr = None
for i, (expr, cond) in reversed(list(enumerate(args))):
if prevexpr is not None:
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Equality), binary=True)
elif isinstance(cond, Equality):
eqs, other = [cond], []
else:
eqs = other = []
_prevexpr = prevexpr
_expr = expr
if eqs and not other:
eqs = list(ordered(eqs))
for e in eqs:
# allow 2 args to collapse into 1 for any e
# otherwise limit simplification to only simple-arg
# Eq instances
if len(args) == 2 or _blessed(e):
_prevexpr = _prevexpr.subs(*e.args)
_expr = _expr.subs(*e.args)
# Did it evaluate to the same?
if _prevexpr == _expr:
# Set the expression for the Not equal section to the same
# as the next. These will be merged when creating the new
# Piecewise
args[i] = args[i].func(args[i+1][0], cond)
else:
# Update the expression that we compare against
prevexpr = expr
else:
prevexpr = expr
return Piecewise(*args)
|
ba4775b519e0acac508258729574d4c39fb79f0902dd9550c9f1cc9adc5a39f4 | from sympy import Basic, Expr
from sympy.core import Add, S
from sympy.core.evalf import get_integer_part, PrecisionExhausted
from sympy.core.function import Function
from sympy.core.logic import fuzzy_or
from sympy.core.numbers import Integer
from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
from sympy.core.symbol import Symbol
from sympy.core.sympify import _sympify
from sympy.multipledispatch import dispatch
###############################################################################
######################### FLOOR and CEILING FUNCTIONS #########################
###############################################################################
class RoundFunction(Function):
"""The base class for rounding functions."""
@classmethod
def eval(cls, arg):
from sympy import im
v = cls._eval_number(arg)
if v is not None:
return v
if arg.is_integer or arg.is_finite is False:
return arg
if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
i = im(arg)
if not i.has(S.ImaginaryUnit):
return cls(i)*S.ImaginaryUnit
return cls(arg, evaluate=False)
# Integral, numerical, symbolic part
ipart = npart = spart = S.Zero
# Extract integral (or complex integral) terms
terms = Add.make_args(arg)
for t in terms:
if t.is_integer or (t.is_imaginary and im(t).is_integer):
ipart += t
elif t.has(Symbol):
spart += t
else:
npart += t
if not (npart or spart):
return ipart
# Evaluate npart numerically if independent of spart
if npart and (
not spart or
npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
npart.is_imaginary and spart.is_real):
try:
r, i = get_integer_part(
npart, cls._dir, {}, return_ints=True)
ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
npart = S.Zero
except (PrecisionExhausted, NotImplementedError):
pass
spart += npart
if not spart:
return ipart
elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
elif isinstance(spart, (floor, ceiling)):
return ipart + spart
else:
return ipart + cls(spart, evaluate=False)
def _eval_is_finite(self):
return self.args[0].is_finite
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_integer(self):
return self.args[0].is_real
class floor(RoundFunction):
"""
Floor is a univariate function which returns the largest integer
value not greater than its argument. This implementation
generalizes floor to complex numbers by taking the floor of the
real and imaginary parts separately.
Examples
========
>>> from sympy import floor, E, I, S, Float, Rational
>>> floor(17)
17
>>> floor(Rational(23, 10))
2
>>> floor(2*E)
5
>>> floor(-Float(0.567))
-1
>>> floor(-I/2)
-I
>>> floor(S(5)/2 + 5*I/2)
2 + 2*I
See Also
========
sympy.functions.elementary.integers.ceiling
References
==========
.. [1] "Concrete mathematics" by Graham, pp. 87
.. [2] http://mathworld.wolfram.com/FloorFunction.html
"""
_dir = -1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
return arg.floor()
elif any(isinstance(i, j)
for i in (arg, -arg) for j in (floor, ceiling)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[0]
def _eval_nseries(self, x, n, logx, cdir=0):
r = self.subs(x, 0)
args = self.args[0]
args0 = args.subs(x, 0)
if args0 == r:
direction = (args - args0).leadterm(x)[0]
if direction.is_positive:
return r
else:
return r - 1
else:
return r
def _eval_is_negative(self):
return self.args[0].is_negative
def _eval_is_nonnegative(self):
return self.args[0].is_nonnegative
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
return -ceiling(-arg)
def _eval_rewrite_as_frac(self, arg, **kwargs):
return arg - frac(arg)
def __le__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] < other + 1
if other.is_number and other.is_real:
return self.args[0] < ceiling(other)
if self.args[0] == other and other.is_real:
return S.true
if other is S.Infinity and self.is_finite:
return S.true
return Le(self, other, evaluate=False)
def __ge__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] >= other
if other.is_number and other.is_real:
return self.args[0] >= ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Ge(self, other, evaluate=False)
def __gt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] >= other + 1
if other.is_number and other.is_real:
return self.args[0] >= ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Gt(self, other, evaluate=False)
def __lt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] < other
if other.is_number and other.is_real:
return self.args[0] < ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Lt(self, other, evaluate=False)
@dispatch(floor, Expr)
def _eval_is_eq(lhs, rhs): # noqa:F811
return is_eq(lhs.rewrite(ceiling), rhs) or \
is_eq(lhs.rewrite(frac),rhs)
class ceiling(RoundFunction):
"""
Ceiling is a univariate function which returns the smallest integer
value not less than its argument. This implementation
generalizes ceiling to complex numbers by taking the ceiling of the
real and imaginary parts separately.
Examples
========
>>> from sympy import ceiling, E, I, S, Float, Rational
>>> ceiling(17)
17
>>> ceiling(Rational(23, 10))
3
>>> ceiling(2*E)
6
>>> ceiling(-Float(0.567))
0
>>> ceiling(I/2)
I
>>> ceiling(S(5)/2 + 5*I/2)
3 + 3*I
See Also
========
sympy.functions.elementary.integers.floor
References
==========
.. [1] "Concrete mathematics" by Graham, pp. 87
.. [2] http://mathworld.wolfram.com/CeilingFunction.html
"""
_dir = 1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
return arg.ceiling()
elif any(isinstance(i, j)
for i in (arg, -arg) for j in (floor, ceiling)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[1]
def _eval_nseries(self, x, n, logx, cdir=0):
r = self.subs(x, 0)
args = self.args[0]
args0 = args.subs(x, 0)
if args0 == r:
direction = (args - args0).leadterm(x)[0]
if direction.is_positive:
return r + 1
else:
return r
else:
return r
def _eval_rewrite_as_floor(self, arg, **kwargs):
return -floor(-arg)
def _eval_rewrite_as_frac(self, arg, **kwargs):
return arg + frac(-arg)
def _eval_is_positive(self):
return self.args[0].is_positive
def _eval_is_nonpositive(self):
return self.args[0].is_nonpositive
def __lt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] <= other - 1
if other.is_number and other.is_real:
return self.args[0] <= floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Lt(self, other, evaluate=False)
def __gt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] > other
if other.is_number and other.is_real:
return self.args[0] > floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Gt(self, other, evaluate=False)
def __ge__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] > other - 1
if other.is_number and other.is_real:
return self.args[0] > floor(other)
if self.args[0] == other and other.is_real:
return S.true
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Ge(self, other, evaluate=False)
def __le__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] <= other
if other.is_number and other.is_real:
return self.args[0] <= floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Le(self, other, evaluate=False)
@dispatch(ceiling, Basic) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
class frac(Function):
r"""Represents the fractional part of x
For real numbers it is defined [1]_ as
.. math::
x - \left\lfloor{x}\right\rfloor
Examples
========
>>> from sympy import Symbol, frac, Rational, floor, I
>>> frac(Rational(4, 3))
1/3
>>> frac(-Rational(4, 3))
2/3
returns zero for integer arguments
>>> n = Symbol('n', integer=True)
>>> frac(n)
0
rewrite as floor
>>> x = Symbol('x')
>>> frac(x).rewrite(floor)
x - floor(x)
for complex arguments
>>> r = Symbol('r', real=True)
>>> t = Symbol('t', real=True)
>>> frac(t + I*r)
I*frac(r) + frac(t)
See Also
========
sympy.functions.elementary.integers.floor
sympy.functions.elementary.integers.ceiling
References
===========
.. [1] https://en.wikipedia.org/wiki/Fractional_part
.. [2] http://mathworld.wolfram.com/FractionalPart.html
"""
@classmethod
def eval(cls, arg):
from sympy import AccumBounds, im
def _eval(arg):
if arg is S.Infinity or arg is S.NegativeInfinity:
return AccumBounds(0, 1)
if arg.is_integer:
return S.Zero
if arg.is_number:
if arg is S.NaN:
return S.NaN
elif arg is S.ComplexInfinity:
return S.NaN
else:
return arg - floor(arg)
return cls(arg, evaluate=False)
terms = Add.make_args(arg)
real, imag = S.Zero, S.Zero
for t in terms:
# Two checks are needed for complex arguments
# see issue-7649 for details
if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
i = im(t)
if not i.has(S.ImaginaryUnit):
imag += i
else:
real += t
else:
real += t
real = _eval(real)
imag = _eval(imag)
return real + S.ImaginaryUnit*imag
def _eval_rewrite_as_floor(self, arg, **kwargs):
return arg - floor(arg)
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
return arg + ceiling(-arg)
def _eval_is_finite(self):
return True
def _eval_is_real(self):
return self.args[0].is_extended_real
def _eval_is_imaginary(self):
return self.args[0].is_imaginary
def _eval_is_integer(self):
return self.args[0].is_integer
def _eval_is_zero(self):
return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
def _eval_is_negative(self):
return False
def __ge__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other <= 0
if other.is_extended_nonpositive:
return S.true
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return not(res)
return Ge(self, other, evaluate=False)
def __gt__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other < 0
res = self._value_one_or_more(other)
if res is not None:
return not(res)
# Check if other >= 1
if other.is_extended_negative:
return S.true
return Gt(self, other, evaluate=False)
def __le__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other < 0
if other.is_extended_negative:
return S.false
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return res
return Le(self, other, evaluate=False)
def __lt__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other <= 0
if other.is_extended_nonpositive:
return S.false
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return res
return Lt(self, other, evaluate=False)
def _value_one_or_more(self, other):
if other.is_extended_real:
if other.is_number:
res = other >= 1
if res and not isinstance(res, Relational):
return S.true
if other.is_integer and other.is_positive:
return S.true
@dispatch(frac, Basic) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if (lhs.rewrite(floor) == rhs) or \
(lhs.rewrite(ceiling) == rhs):
return True
# Check if other < 0
if rhs.is_extended_negative:
return False
# Check if other >= 1
res = lhs._value_one_or_more(rhs)
if res is not None:
return False
|
6874ec09dc7ef2e0ad99708dd78024e87552959acc406b4be1a84b197da70327 | 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.parameters import global_parameters
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 global_parameters.exp_is_pow:
return Pow(S.Exp1, arg)
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)
if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
return arg.exp
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
|
b1c70fbccc4fb674316a4d5dbc1d9a5eb1c4448c95fffdbf91173a5681079723 | import string
from sympy import (
Symbol, symbols, Dummy, S, Sum, Rational, oo, pi, I, floor, limit,
expand_func, diff, EulerGamma, cancel, re, im, Product, carmichael,
TribonacciConstant)
from sympy.functions import (
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
genocchi, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
trigamma, polygamma, factorial, sin, cos, cot, zeta)
from sympy.functions.combinatorial.numbers import _nT
from sympy.core.expr import unchanged
from sympy.core.numbers import GoldenRatio, Integer
from sympy.testing.pytest import XFAIL, raises, nocache_fail
x = Symbol('x')
def test_carmichael():
assert carmichael.find_carmichael_numbers_in_range(0, 561) == []
assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561]
assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561,
562)
assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821]
assert carmichael.is_prime(2821) == False
assert carmichael.is_prime(2465) == False
assert carmichael.is_prime(1729) == False
assert carmichael.is_prime(1105) == False
assert carmichael.is_prime(561) == False
raises(ValueError, lambda: carmichael.is_carmichael(-2))
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2))
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2))
def test_bernoulli():
assert bernoulli(0) == 1
assert bernoulli(1) == Rational(-1, 2)
assert bernoulli(2) == Rational(1, 6)
assert bernoulli(3) == 0
assert bernoulli(4) == Rational(-1, 30)
assert bernoulli(5) == 0
assert bernoulli(6) == Rational(1, 42)
assert bernoulli(7) == 0
assert bernoulli(8) == Rational(-1, 30)
assert bernoulli(10) == Rational(5, 66)
assert bernoulli(1000001) == 0
assert bernoulli(0, x) == 1
assert bernoulli(1, x) == x - S.Half
assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
# Should be fast; computed with mpmath
b = bernoulli(1000)
assert b.p % 10**10 == 7950421099
assert b.q == 342999030
b = bernoulli(10**6, evaluate=False).evalf()
assert str(b) == '-2.23799235765713e+4767529'
# Issue #8527
l = Symbol('l', integer=True)
m = Symbol('m', integer=True, nonnegative=True)
n = Symbol('n', integer=True, positive=True)
assert isinstance(bernoulli(2 * l + 1), bernoulli)
assert isinstance(bernoulli(2 * m + 1), bernoulli)
assert bernoulli(2 * n + 1) == 0
raises(ValueError, lambda: bernoulli(-2))
def test_fibonacci():
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
assert fibonacci(100) == 354224848179261915075
assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
assert lucas(100) == 792070839848372253127
assert fibonacci(1, x) == 1
assert fibonacci(2, x) == x
assert fibonacci(3, x) == x**2 + 1
assert fibonacci(4, x) == x**3 + 2*x
# issue #8800
n = Dummy('n')
assert fibonacci(n).limit(n, S.Infinity) is S.Infinity
assert lucas(n).limit(n, S.Infinity) is S.Infinity
assert fibonacci(n).rewrite(sqrt) == \
2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10)
assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
fibonacci(10)
assert lucas(n).rewrite(sqrt) == \
(fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify()
assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10)
raises(ValueError, lambda: fibonacci(-3, x))
def test_tribonacci():
assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24]
assert tribonacci(100) == 98079530178586034536500564
assert tribonacci(0, x) == 0
assert tribonacci(1, x) == 1
assert tribonacci(2, x) == x**2
assert tribonacci(3, x) == x**4 + x
assert tribonacci(4, x) == x**6 + 2*x**3 + 1
assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2
n = Dummy('n')
assert tribonacci(n).limit(n, S.Infinity) is S.Infinity
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
assert tribonacci(n).rewrite(sqrt) == \
(a**(n + 1)/((a - b)*(a - c))
+ b**(n + 1)/((b - a)*(b - c))
+ c**(n + 1)/((c - a)*(c - b)))
assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4)
assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
tribonacci(10)
assert tribonacci(n).rewrite(TribonacciConstant) == floor(
3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/
(-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33)
+ 586)**Rational(2, 3)) + S.Half)
raises(ValueError, lambda: tribonacci(-1, x))
@nocache_fail
def test_bell():
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
assert bell(0, x) == 1
assert bell(1, x) == x
assert bell(2, x) == x**2 + x
assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
assert bell(oo) is S.Infinity
raises(ValueError, lambda: bell(oo, x))
raises(ValueError, lambda: bell(-1))
raises(ValueError, lambda: bell(S.Half))
X = symbols('x:6')
# X = (x0, x1, .. x5)
# at the same time: X[1] = x1, X[2] = x2 for standard readablity.
# but we must supply zero-based indexed object X[1:] = (x1, .. x5)
assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
assert bell(
6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
X = (1, 10, 100, 1000, 10000)
assert bell(6, 2, X) == (6 + 15 + 10)*10000
X = (1, 2, 3, 3, 5)
assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
X = (1, 2, 3, 5)
assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
# Dobinski's formula
n = Symbol('n', integer=True, nonnegative=True)
# For large numbers, this is too slow
# For nonintegers, there are significant precision errors
for i in [0, 2, 3, 7, 13, 42, 55]:
# Running without the cache this is either very slow or goes into an
# infinite loop.
assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i})
m = Symbol("m")
assert bell(m).rewrite(Sum) == bell(m)
assert bell(n, m).rewrite(Sum) == bell(n, m)
# issue 9184
n = Dummy('n')
assert bell(n).limit(n, S.Infinity) is S.Infinity
def test_harmonic():
n = Symbol("n")
m = Symbol("m")
assert harmonic(n, 0) == n
assert harmonic(n).evalf() == harmonic(n)
assert harmonic(n, 1) == harmonic(n)
assert harmonic(1, n).evalf() == harmonic(1, n)
assert harmonic(0, 1) == 0
assert harmonic(1, 1) == 1
assert harmonic(2, 1) == Rational(3, 2)
assert harmonic(3, 1) == Rational(11, 6)
assert harmonic(4, 1) == Rational(25, 12)
assert harmonic(0, 2) == 0
assert harmonic(1, 2) == 1
assert harmonic(2, 2) == Rational(5, 4)
assert harmonic(3, 2) == Rational(49, 36)
assert harmonic(4, 2) == Rational(205, 144)
assert harmonic(0, 3) == 0
assert harmonic(1, 3) == 1
assert harmonic(2, 3) == Rational(9, 8)
assert harmonic(3, 3) == Rational(251, 216)
assert harmonic(4, 3) == Rational(2035, 1728)
assert harmonic(oo, -1) is S.NaN
assert harmonic(oo, 0) is oo
assert harmonic(oo, S.Half) is oo
assert harmonic(oo, 1) is oo
assert harmonic(oo, 2) == (pi**2)/6
assert harmonic(oo, 3) == zeta(3)
assert harmonic(0, m) == 0
def test_harmonic_rational():
ne = S(6)
no = S(5)
pe = S(8)
po = S(9)
qe = S(10)
qo = S(13)
Heee = harmonic(ne + pe/qe)
Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968))
Heeo = harmonic(ne + pe/qo)
Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13))
+ Rational(2422020029, 702257080))
Heoe = harmonic(ne + po/qe)
Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
+ Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2)
Heoo = harmonic(ne + po/qo)
Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
- 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320))
Hoee = harmonic(no + pe/qe)
Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704))
Hoeo = harmonic(no + pe/qo)
Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2
- 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560))
Hooe = harmonic(no + po/qe)
Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
+ Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2)
Hooo = harmonic(no + po/qo)
Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
- 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080))
H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo]
A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo]
for h, a in zip(H, A):
e = expand_func(h).doit()
assert cancel(e/a) == 1
assert abs(h.n() - a.n()) < 1e-12
def test_harmonic_evalf():
assert str(harmonic(1.5).evalf(n=10)) == '1.280372306'
assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443
def test_harmonic_rewrite():
n = Symbol("n")
m = Symbol("m")
assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
assert harmonic(n,m).rewrite(polygamma) == (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)
assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
_k = Dummy("k")
assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n)))
assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n)))
@XFAIL
def test_harmonic_limit_fail():
n = Symbol("n")
m = Symbol("m")
# For m > 1:
assert limit(harmonic(n, m), n, oo) == zeta(m)
def test_euler():
assert euler(0) == 1
assert euler(1) == 0
assert euler(2) == -1
assert euler(3) == 0
assert euler(4) == 5
assert euler(6) == -61
assert euler(8) == 1385
assert euler(20, evaluate=False) != 370371188237525
n = Symbol('n', integer=True)
assert euler(n) != -1
assert euler(n).subs(n, 2) == -1
raises(ValueError, lambda: euler(-2))
raises(ValueError, lambda: euler(-3))
raises(ValueError, lambda: euler(2.3))
assert euler(20).evalf() == 370371188237525.0
assert euler(20, evaluate=False).evalf() == 370371188237525.0
assert euler(n).rewrite(Sum) == euler(n)
n = Symbol('n', integer=True, nonnegative=True)
assert euler(2*n + 1).rewrite(Sum) == 0
_j = Dummy('j')
_k = Dummy('k')
assert euler(2*n).rewrite(Sum).dummy_eq(
I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*
binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1)))
def test_euler_odd():
n = Symbol('n', odd=True, positive=True)
assert euler(n) == 0
n = Symbol('n', odd=True)
assert euler(n) != 0
def test_euler_polynomials():
assert euler(0, x) == 1
assert euler(1, x) == x - S.Half
assert euler(2, x) == x**2 - x
assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4)
m = Symbol('m')
assert isinstance(euler(m, x), euler)
from sympy import Float
A = Float('-0.46237208575048694923364757452876131e8') # from Maple
B = euler(19, S.Pi.evalf(32))
assert abs((A - B)/A) < 1e-31 # expect low relative error
C = euler(19, S.Pi, evaluate=False).evalf(32)
assert abs((A - C)/A) < 1e-31
def test_euler_polynomial_rewrite():
m = Symbol('m')
A = euler(m, x).rewrite('Sum');
assert A.subs({m:3, x:5}).doit() == euler(3, 5)
def test_catalan():
n = Symbol('n', integer=True)
m = Symbol('m', integer=True, positive=True)
k = Symbol('k', integer=True, nonnegative=True)
p = Symbol('p', nonnegative=True)
catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
for i, c in enumerate(catalans):
assert catalan(i) == c
assert catalan(n).rewrite(factorial).subs(n, i) == c
assert catalan(n).rewrite(Product).subs(n, i).doit() == c
assert unchanged(catalan, x)
assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
assert catalan(S.Half).rewrite(gamma) == 8/(3*pi)
assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\
8 / (3 * pi)
assert catalan(3*x).rewrite(gamma) == 4**(
3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2))
assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
* factorial(n))
assert isinstance(catalan(n).rewrite(Product), catalan)
assert isinstance(catalan(m).rewrite(Product), Product)
assert diff(catalan(x), x) == (polygamma(
0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x)
assert catalan(x).evalf() == catalan(x)
c = catalan(S.Half).evalf()
assert str(c) == '0.848826363156775'
c = catalan(I).evalf(3)
assert str((re(c), im(c))) == '(0.398, -0.0209)'
# Assumptions
assert catalan(p).is_positive is True
assert catalan(k).is_integer is True
assert catalan(m+3).is_composite is True
def test_genocchi():
genocchis = [1, -1, 0, 1, 0, -3, 0, 17]
for n, g in enumerate(genocchis):
assert genocchi(n + 1) == g
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, positive=True)
assert unchanged(genocchi, m)
assert genocchi(2*n + 1) == 0
assert genocchi(n).rewrite(bernoulli) == (1 - 2 ** n) * bernoulli(n) * 2
assert genocchi(2 * n).is_odd
assert genocchi(2 * n).is_even is False
assert genocchi(2 * n + 1).is_even
assert genocchi(n).is_integer
assert genocchi(4 * n).is_positive
# these are the only 2 prime Genocchi numbers
assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime
assert genocchi(8, evaluate=False).is_prime
assert genocchi(4 * n + 2).is_negative
assert genocchi(4 * n + 1).is_negative is False
assert genocchi(4 * n - 2).is_negative
raises(ValueError, lambda: genocchi(Rational(5, 4)))
raises(ValueError, lambda: genocchi(-2))
@nocache_fail
def test_partition():
partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22]
for n, p in enumerate(partition_nums):
assert partition(n) == p
x = Symbol('x')
y = Symbol('y', real=True)
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, negative=True)
p = Symbol('p', integer=True, nonnegative=True)
assert partition(m).is_integer
assert not partition(m).is_negative
assert partition(m).is_nonnegative
assert partition(n).is_zero
assert partition(p).is_positive
assert partition(x).subs(x, 7) == 15
assert partition(y).subs(y, 8) == 22
raises(ValueError, lambda: partition(Rational(5, 4)))
def test__nT():
assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [
1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0]
check = [_nT(10, i) for i in range(11)]
assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1]
assert all(type(i) is int for i in check)
assert _nT(10, 5) == 7
assert _nT(100, 98) == 2
assert _nT(100, 100) == 1
assert _nT(10, 3) == 8
def test_nC_nP_nT():
from sympy.utilities.iterables import (
multiset_permutations, multiset_combinations, multiset_partitions,
partitions, subsets, permutations)
from sympy.functions.combinatorial.numbers import (
nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product)
from sympy.combinatorics.permutations import Permutation
from sympy.core.numbers import oo
from random import choice
c = string.ascii_lowercase
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nP(s, i)
tot += check
assert len(list(multiset_permutations(s, i))) == check
if u:
assert nP(len(s), i) == check
assert nP(s) == tot
except AssertionError:
print(s, i, 'failed perm test')
raise ValueError()
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nC(s, i)
tot += check
assert len(list(multiset_combinations(s, i))) == check
if u:
assert nC(len(s), i) == check
assert nC(s) == tot
if u:
assert nC(len(s)) == tot
except AssertionError:
print(s, i, 'failed combo test')
raise ValueError()
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(i, j)
assert check.is_Integer
tot += check
assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
assert nT(i) == tot
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(range(i), j)
tot += check
assert len(list(multiset_partitions(list(range(i)), j))) == check
assert nT(range(i)) == tot
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(1, 8):
check = nT(s, i)
tot += check
assert len(list(multiset_partitions(s, i))) == check
if u:
assert nT(range(len(s)), i) == check
if u:
assert nT(range(len(s))) == tot
assert nT(s) == tot
except AssertionError:
print(s, i, 'failed partition test')
raise ValueError()
# tests for Stirling numbers of the first kind that are not tested in the
# above
assert [stirling(9, i, kind=1) for i in range(11)] == [
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
perms = list(permutations(range(4)))
assert [sum(1 for p in perms if Permutation(p).cycles == i)
for i in range(5)] == [0, 6, 11, 6, 1] == [
stirling(4, i, kind=1) for i in range(5)]
# http://oeis.org/A008275
assert [stirling(n, k, signed=1)
for n in range(10) for k in range(1, n + 1)] == [
1, -1,
1, 2, -3,
1, -6, 11, -6,
1, 24, -50, 35, -10,
1, -120, 274, -225, 85, -15,
1, 720, -1764, 1624, -735, 175, -21,
1, -5040, 13068, -13132, 6769, -1960, 322, -28,
1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
assert [stirling(n, k, kind=1)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 2, 3, 1,
0, 6, 11, 6, 1,
0, 24, 50, 35, 10, 1,
0, 120, 274, 225, 85, 15, 1,
0, 720, 1764, 1624, 735, 175, 21, 1,
0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
assert [stirling(n, k, kind=2)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 1, 3, 1,
0, 1, 7, 6, 1,
0, 1, 15, 25, 10, 1,
0, 1, 31, 90, 65, 15, 1,
0, 1, 63, 301, 350, 140, 21, 1,
0, 1, 127, 966, 1701, 1050, 266, 28, 1,
0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
raises(ValueError, lambda: stirling(-2, 2))
# Assertion that the return type is SymPy Integer.
assert isinstance(_stirling1(6, 3), Integer)
assert isinstance(_stirling2(6, 3), Integer)
def delta(p):
if len(p) == 1:
return oo
return min(abs(i[0] - i[1]) for i in subsets(p, 2))
parts = multiset_partitions(range(5), 3)
d = 2
assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
stirling(5, 3, d=d) == 7)
# other coverage tests
assert nC('abb', 2) == nC('aab', 2) == 2
assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
assert nP(3, 4) == 0
assert nP('aabc', 5) == 0
assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
len(list(multiset_combinations('aabbccdd', 2))) == 10
assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
assert nC(list('abcdd'), 4) == 4
assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
assert dict(_AOP_product((4,1,1,1))) == {
0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
# the following was the first t that showed a problem in a previous form of
# the function, so it's not as random as it may appear
t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
raises(ValueError, lambda: _multiset_histogram({1:'a'}))
def test_PR_14617():
from sympy.functions.combinatorial.numbers import nT
for n in (0, []):
for k in (-1, 0, 1):
if k == 0:
assert nT(n, k) == 1
else:
assert nT(n, k) == 0
def test_issue_8496():
n = Symbol("n")
k = Symbol("k")
raises(TypeError, lambda: catalan(n, k))
def test_issue_8601():
n = Symbol('n', integer=True, negative=True)
assert catalan(n - 1) is S.Zero
assert catalan(Rational(-1, 2)) is S.ComplexInfinity
assert catalan(-S.One) == Rational(-1, 2)
c1 = catalan(-5.6).evalf()
assert str(c1) == '6.93334070531408e-5'
c2 = catalan(-35.4).evalf()
assert str(c2) == '-4.14189164517449e-24'
def test_motzkin():
assert motzkin.is_motzkin(4) == True
assert motzkin.is_motzkin(9) == True
assert motzkin.is_motzkin(10) == False
assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127]
assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323]
assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835]
assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9]
assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51]
assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
raises(ValueError, lambda: motzkin.eval(77.58))
raises(ValueError, lambda: motzkin.eval(-8))
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7))
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7))
raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8))
|
d4c7a5b242d0c5689ef7531720c84cba19edada04e168a260ec213003e48d3f6 | 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.core.parameters import global_parameters
from sympy.functions.elementary.exponential import match_real_imag
from sympy.abc import x, y, z
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import raises, XFAIL, _both_exp_pow
@_both_exp_pow
def test_exp_values():
if global_parameters.exp_is_pow:
assert type(exp(x)) is Pow
else:
assert type(exp(x)) is exp
k = Symbol('k', integer=True)
assert exp(nan) is nan
assert exp(oo) is oo
assert exp(-oo) == 0
assert exp(0) == 1
assert exp(1) == E
assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
assert exp(pi*I/2) == I
assert exp(pi*I) == -1
assert exp(pi*I*Rational(3, 2)) == -I
assert exp(2*pi*I) == 1
assert refine(exp(pi*I*2*k)) == 1
assert refine(exp(pi*I*2*(k + S.Half))) == -1
assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
assert exp(log(x)) == x
assert exp(2*log(x)) == x**2
assert exp(pi*log(x)) == x**pi
assert exp(17*log(x) + E*log(y)) == x**17 * y**E
assert exp(x*log(x)) != x**x
assert exp(sin(x)*log(x)) != x
assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
assert exp(-oo, evaluate=False).is_finite is True
assert exp(oo, evaluate=False).is_finite is False
@_both_exp_pow
def test_exp_period():
assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
n = Symbol('n', integer=True)
e = Symbol('e', even=True)
assert exp(e*I*pi) == 1
assert exp((e + 1)*I*pi) == -1
assert exp((1 + 4*n)*I*pi/2) == I
assert exp((-1 + 4*n)*I*pi/2) == -I
@_both_exp_pow
def test_exp_log():
x = Symbol("x", real=True)
assert log(exp(x)) == x
assert exp(log(x)) == x
if not global_parameters.exp_is_pow:
assert log(x).inverse() == exp
assert exp(x).inverse() == log
y = Symbol("y", polar=True)
assert log(exp_polar(z)) == z
assert exp(log(y)) == y
@_both_exp_pow
def test_exp_expand():
e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
assert e.expand() == 2
assert exp(x + y) != exp(x)*exp(y)
assert exp(x + y).expand() == exp(x)*exp(y)
@_both_exp_pow
def test_exp__as_base_exp():
assert exp(x).as_base_exp() == (E, x)
assert exp(2*x).as_base_exp() == (E, 2*x)
assert exp(x*y).as_base_exp() == (E, x*y)
assert exp(-x).as_base_exp() == (E, -x)
# Pow( *expr.as_base_exp() ) == expr invariant should hold
assert E**x == exp(x)
assert E**(2*x) == exp(2*x)
assert E**(x*y) == exp(x*y)
assert exp(x).base is S.Exp1
assert exp(x).exp == x
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))
@_both_exp_pow
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
if not global_parameters.exp_is_pow:
assert exp(x*log(y)).rewrite(Pow) == y**x
assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
n = Symbol('n', integer=True)
assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*Rational(2, 5)
assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
== 4/(3 - sqrt(3)*I))
@_both_exp_pow
def test_exp_leading_term():
assert exp(x).as_leading_term(x) == 1
assert exp(2 + x).as_leading_term(x) == exp(2)
assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
# The following tests are commented, since now SymPy returns the
# original function when the leading term in the series expansion does
# not exist.
# raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
# raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
# raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
@_both_exp_pow
def test_exp_taylor_term():
x = symbols('x')
assert exp(x).taylor_term(1, x) == x
assert exp(x).taylor_term(3, x) == x**3/6
assert exp(x).taylor_term(4, x) == x**4/24
assert exp(x).taylor_term(-1, x) is S.Zero
def test_exp_MatrixSymbol():
A = MatrixSymbol("A", 2, 2)
assert exp(A).has(exp)
def test_exp_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
def test_log_values():
assert log(nan) is nan
assert log(oo) is oo
assert log(-oo) is oo
assert log(zoo) is zoo
assert log(-zoo) is zoo
assert log(0) is zoo
assert log(1) == 0
assert log(-1) == I*pi
assert log(E) == 1
assert log(-E).expand() == 1 + I*pi
assert unchanged(log, pi)
assert log(-pi).expand() == log(pi) + I*pi
assert unchanged(log, 17)
assert log(-17) == log(17) + I*pi
assert log(I) == I*pi/2
assert log(-I) == -I*pi/2
assert log(17*I) == I*pi/2 + log(17)
assert log(-17*I).expand() == -I*pi/2 + log(17)
assert log(oo*I) is oo
assert log(-oo*I) is oo
assert log(0, 2) is zoo
assert log(0, 5) is zoo
assert exp(-log(3))**(-1) == 3
assert log(S.Half) == -log(2)
assert log(2*3).func is log
assert log(2*3**2).func is log
def test_match_real_imag():
x, y = symbols('x,y', real=True)
i = Symbol('i', imaginary=True)
assert match_real_imag(S.One) == (1, 0)
assert match_real_imag(I) == (0, 1)
assert match_real_imag(3 - 5*I) == (3, -5)
assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
assert match_real_imag(x + y*I) == (x, y)
assert match_real_imag(x*I + y*I) == (0, x + y)
assert match_real_imag((x + y)*I) == (0, x + y)
assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
assert match_real_imag(1 - 2*i) == (None, None)
assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
def test_log_exact():
# check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
for n in range(-23, 24):
if gcd(n, 24) != 1:
assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
for n in range(-9, 10):
assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
# bail quickly if no obvious simplification is possible:
assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
# beware of non-real coefficients
assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
def test_log_base():
assert log(1, 2) == 0
assert log(2, 2) == 1
assert log(3, 2) == log(3)/log(2)
assert log(6, 2) == 1 + log(3)/log(2)
assert log(6, 3) == 1 + log(2)/log(3)
assert log(2**3, 2) == 3
assert log(3**3, 3) == 3
assert log(5, 1) is zoo
assert log(1, 1) is nan
assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
assert log(Rational(2, 3), Rational(2, 5)) == \
log(Rational(2, 3))/log(Rational(2, 5))
# issue 17148
assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
def test_log_symbolic():
assert log(x, exp(1)) == log(x)
assert log(exp(x)) != x
assert log(x, exp(1)) == log(x)
assert log(x*y) != log(x) + log(y)
assert log(x/y).expand() != log(x) - log(y)
assert log(x/y).expand(force=True) == log(x) - log(y)
assert log(x**y).expand() != y*log(x)
assert log(x**y).expand(force=True) == y*log(x)
assert log(x, 2) == log(x)/log(2)
assert log(E, 2) == 1/log(2)
p, q = symbols('p,q', positive=True)
r = Symbol('r', real=True)
assert log(p**2) != 2*log(p)
assert log(p**2).expand() == 2*log(p)
assert log(x**2).expand() != 2*log(x)
assert log(p**q) != q*log(p)
assert log(exp(p)) == p
assert log(p*q) != log(p) + log(q)
assert log(p*q).expand() == log(p) + log(q)
assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
assert log(-exp(p)) != p + I*pi
assert log(-exp(x)).expand() != x + I*pi
assert log(-exp(r)).expand() == r + I*pi
assert log(x**y) != y*log(x)
assert (log(x**-5)**-1).expand() != -1/log(x)/5
assert (log(p**-5)**-1).expand() == -1/log(p)/5
assert log(-x).func is log and log(-x).args[0] == -x
assert log(-p).func is log and log(-p).args[0] == -p
def test_log_exp():
assert log(exp(4*I*pi)) == 0 # exp evaluates
assert log(exp(-5*I*pi)) == I*pi # exp evaluates
assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
assert log(exp(-5*I)) == -5*I + 2*I*pi
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)
@_both_exp_pow
def test_as_numer_denom():
n = symbols('n', negative=True)
assert exp(x).as_numer_denom() == (exp(x), 1)
assert exp(-x).as_numer_denom() == (1, exp(x))
assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
assert exp(-2).as_numer_denom() == (1, exp(2))
assert exp(n).as_numer_denom() == (1, exp(-n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
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
|
0e948202e40946e68da421724757309e39e1f1538f62e4a8ca512b84828413d9 | from sympy import (
Abs, And, Derivative, Dummy, Eq, Float, Function, Gt, I, Integral,
LambertW, Lt, Matrix, Or, Poly, Q, Rational, S, Symbol, Ne,
Wild, acos, asin, atan, atanh, binomial, cos, cosh, diff, erf, erfinv, erfc,
erfcinv, exp, im, log, pi, re, sec, sin,
sinh, solve, solve_linear, sqrt, sstr, symbols, sympify, tan, tanh,
root, atan2, arg, Mul, SparseMatrix, ask, Tuple, nsolve, oo,
E, cbrt, denom, Add, Piecewise, GoldenRatio, TribonacciConstant)
from sympy.core.function import nfloat
from sympy.solvers import solve_linear_system, solve_linear_system_LU, \
solve_undetermined_coeffs
from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert
from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \
det_quick, det_perm, det_minor, _simple_dens, denoms
from sympy.physics.units import cm
from sympy.polys.rootoftools import CRootOf
from sympy.testing.pytest import slow, XFAIL, SKIP, raises
from sympy.testing.randtest import verify_numerically as tn
from sympy.abc import a, b, c, d, k, h, p, x, y, z, t, q, m
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_swap_back():
f, g = map(Function, 'fg')
fx, gx = f(x), g(x)
assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \
{fx: gx + 5, y: -gx - 3}
assert solve(fx + gx*x - 2, [fx, gx], dict=True)[0] == {fx: 2, gx: 0}
assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y - gx**2*x}]
assert solve([f(1) - 2, x + 2], dict=True) == [{x: -2, f(1): 2}]
def guess_solve_strategy(eq, symbol):
try:
solve(eq, symbol)
return True
except (TypeError, NotImplementedError):
return False
def test_guess_poly():
# polynomial equations
assert guess_solve_strategy( S(4), x ) # == GS_POLY
assert guess_solve_strategy( x, x ) # == GS_POLY
assert guess_solve_strategy( x + a, x ) # == GS_POLY
assert guess_solve_strategy( 2*x, x ) # == GS_POLY
assert guess_solve_strategy( x + sqrt(2), x) # == GS_POLY
assert guess_solve_strategy( x + 2**Rational(1, 4), x) # == GS_POLY
assert guess_solve_strategy( x**2 + 1, x ) # == GS_POLY
assert guess_solve_strategy( x**2 - 1, x ) # == GS_POLY
assert guess_solve_strategy( x*y + y, x ) # == GS_POLY
assert guess_solve_strategy( x*exp(y) + y, x) # == GS_POLY
assert guess_solve_strategy(
(x - y**3)/(y**2*sqrt(1 - y**2)), x) # == GS_POLY
def test_guess_poly_cv():
# polynomial equations via a change of variable
assert guess_solve_strategy( sqrt(x) + 1, x ) # == GS_POLY_CV_1
assert guess_solve_strategy(
x**Rational(1, 3) + sqrt(x) + 1, x ) # == GS_POLY_CV_1
assert guess_solve_strategy( 4*x*(1 - sqrt(x)), x ) # == GS_POLY_CV_1
# polynomial equation multiplying both sides by x**n
assert guess_solve_strategy( x + 1/x + y, x ) # == GS_POLY_CV_2
def test_guess_rational_cv():
# rational functions
assert guess_solve_strategy( (x + 1)/(x**2 + 2), x) # == GS_RATIONAL
assert guess_solve_strategy(
(x - y**3)/(y**2*sqrt(1 - y**2)), y) # == GS_RATIONAL_CV_1
# rational functions via the change of variable y -> x**n
assert guess_solve_strategy( (sqrt(x) + 1)/(x**Rational(1, 3) + sqrt(x) + 1), x ) \
#== GS_RATIONAL_CV_1
def test_guess_transcendental():
#transcendental functions
assert guess_solve_strategy( exp(x) + 1, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(
exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL
def test_solve_args():
# equation container, issue 5113
ans = {x: -3, y: 1}
eqs = (x + 5*y - 2, -3*x + 6*y - 15)
assert all(solve(container(eqs), x, y) == ans for container in
(tuple, list, set, frozenset))
assert solve(Tuple(*eqs), x, y) == ans
# implicit symbol to solve for
assert set(solve(x**2 - 4)) == {S(2), -S(2)}
assert solve([x + y - 3, x - y - 5]) == {x: 4, y: -1}
assert solve(x - exp(x), x, implicit=True) == [exp(x)]
# no symbol to solve for
assert solve(42) == solve(42, x) == []
assert solve([1, 2]) == []
# duplicate symbols removed
assert solve((x - 3, y + 2), x, y, x) == {x: 3, y: -2}
# unordered symbols
# only 1
assert solve(y - 3, {y}) == [3]
# more than 1
assert solve(y - 3, {x, y}) == [{y: 3}]
# multiple symbols: take the first linear solution+
# - return as tuple with values for all requested symbols
assert solve(x + y - 3, [x, y]) == [(3 - y, y)]
# - unless dict is True
assert solve(x + y - 3, [x, y], dict=True) == [{x: 3 - y}]
# - or no symbols are given
assert solve(x + y - 3) == [{x: 3 - y}]
# multiple symbols might represent an undetermined coefficients system
assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0}
args = (a + b)*x - b**2 + 2, a, b
assert solve(*args) == \
[(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]
assert solve(*args, set=True) == \
([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))})
assert solve(*args, dict=True) == \
[{b: sqrt(2), a: -sqrt(2)}, {b: -sqrt(2), a: sqrt(2)}]
eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p
flags = dict(dict=True)
assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \
[{k: c - b**2/(4*a), h: -b/(2*a), p: 1/(4*a)}]
flags.update(dict(simplify=False))
assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \
[{k: (4*a*c - b**2)/(4*a), h: -b/(2*a), p: 1/(4*a)}]
# failing undetermined system
assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \
[{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}]
# failed single equation
assert solve(1/(1/x - y + exp(y))) == []
raises(
NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y)))
# failed system
# -- when no symbols given, 1 fails
assert solve([y, exp(x) + x]) == {x: -LambertW(1), y: 0}
# both fail
assert solve(
(exp(x) - x, exp(y) - y)) == {x: -LambertW(-1), y: -LambertW(-1)}
# -- when symbols given
solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)]
# symbol is a number
assert solve(x**2 - pi, pi) == [x**2]
# no equations
assert solve([], [x]) == []
# overdetermined system
# - nonlinear
assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}]
# - linear
assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2}
# When one or more args are Boolean
assert solve(Eq(x**2, 0.0)) == [0] # issue 19048
assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}]
assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == []
assert not solve([Eq(x, x+1), x < 2], x)
assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0)
assert solve([Eq(x, x), Eq(x, x+1)], x) == []
assert solve(True, x) == []
assert solve([x - 1, False], [x], set=True) == ([], set())
def test_solve_polynomial1():
assert solve(3*x - 2, x) == [Rational(2, 3)]
assert solve(Eq(3*x, 2), x) == [Rational(2, 3)]
assert set(solve(x**2 - 1, x)) == {-S.One, S.One}
assert set(solve(Eq(x**2, 1), x)) == {-S.One, S.One}
assert solve(x - y**3, x) == [y**3]
rx = root(x, 3)
assert solve(x - y**3, y) == [
rx, -rx/2 - sqrt(3)*I*rx/2, -rx/2 + sqrt(3)*I*rx/2]
a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2')
assert solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) == \
{
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
}
solution = {y: S.Zero, x: S.Zero}
assert solve((x - y, x + y), x, y ) == solution
assert solve((x - y, x + y), (x, y)) == solution
assert solve((x - y, x + y), [x, y]) == solution
assert set(solve(x**3 - 15*x - 4, x)) == {
-2 + 3**S.Half,
S(4),
-2 - 3**S.Half
}
assert set(solve((x**2 - 1)**2 - a, x)) == \
{sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)),
sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))}
def test_solve_polynomial2():
assert solve(4, x) == []
def test_solve_polynomial_cv_1a():
"""
Test for solving on equations that can be converted to a polynomial equation
using the change of variable y -> x**Rational(p, q)
"""
assert solve( sqrt(x) - 1, x) == [1]
assert solve( sqrt(x) - 2, x) == [4]
assert solve( x**Rational(1, 4) - 2, x) == [16]
assert solve( x**Rational(1, 3) - 3, x) == [27]
assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0]
def test_solve_polynomial_cv_1b():
assert set(solve(4*x*(1 - a*sqrt(x)), x)) == {S.Zero, 1/a**2}
assert set(solve(x*(root(x, 3) - 3), x)) == {S.Zero, S(27)}
def test_solve_polynomial_cv_2():
"""
Test for solving on equations that can be converted to a polynomial equation
multiplying both sides of the equation by x**m
"""
assert solve(x + 1/x - 1, x) in \
[[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2],
[ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]]
def test_quintics_1():
f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
# if one uses solve to get the roots of a polynomial that has a CRootOf
# solution, make sure that the use of nfloat during the solve process
# doesn't fail. Note: if you want numerical solutions to a polynomial
# it is *much* faster to use nroots to get them than to solve the
# equation only to get RootOf solutions which are then numerically
# evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather
# than [i.n() for i in solve(eq)] to get the numerical roots of eq.
assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \
CRootOf(x**5 + 3*x**3 + 7, 0).n()
def test_quintics_2():
f = x**5 + 15*x + 12
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)]
def test_highorder_poly():
# just testing that the uniq generator is unpacked
sol = solve(x**6 - 2*x + 2)
assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6
def test_solve_rational():
"""Test solve for rational functions"""
assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3]
def test_solve_nonlinear():
assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}]
assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))},
{y: x*sqrt(exp(x))}]
def test_issue_8666():
x = symbols('x')
assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == []
assert solve(Eq(x + 1/x, 1/x), x) == []
def test_issue_7228():
assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half]
def test_issue_7190():
assert solve(log(x-3) + log(x+3), x) == [sqrt(10)]
def test_linear_system():
x, y, z, t, n = symbols('x, y, z, t, n')
assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == []
assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == []
assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == []
assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1}
M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0],
[n + 1, n + 1, -2*n - 1, -(n + 1), 0],
[-1, 0, 1, 0, 0]])
assert solve_linear_system(M, x, y, z, t) == \
{x: t*(-n-1)/n, z: t*(-n-1)/n, y: 0}
assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t}
@XFAIL
def test_linear_system_xfail():
# https://github.com/sympy/sympy/issues/6420
M = Matrix([[0, 15.0, 10.0, 700.0],
[1, 1, 1, 100.0],
[0, 10.0, 5.0, 200.0],
[-5.0, 0, 0, 0 ]])
assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0}
def test_linear_system_function():
a = Function('a')
assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)],
a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)}
def test_linear_system_symbols_doesnt_hang_1():
def _mk_eqs(wy):
# Equations for fitting a wy*2 - 1 degree polynomial between two points,
# at end points derivatives are known up to order: wy - 1
order = 2*wy - 1
x, x0, x1 = symbols('x, x0, x1', real=True)
y0s = symbols('y0_:{}'.format(wy), real=True)
y1s = symbols('y1_:{}'.format(wy), real=True)
c = symbols('c_:{}'.format(order+1), real=True)
expr = sum([coeff*x**o for o, coeff in enumerate(c)])
eqs = []
for i in range(wy):
eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i])
eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i])
return eqs, c
#
# The purpose of this test is just to see that these calls don't hang. The
# expressions returned are complicated so are not included here. Testing
# their correctness takes longer than solving the system.
#
for n in range(1, 7+1):
eqs, c = _mk_eqs(n)
solve(eqs, c)
def test_linear_system_symbols_doesnt_hang_2():
M = Matrix([
[66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76],
[10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78],
[19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3],
[74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6],
[69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81],
[50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35],
[58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39],
[42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24],
[ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13],
[19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51],
[29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40],
[15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37],
[62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45],
[ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50],
[40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32],
[33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1],
[97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96],
[40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52],
[38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]])
syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19')
sol = {
x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588,
x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147,
x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294,
x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176,
x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528,
x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764,
x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588,
x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063,
x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176,
x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528,
x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528,
x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882,
x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882,
x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176,
x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168,
x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176,
x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764,
x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176,
x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528
}
eqs = list(M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
y = Symbol('y')
eqs = list(y * M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
def test_linear_systemLU():
n = Symbol('n')
M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]])
assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n),
x: 1 - 12*n/(n**2 + 18*n),
y: 6*n/(n**2 + 18*n)}
# Note: multiple solutions exist for some of these equations, so the tests
# should be expected to break if the implementation of the solver changes
# in such a way that a different branch is chosen
@slow
def test_solve_transcendental():
from sympy.abc import a, b
assert solve(exp(x) - 3, x) == [log(3)]
assert set(solve((a*x + b)*(exp(x) - 3), x)) == {-b/a, log(3)}
assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)]
assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)]
assert solve(Eq(cos(x), sin(x)), x) == [pi/4]
assert set(solve(exp(x) + exp(-x) - y, x)) in [{
log(y/2 - sqrt(y**2 - 4)/2),
log(y/2 + sqrt(y**2 - 4)/2),
}, {
log(y - sqrt(y**2 - 4)) - log(2),
log(y + sqrt(y**2 - 4)) - log(2)},
{
log(y/2 - sqrt((y - 2)*(y + 2))/2),
log(y/2 + sqrt((y - 2)*(y + 2))/2)}]
assert solve(exp(x) - 3, x) == [log(3)]
assert solve(Eq(exp(x), 3), x) == [log(3)]
assert solve(log(x) - 3, x) == [exp(3)]
assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)]
assert solve(3**(x + 2), x) == []
assert solve(3**(2 - x), x) == []
assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)]
assert solve(2*x + 5 + log(3*x - 2), x) == \
[Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2]
assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3]
assert set(solve((2*x + 8)*(8 + exp(x)), x)) == {S(-4), log(8) + pi*I}
eq = 2*exp(3*x + 4) - 3
ans = solve(eq, x) # this generated a failure in flatten
assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3]
assert solve(exp(x) + 1, x) == [pi*I]
eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9)
result = solve(eq, x)
ans = [(log(2401) + 5*LambertW((-1 + sqrt(5) + sqrt(2)*I*sqrt(sqrt(5) + \
5))*log(7**(7*3**Rational(1, 5)/20))* -1))/(-3*log(7)), \
(log(2401) + 5*LambertW((1 + sqrt(5) - sqrt(2)*I*sqrt(5 - \
sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW((1 + sqrt(5) + sqrt(2)*I*sqrt(5 - \
sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW((-sqrt(5) + 1 + sqrt(2)*I*sqrt(sqrt(5) + \
5))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(-3*log(7))]
assert result == ans
# it works if expanded, too
assert solve(eq.expand(), x) == result
assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)]
assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2]
assert solve(z*cos(sin(x)) - y, x) == [
pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi,
-asin(acos(y/z) - 2*pi), asin(acos(y/z))]
assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)]
# issue 4508
assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]]
assert solve(y - b*exp(a/x), x) == [a/log(y/b)]
# issue 4507
assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]]
# issue 4506
assert solve(y - a*x**b, x) == [(y/a)**(1/b)]
# issue 4505
assert solve(z**x - y, x) == [log(y)/log(z)]
# issue 4504
assert solve(2**x - 10, x) == [1 + log(5)/log(2)]
# issue 6744
assert solve(x*y) == [{x: 0}, {y: 0}]
assert solve([x*y]) == [{x: 0}, {y: 0}]
assert solve(x**y - 1) == [{x: 1}, {y: 0}]
assert solve([x**y - 1]) == [{x: 1}, {y: 0}]
assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
# issue 4739
assert solve(exp(log(5)*x) - 2**x, x) == [0]
# issue 14791
assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0]
f = Function('f')
assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0]
assert solve(f(x) - f(0), x) == [0]
assert solve(f(x) - f(2 - x), x) == [1]
raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x))
raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x))
raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x))
raises(ValueError, lambda: solve(f(x, y) - f(1), x))
# misc
# make sure that the right variables is picked up in tsolve
# shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated
# for eq_down. Actual answers, as determined numerically are approx. +/- 0.83
raises(NotImplementedError, lambda:
solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3))
# watch out for recursive loop in tsolve
raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x))
# issue 7245
assert solve(sin(sqrt(x))) == [0, pi**2]
# issue 7602
a, b = symbols('a, b', real=True, negative=False)
assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \
'[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]'
# issue 15325
assert solve(y**(1/x) - z, x) == [log(y)/log(z)]
def test_solve_for_functions_derivatives():
t = Symbol('t')
x = Function('x')(t)
y = Function('y')(t)
a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2')
soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y)
assert soln == {
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
}
assert solve(x - 1, x) == [1]
assert solve(3*x - 2, x) == [Rational(2, 3)]
soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) +
a22*y.diff(t) - b2], x.diff(t), y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
assert solve(x.diff(t) - 1, x.diff(t)) == [1]
assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)]
eqns = {3*x - 1, 2*y - 4}
assert solve(eqns, {x, y}) == { x: Rational(1, 3), y: 2 }
x = Symbol('x')
f = Function('f')
F = x**2 + f(x)**2 - 4*x - 1
assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)]
# Mixed cased with a Symbol and a Function
x = Symbol('x')
y = Function('y')(t)
soln = solve([a11*x + a12*y.diff(t) - b1, a21*x +
a22*y.diff(t) - b2], x, y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
# issue 13263
x = Symbol('x')
f = Function('f')
soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)],
f(x).diff(x), f(x).diff(x, 2))
assert soln == { f(x).diff(x, 2): 1/2, f(x).diff(x): 1/2 }
soln = solve([f(x).diff(x, 2) + f(x).diff(x, 3) - 1, 1 - f(x).diff(x, 2) -
f(x).diff(x, 3), 1 - f(x).diff(x,3)], f(x).diff(x, 2), f(x).diff(x, 3))
assert soln == { f(x).diff(x, 2): 0, f(x).diff(x, 3): 1 }
def test_issue_3725():
f = Function('f')
F = x**2 + f(x)**2 - 4*x - 1
e = F.diff(x)
assert solve(e, f(x).diff(x)) in [[(2 - x)/f(x)], [-((x - 2)/f(x))]]
def test_issue_3870():
a, b, c, d = symbols('a b c d')
A = Matrix(2, 2, [a, b, c, d])
B = Matrix(2, 2, [0, 2, -3, 0])
C = Matrix(2, 2, [1, 2, 3, 4])
assert solve(A*B - C, [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve([A*B - C], [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve(Eq(A*B, C), [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve([A*B - B*A], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c}
assert solve([A*C - C*A], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c}
assert solve([A*B - B*A, A*C - C*A], [a, b, c, d]) == {a: d, b: 0, c: 0}
assert solve([Eq(A*B, B*A)], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c}
assert solve([Eq(A*C, C*A)], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c}
assert solve([Eq(A*B, B*A), Eq(A*C, C*A)], [a, b, c, d]) == {a: d, b: 0, c: 0}
def test_solve_linear():
w = Wild('w')
assert solve_linear(x, x) == (0, 1)
assert solve_linear(x, exclude=[x]) == (0, 1)
assert solve_linear(x, symbols=[w]) == (0, 1)
assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)]
assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x)
assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)]
assert solve_linear(3*x - y, 0, [x]) == (x, y/3)
assert solve_linear(3*x - y, 0, [y]) == (y, 3*x)
assert solve_linear(x**2/y, 1) == (y, x**2)
assert solve_linear(w, x) in [(w, x), (x, w)]
assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y) == \
(y, -2 - cos(x)**2 - sin(x)**2)
assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1)
assert solve_linear(Eq(x, 3)) == (x, 3)
assert solve_linear(1/(1/x - 2)) == (0, 0)
assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1)
assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1)
assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0)
assert solve_linear(0**x - 1) == (0**x - 1, 1)
assert solve_linear(1 + 1/(x - 1)) == (x, 0)
eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
assert solve_linear(eq) == (0, 1)
eq = cos(x)**2 + sin(x)**2 # = 1
assert solve_linear(eq) == (0, 1)
raises(ValueError, lambda: solve_linear(Eq(x, 3), 3))
def test_solve_undetermined_coeffs():
assert solve_undetermined_coeffs(a*x**2 + b*x**2 + b*x + 2*c*x + c + 1, [a, b, c], x) == \
{a: -2, b: 2, c: -1}
# Test that rational functions work
assert solve_undetermined_coeffs(a/x + b/(x + 1) - (2*x + 1)/(x**2 + x), [a, b], x) == \
{a: 1, b: 1}
# Test cancellation in rational functions
assert solve_undetermined_coeffs(((c + 1)*a*x**2 + (c + 1)*b*x**2 +
(c + 1)*b*x + (c + 1)*2*c*x + (c + 1)**2)/(c + 1), [a, b, c], x) == \
{a: -2, b: 2, c: -1}
def test_solve_inequalities():
x = Symbol('x')
sol = And(S.Zero < x, x < oo)
assert solve(x + 1 > 1) == sol
assert solve([x + 1 > 1]) == sol
assert solve([x + 1 > 1], x) == sol
assert solve([x + 1 > 1], [x]) == sol
system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]
assert solve(system) == \
And(Or(And(Lt(-sqrt(2), x), Lt(x, -1)),
And(Lt(1, x), Lt(x, sqrt(2)))), Eq(0, 0))
x = Symbol('x', real=True)
system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]
assert solve(system) == \
Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2))))
# issues 6627, 3448
assert solve((x - 3)/(x - 2) < 0, x) == And(Lt(2, x), Lt(x, 3))
assert solve(x/(x + 1) > 1, x) == And(Lt(-oo, x), Lt(x, -1))
assert solve(sin(x) > S.Half) == And(pi/6 < x, x < pi*Rational(5, 6))
assert solve(Eq(False, x < 1)) == (S.One <= x) & (x < oo)
assert solve(Eq(True, x < 1)) == (-oo < x) & (x < 1)
assert solve(Eq(x < 1, False)) == (S.One <= x) & (x < oo)
assert solve(Eq(x < 1, True)) == (-oo < x) & (x < 1)
assert solve(Eq(False, x)) == False
assert solve(Eq(0, x)) == [0]
assert solve(Eq(True, x)) == True
assert solve(Eq(1, x)) == [1]
assert solve(Eq(False, ~x)) == True
assert solve(Eq(True, ~x)) == False
assert solve(Ne(True, x)) == False
assert solve(Ne(1, x)) == (x > -oo) & (x < oo) & Ne(x, 1)
def test_issue_4793():
assert solve(1/x) == []
assert solve(x*(1 - 5/x)) == [5]
assert solve(x + sqrt(x) - 2) == [1]
assert solve(-(1 + x)/(2 + x)**2 + 1/(2 + x)) == []
assert solve(-x**2 - 2*x + (x + 1)**2 - 1) == []
assert solve((x/(x + 1) + 3)**(-2)) == []
assert solve(x/sqrt(x**2 + 1), x) == [0]
assert solve(exp(x) - y, x) == [log(y)]
assert solve(exp(x)) == []
assert solve(x**2 + x + sin(y)**2 + cos(y)**2 - 1, x) in [[0, -1], [-1, 0]]
eq = 4*3**(5*x + 2) - 7
ans = solve(eq, x)
assert len(ans) == 5 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
assert solve(log(x**2) - y**2/exp(x), x, y, set=True) == (
[x, y],
{(x, sqrt(exp(x) * log(x ** 2))), (x, -sqrt(exp(x) * log(x ** 2)))})
assert solve(x**2*z**2 - z**2*y**2) == [{x: -y}, {x: y}, {z: 0}]
assert solve((x - 1)/(1 + 1/(x - 1))) == []
assert solve(x**(y*z) - x, x) == [1]
raises(NotImplementedError, lambda: solve(log(x) - exp(x), x))
raises(NotImplementedError, lambda: solve(2**x - exp(x) - 3))
def test_PR1964():
# issue 5171
assert solve(sqrt(x)) == solve(sqrt(x**3)) == [0]
assert solve(sqrt(x - 1)) == [1]
# issue 4462
a = Symbol('a')
assert solve(-3*a/sqrt(x), x) == []
# issue 4486
assert solve(2*x/(x + 2) - 1, x) == [2]
# issue 4496
assert set(solve((x**2/(7 - x)).diff(x))) == {S.Zero, S(14)}
# issue 4695
f = Function('f')
assert solve((3 - 5*x/f(x))*f(x), f(x)) == [x*Rational(5, 3)]
# issue 4497
assert solve(1/root(5 + x, 5) - 9, x) == [Rational(-295244, 59049)]
assert solve(sqrt(x) + sqrt(sqrt(x)) - 4) == [(Rational(-1, 2) + sqrt(17)/2)**4]
assert set(solve(Poly(sqrt(exp(x)) + sqrt(exp(-x)) - 4))) in \
[
{log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)},
{2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)},
{log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)},
]
assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \
{log(-sqrt(3) + 2), log(sqrt(3) + 2)}
assert set(solve(x**y + x**(2*y) - 1, x)) == \
{(Rational(-1, 2) + sqrt(5)/2)**(1/y), (Rational(-1, 2) - sqrt(5)/2)**(1/y)}
assert solve(exp(x/y)*exp(-z/y) - 2, y) == [(x - z)/log(2)]
assert solve(
x**z*y**z - 2, z) in [[log(2)/(log(x) + log(y))], [log(2)/(log(x*y))]]
# if you do inversion too soon then multiple roots (as for the following)
# will be missed, e.g. if exp(3*x) = exp(3) -> 3*x = 3
E = S.Exp1
assert solve(exp(3*x) - exp(3), x) in [
[1, log(E*(Rational(-1, 2) - sqrt(3)*I/2)), log(E*(Rational(-1, 2) + sqrt(3)*I/2))],
[1, log(-E/2 - sqrt(3)*E*I/2), log(-E/2 + sqrt(3)*E*I/2)],
]
# coverage test
p = Symbol('p', positive=True)
assert solve((1/p + 1)**(p + 1)) == []
def test_issue_5197():
x = Symbol('x', real=True)
assert solve(x**2 + 1, x) == []
n = Symbol('n', integer=True, positive=True)
assert solve((n - 1)*(n + 2)*(2*n - 1), n) == [1]
x = Symbol('x', positive=True)
y = Symbol('y')
assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == []
# not {x: -3, y: 1} b/c x is positive
# The solution following should not contain (-sqrt(2), sqrt(2))
assert solve((x + y)*n - y**2 + 2, x, y) == [(sqrt(2), -sqrt(2))]
y = Symbol('y', positive=True)
# The solution following should not contain {y: -x*exp(x/2)}
assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: x*exp(x/2)}]
x, y, z = symbols('x y z', positive=True)
assert solve(z**2*x**2 - z**2*y**2/exp(x), y, x, z, dict=True) == [{y: x*exp(x/2)}]
def test_checking():
assert set(
solve(x*(x - y/x), x, check=False)) == {sqrt(y), S.Zero, -sqrt(y)}
assert set(solve(x*(x - y/x), x, check=True)) == {sqrt(y), -sqrt(y)}
# {x: 0, y: 4} sets denominator to 0 in the following so system should return None
assert solve((1/(1/x + 2), 1/(y - 3) - 1)) == []
# 0 sets denominator of 1/x to zero so None is returned
assert solve(1/(1/x + 2)) == []
def test_issue_4671_4463_4467():
assert solve(sqrt(x**2 - 1) - 2) in ([sqrt(5), -sqrt(5)],
[-sqrt(5), sqrt(5)])
assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == [
-sqrt(x*log(1 + I*pi/log(2))), sqrt(x*log(1 + I*pi/log(2)))]
C1, C2 = symbols('C1 C2')
f = Function('f')
assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))]
a = Symbol('a')
E = S.Exp1
assert solve(1 - log(a + 4*x**2), x) in (
[-sqrt(-a + E)/2, sqrt(-a + E)/2],
[sqrt(-a + E)/2, -sqrt(-a + E)/2]
)
assert solve(log(a**(-3) - x**2)/a, x) in (
[-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))],
[sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],)
assert solve(1 - log(a + 4*x**2), x) in (
[-sqrt(-a + E)/2, sqrt(-a + E)/2],
[sqrt(-a + E)/2, -sqrt(-a + E)/2],)
assert solve((a**2 + 1)*(sin(a*x) + cos(a*x)), x) == [-pi/(4*a)]
assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [log(3)/a]
assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \
{log(-2 + sqrt(5))/a, log(-sqrt(2) + 1)/a,
log(-sqrt(5) - 2)/a, log(1 + sqrt(2))/a}
assert solve(atan(x) - 1) == [tan(1)]
def test_issue_5132():
r, t = symbols('r,t')
assert set(solve([r - x**2 - y**2, tan(t) - y/x], [x, y])) == \
{(
-sqrt(r*cos(t)**2), -1*sqrt(r*cos(t)**2)*tan(t)),
(sqrt(r*cos(t)**2), sqrt(r*cos(t)**2)*tan(t))}
assert solve([exp(x) - sin(y), 1/y - 3], [x, y]) == \
[(log(sin(Rational(1, 3))), Rational(1, 3))]
assert solve([exp(x) - sin(y), 1/exp(y) - 3], [x, y]) == \
[(log(-sin(log(3))), -log(3))]
assert set(solve([exp(x) - sin(y), y**2 - 4], [x, y])) == \
{(log(-sin(2)), -S(2)), (log(sin(2)), S(2))}
eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3]
assert solve(eqs, set=True) == \
([x, y], {
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))})
assert solve(eqs, x, z, set=True) == (
[x, z],
{(log(-z**2 + sin(y))/2, z), (log(-sqrt(-z**2 + sin(y))), z)})
assert set(solve(eqs, x, y)) == \
{
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))}
assert set(solve(eqs, y, z)) == \
{
(-log(3), -sqrt(-exp(2*x) - sin(log(3)))),
(-log(3), sqrt(-exp(2*x) - sin(log(3))))}
eqs = [exp(x)**2 - sin(y) + z, 1/exp(y) - 3]
assert solve(eqs, set=True) == ([x, y], {
(log(-sqrt(-z - sin(log(3)))), -log(3)),
(log(-z - sin(log(3)))/2, -log(3))})
assert solve(eqs, x, z, set=True) == (
[x, z],
{(log(-sqrt(-z + sin(y))), z), (log(-z + sin(y))/2, z)})
assert set(solve(eqs, x, y)) == {
(log(-sqrt(-z - sin(log(3)))), -log(3)),
(log(-z - sin(log(3)))/2, -log(3))}
assert solve(eqs, z, y) == \
[(-exp(2*x) - sin(log(3)), -log(3))]
assert solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), set=True) == (
[x, y], {(S.One, S(3)), (S(3), S.One)})
assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \
{(S.One, S(3)), (S(3), S.One)}
def test_issue_5335():
lam, a0, conc = symbols('lam a0 conc')
a = 0.005
b = 0.743436700916726
eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x,
a0*(1 - x/2)*x - 1*y - b*y,
x + y - conc]
sym = [x, y, a0]
# there are 4 solutions obtained manually but only two are valid
assert len(solve(eqs, sym, manual=True, minimal=True)) == 2
assert len(solve(eqs, sym)) == 2 # cf below with rational=False
@SKIP("Hangs")
def _test_issue_5335_float():
# gives ZeroDivisionError: polynomial division
lam, a0, conc = symbols('lam a0 conc')
a = 0.005
b = 0.743436700916726
eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x,
a0*(1 - x/2)*x - 1*y - b*y,
x + y - conc]
sym = [x, y, a0]
assert len(solve(eqs, sym, rational=False)) == 2
def test_issue_5767():
assert set(solve([x**2 + y + 4], [x])) == \
{(-sqrt(-y - 4),), (sqrt(-y - 4),)}
def test_polysys():
assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \
{(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)),
(1 - sqrt(5), 2 + sqrt(5))}
assert solve([x**2 + y - 2, x**2 + y]) == []
# the ordering should be whatever the user requested
assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 +
y - 3, x - y - 4], (y, x))
@slow
def test_unrad1():
raises(NotImplementedError, lambda:
unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
raises(NotImplementedError, lambda:
unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y)))
s = symbols('s', cls=Dummy)
# checkers to deal with possibility of answer coming
# back with a sign change (cf issue 5203)
def check(rv, ans):
assert bool(rv[1]) == bool(ans[1])
if ans[1]:
return s_check(rv, ans)
e = rv[0].expand()
a = ans[0].expand()
return e in [a, -a] and rv[1] == ans[1]
def s_check(rv, ans):
# get the dummy
rv = list(rv)
d = rv[0].atoms(Dummy)
reps = list(zip(d, [s]*len(d)))
# replace s with this dummy
rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)])
ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)])
return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
str(rv[1]) == str(ans[1])
assert check(unrad(sqrt(x)),
(x, []))
assert check(unrad(sqrt(x) + 1),
(x - 1, []))
assert check(unrad(sqrt(x) + root(x, 3) + 2),
(s**3 + s**2 + 2, [s, s**6 - x]))
assert check(unrad(sqrt(x)*root(x, 3) + 2),
(x**5 - 64, []))
assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
(x**3 - (x + 1)**2, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)),
(-2*sqrt(2)*x - 2*x + 1, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + 2),
(16*x - 9, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
(5*x**2 - 4*x, []))
assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)),
((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, []))
assert check(unrad(sqrt(x) + sqrt(1 - x)),
(2*x - 1, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
(x**2 - x + 16, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
(5*x**2 - 2*x + 1, []))
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [
(25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []),
(25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])]
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \
(41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487
assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, []))
eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
assert check(unrad(eq),
(16*x**2 - 9*x, []))
assert set(solve(eq, check=False)) == {S.Zero, Rational(9, 16)}
assert solve(eq) == []
# but this one really does have those solutions
assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \
{S.Zero, Rational(9, 16)}
assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y),
(S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), []))
assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)),
(x**5 - x**4 - x**3 + 2*x**2 + x - 1, []))
assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y),
(4*x*y + x - 4*y, []))
assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x),
(x**2 - x + 4, []))
# http://tutorial.math.lamar.edu/
# Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
assert solve(Eq(x, sqrt(x + 6))) == [3]
assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
assert solve(Eq(1, x + sqrt(2*x - 3))) == []
assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == {-S.One, S(2)}
assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {S(5), S(13)}
assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
# http://www.purplemath.com/modules/solverad.htm
assert solve((2*x - 5)**Rational(1, 3) - 3) == [16]
assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \
{Rational(-1, 2), Rational(-1, 3)}
assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-S(8), S(2)}
assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5]
assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16]
assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0]
assert solve(sqrt(x) - 2 - 5) == [49]
assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
assert solve(sqrt(x - 1) - x + 7) == [10]
assert solve(sqrt(x - 2) - 5) == [27]
assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3]
assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []
# don't posify the expression in unrad and do use _mexpand
z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x)
p = posify(z)[0]
assert solve(p) == []
assert solve(z) == []
assert solve(z + 6*I) == [Rational(-1, 11)]
assert solve(p + 6*I) == []
# issue 8622
assert unrad(root(x + 1, 5) - root(x, 3)) == (
x**5 - x**3 - 3*x**2 - 3*x - 1, [])
# issue #8679
assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x),
(s**3 + s**2 + s + sqrt(y), [s, s**3 - x]))
# for coverage
assert check(unrad(sqrt(x) + root(x, 3) + y),
(s**3 + s**2 + y, [s, s**6 - x]))
assert solve(sqrt(x) + root(x, 3) - 2) == [1]
raises(NotImplementedError, lambda:
solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2))
# fails through a different code path
raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x))
# unrad some
assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [
x + (x**Rational(1, 3) + x)**Rational(5, 2)]
assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2),
(s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 -
192*s - 56, [s, s**2 - x]))
e = root(x + 1, 3) + root(x, 3)
assert unrad(e) == (2*x + 1, [])
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
(15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, []))
assert check(unrad(root(x, 4) + root(x, 4)**3 - 1),
(s**3 + s - 1, [s, s**4 - x]))
assert check(unrad(root(x, 2) + root(x, 2)**3 - 1),
(x**3 + 2*x**2 + x - 1, []))
assert unrad(x**0.5) is None
assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3),
(s**3 + s + t, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y),
(s**3 + s + x, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x),
(s**5 + s**3 + s - y, [s, s**5 - x - y]))
assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)),
(s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 +
10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1]))
raises(NotImplementedError, lambda:
unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1)))
# the simplify flag should be reset to False for unrad results;
# if it's not then this next test will take a long time
assert solve(root(x, 3) + root(x, 5) - 2) == [1]
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), []))
ans = S('''
[4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 +
12459439/52734375)**(1/3)) +
4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''')
assert solve(eq) == ans
# duplicate radical handling
assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2),
(s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1]))
# cov post-processing
e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2
assert check(unrad(e),
(s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30,
[s, s**3 - x**2 - 1]))
e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2
assert check(unrad(e),
(s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25,
[s, s**3 - x - 1]))
assert check(unrad(e, _reverse=True),
(s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89,
[s, s**2 - x - sqrt(x + 1)]))
# this one needs r0, r1 reversal to work
assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2),
(s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 +
32*s + 17, [s, s**6 - x]))
# is this needed?
#assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == (
# x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5, [])
raises(NotImplementedError, lambda:
unrad(sqrt(cosh(x)/x) + root(x + 1,3)*sqrt(x) - 1))
assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None
assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x),
(s**(2*y) + s + 1, [s, s**3 - x - y]))
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests that the use of
# composite
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
# watch out for when the cov doesn't involve the symbol of interest
eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1')
assert solve(eq, y) == [
4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 - (Rational(-1, 2) -
sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) - Rational(13824, 343))**2)/2 -
Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 -
(Rational(-1, 2) + sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) -
Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x +
27*sqrt(x**2))**Rational(1, 3)/21 - (x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) -
Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3]
eq = root(x + 1, 3) - (root(x, 3) + root(x, 5))
assert check(unrad(eq),
(3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x]))
assert check(unrad(eq - 2),
(3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 +
12*s**3 + 7, [s, s**15 - x]))
assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)),
(4096*s**13 + 960*s**12 + 48*s**11 - s**10 - 1728*s**4,
[s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389
assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2),
(343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 -
3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x -
1])) # orig expr has one real root: -0.048
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)),
(729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 -
3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x -
1])) # orig expr has 2 real roots: -0.91, -0.15
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2),
(729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 +
453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3
- 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1]))
# orig expr has 1 real root: 19.53
ans = solve(sqrt(x) + sqrt(x + 1) -
sqrt(1 - x) - sqrt(2 + x))
assert len(ans) == 1 and NS(ans[0])[:4] == '0.73'
# the fence optimization problem
# https://github.com/sympy/sympy/issues/4793#issuecomment-36994519
F = Symbol('F')
eq = F - (2*x + 2*y + sqrt(x**2 + y**2))
ans = F*Rational(2, 7) - sqrt(2)*F/14
X = solve(eq, x, check=False)
for xi in reversed(X): # reverse since currently, ans is the 2nd one
Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False)
if any((a - ans).expand().is_zero for a in Y):
break
else:
assert None # no answer was found
assert solve(sqrt(x + 1) + root(x, 3) - 2) == S('''
[(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 +
sqrt(93)/6)**(1/3))**3]''')
assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S('''
[(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 +
sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 +
sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 +
sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 +
sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''')
assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S('''
[(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) +
2)**2]''')
eq = S('''
-x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3
+ x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 -
sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2
- 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''')
assert check(unrad(eq),
(-s*(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 +
51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 +
1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 +
471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 -
165240*x + 61484) + 810]))
assert solve(eq) == [] # not other code errors
eq = root(x, 3) - root(y, 3) + root(x, 5)
assert check(unrad(eq),
(s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x]))
eq = root(x, 3) + root(y, 3) + root(x*y, 4)
assert check(unrad(eq),
(s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 -
3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 -
3*s**3*y**5 - y**6), [s, s**4 - x*y]))
raises(NotImplementedError,
lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5)))
# Test unrad with an Equality
eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5))
assert check(unrad(eq),
(-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x]))
@slow
def test_unrad_slow():
# this has roots with multiplicity > 1; there should be no
# repeats in roots obtained, however
eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*(1 + sqrt(1 + 2*sqrt(1 - 4*x**2))))
assert solve(eq) == [S.Half]
@XFAIL
def test_unrad_fail():
# this only works if we check real_root(eq.subs(x, Rational(1, 3)))
# but checksol doesn't work like that
assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)]
assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [
-1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3]
def test_checksol():
x, y, r, t = symbols('x, y, r, t')
eq = r - x**2 - y**2
dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1),
x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)}
assert checksol(eq, dict_var_soln) == True
assert checksol(Eq(x, False), {x: False}) is True
assert checksol(Ne(x, False), {x: False}) is False
assert checksol(Eq(x < 1, True), {x: 0}) is True
assert checksol(Eq(x < 1, True), {x: 1}) is False
assert checksol(Eq(x < 1, False), {x: 1}) is True
assert checksol(Eq(x < 1, False), {x: 0}) is False
assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True
assert checksol([x - 1, x**2 - 1], x, 1) is True
assert checksol([x - 1, x**2 - 2], x, 1) is False
assert checksol(Poly(x**2 - 1), x, 1) is True
raises(ValueError, lambda: checksol(x, 1))
raises(ValueError, lambda: checksol([], x, 1))
def test__invert():
assert _invert(x - 2) == (2, x)
assert _invert(2) == (2, 0)
assert _invert(exp(1/x) - 3, x) == (1/log(3), x)
assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x)
assert _invert(a, x) == (a, 0)
def test_issue_4463():
assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)]
assert solve(x**x) == []
assert solve(x**x - 2) == [exp(LambertW(log(2)))]
assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2]
@slow
def test_issue_5114_solvers():
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r')
# there is no 'a' in the equation set but this is how the
# problem was originally posed
syms = a, b, c, f, h, k, n
eqs = [b + r/d - c/d,
c*(1/d + 1/e + 1/g) - f/g - r/d,
f*(1/g + 1/i + 1/j) - c/g - h/i,
h*(1/i + 1/l + 1/m) - f/i - k/m,
k*(1/m + 1/o + 1/p) - h/m - n/p,
n*(1/p + 1/q) - k/p]
assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1
def test_issue_5849():
I1, I2, I3, I4, I5, I6 = symbols('I1:7')
dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')
e = (
I1 - I2 - I3,
I3 - I4 - I5,
I4 + I5 - I6,
-I1 + I2 + I6,
-2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
-I4 + dQ4,
-I2 + dQ2,
2*I3 + 2*I5 + 3*I6 - Q2,
I4 - 2*I5 + 2*Q4 + dI4
)
ans = [{
I1: I2 + I6,
dI1: -4*I2 - 4*I3 - 4*I5 - 10*I6 + 24,
I4: -I5 + I6,
dQ4: -I5 + I6,
Q4: 3*I5/2 - I6/2 - dI4/2,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6}]
v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4
assert solve(e, *v, manual=True, check=False, dict=True) == ans
assert solve(e, *v, manual=True) == ans[0]
# the matrix solver (tested below) doesn't like this because it produces
# a zero row in the matrix. Is this related to issue 4551?
assert [ei.subs(
ans[0]) for ei in e] == [-I3 + I6, I3 - I6, 0, 0, 0, 0, 0, 0, 0]
def test_issue_5849_matrix():
'''Same as test_issue_5849 but solved with the matrix solver.
A solution only exists if I3 == I6 which is not generically true,
but `solve` does not return conditions under which the solution is
valid, only a solution that is canonical and consistent with the input.
'''
# a simple example with the same issue
# assert solve([x+y+z, x+y], [x, y]) == {x: y}
# the longer example
I1, I2, I3, I4, I5, I6 = symbols('I1:7')
dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')
e = (
I1 - I2 - I3,
I3 - I4 - I5,
I4 + I5 - I6,
-I1 + I2 + I6,
-2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
-I4 + dQ4,
-I2 + dQ2,
2*I3 + 2*I5 + 3*I6 - Q2,
I4 - 2*I5 + 2*Q4 + dI4
)
assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4) == {
I1: I2 + I6,
dI1: -4*I2 - 4*I3 - 4*I5 - 10*I6 + 24,
I4: -I5 + I6,
dQ4: -I5 + I6,
Q4: 3*I5/2 - I6/2 - dI4/2,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6}
def test_issue_5901():
f, g, h = map(Function, 'fgh')
a = Symbol('a')
D = Derivative(f(x), x)
G = Derivative(g(a), a)
assert solve(f(x) + f(x).diff(x), f(x)) == \
[-D]
assert solve(f(x) - 3, f(x)) == \
[3]
assert solve(f(x) - 3*f(x).diff(x), f(x)) == \
[3*D]
assert solve([f(x) - 3*f(x).diff(x)], f(x)) == \
{f(x): 3*D}
assert solve([f(x) - 3*f(x).diff(x), f(x)**2 - y + 4], f(x), y) == \
[{f(x): 3*D, y: 9*D**2 + 4}]
assert solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a),
h(a), g(a), set=True) == \
([g(a)], {
(-sqrt(h(a)**2*f(a)**2 + G)/f(a),),
(sqrt(h(a)**2*f(a)**2+ G)/f(a),)})
args = [f(x).diff(x, 2)*(f(x) + g(x)) - g(x)**2 + 2, f(x), g(x)]
assert set(solve(*args)) == \
{(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}
eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4]
assert solve(eqs, f(x), g(x), set=True) == \
([f(x), g(x)], {
(-sqrt(2*D - 2), S(2)),
(sqrt(2*D - 2), S(2)),
(-sqrt(2*D + 2), -S(2)),
(sqrt(2*D + 2), -S(2))})
# the underlying problem was in solve_linear that was not masking off
# anything but a Mul or Add; it now raises an error if it gets anything
# but a symbol and solve handles the substitutions necessary so solve_linear
# won't make this error
raises(
ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)]))
assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \
(f(x) + Derivative(f(x), x), 1)
assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \
(f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x + f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x, -f(y) - Integral(x, (x, y)))
assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \
(x, 1/a)
assert solve_linear(x + Derivative(2*x, x)) == \
(x, -2)
assert solve_linear(x + Integral(x, y), symbols=[x]) == \
(x, 0)
assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \
(x, 2/(y + 1))
assert set(solve(x + exp(x)**2, exp(x))) == \
{-sqrt(-x), sqrt(-x)}
assert solve(x + exp(x), x, implicit=True) == \
[-exp(x)]
assert solve(cos(x) - sin(x), x, implicit=True) == []
assert solve(x - sin(x), x, implicit=True) == \
[sin(x)]
assert solve(x**2 + x - 3, x, implicit=True) == \
[-x**2 + 3]
assert solve(x**2 + x - 3, x**2, implicit=True) == \
[-x + 3]
def test_issue_5912():
assert set(solve(x**2 - x - 0.1, rational=True)) == \
{S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half}
ans = solve(x**2 - x - 0.1, rational=False)
assert len(ans) == 2 and all(a.is_Number for a in ans)
ans = solve(x**2 - x - 0.1)
assert len(ans) == 2 and all(a.is_Number for a in ans)
def test_float_handling():
def test(e1, e2):
return len(e1.atoms(Float)) == len(e2.atoms(Float))
assert solve(x - 0.5, rational=True)[0].is_Rational
assert solve(x - 0.5, rational=False)[0].is_Float
assert solve(x - S.Half, rational=False)[0].is_Rational
assert solve(x - 0.5, rational=None)[0].is_Float
assert solve(x - S.Half, rational=None)[0].is_Rational
assert test(nfloat(1 + 2*x), 1.0 + 2.0*x)
for contain in [list, tuple, set]:
ans = nfloat(contain([1 + 2*x]))
assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x)
k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0]
assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x)
assert test(nfloat(cos(2*x)), cos(2.0*x))
assert test(nfloat(3*x**2), 3.0*x**2)
assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0)
assert test(nfloat(exp(2*x)), exp(2.0*x))
assert test(nfloat(x/3), x/3.0)
assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1),
x**4 + 2.0*x + 1.94495694631474)
# don't call nfloat if there is no solution
tot = 100 + c + z + t
assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == []
def test_check_assumptions():
x = symbols('x', positive=True)
assert solve(x**2 - 1) == [1]
def test_issue_6056():
assert solve(tanh(x + 3)*tanh(x - 3) - 1) == []
assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
def test_issue_5673():
eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x)))
assert checksol(eq, x, 2) is True
assert checksol(eq, x, 2, numerical=False) is None
def test_exclude():
R, C, Ri, Vout, V1, Vminus, Vplus, s = \
symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s')
Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln
eqs = [C*V1*s + Vplus*(-2*C*s - 1/R),
Vminus*(-1/Ri - 1/Rf) + Vout/Rf,
C*Vplus*s + V1*(-C*s - 1/R) + Vout/R,
-Vminus + Vplus]
assert solve(eqs, exclude=s*C*R) == [
{
Rf: Ri*(C*R*s + 1)**2/(C*R*s),
Vminus: Vplus,
V1: 2*Vplus + Vplus/(C*R*s),
Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)},
{
Vplus: 0,
Vminus: 0,
V1: 0,
Vout: 0},
]
# TODO: Investigate why currently solution [0] is preferred over [1].
assert solve(eqs, exclude=[Vplus, s, C]) in [[{
Vminus: Vplus,
V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}, {
Vminus: Vplus,
V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}], [{
Vminus: Vplus,
Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus),
Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)),
R: Vplus/(C*s*(V1 - 2*Vplus)),
}]]
def test_high_order_roots():
s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4)
assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots())
def test_minsolve_linear_system():
def count(dic):
return len([x for x in dic.values() if x == 0])
assert count(solve([x + y + z, y + z + a + t], particular=True, quick=True)) \
== 3
assert count(solve([x + y + z, y + z + a + t], particular=True, quick=False)) \
== 3
assert count(solve([x + y + z, y + z + a], particular=True, quick=True)) == 1
assert count(solve([x + y + z, y + z + a], particular=True, quick=False)) == 2
def test_real_roots():
# cf. issue 6650
x = Symbol('x', real=True)
assert len(solve(x**5 + x**3 + 1)) == 1
def test_issue_6528():
eqs = [
327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626,
895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000]
# two expressions encountered are > 1400 ops long so if this hangs
# it is likely because simplification is being done
assert len(solve(eqs, y, x, check=False)) == 4
def test_overdetermined():
x = symbols('x', real=True)
eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1]
assert solve(eqs, x) == [(S.Half,)]
assert solve(eqs, x, manual=True) == [(S.Half,)]
assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)]
def test_issue_6605():
x = symbols('x')
assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)]
# while the first one passed, this one failed
x = symbols('x', real=True)
assert solve(5**(x/2) - 2**(x/3)) == [0]
b = sqrt(6)*sqrt(log(2))/sqrt(log(5))
assert solve(5**(x/2) - 2**(3/x)) == [-b, b]
def test__ispow():
assert _ispow(x**2)
assert not _ispow(x)
assert not _ispow(True)
def test_issue_6644():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2)
sol = solve(eq, q, simplify=False, check=False)
assert len(sol) == 5
def test_issue_6752():
assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)]
assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)]
def test_issue_6792():
assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [
-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1),
CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3),
CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)]
def test_issues_6819_6820_6821_6248_8692():
# issue 6821
x, y = symbols('x y', real=True)
assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9]
assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)]
assert set(solve(abs(x - 7) - 8)) == {-S.One, S(15)}
# issue 8692
assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [
Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half]
# issue 7145
assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)]
x = symbols('x')
assert solve([re(x) - 1, im(x) - 2], x) == [
{re(x): 1, x: 1 + 2*I, im(x): 2}]
# check for 'dict' handling of solution
eq = sqrt(re(x)**2 + im(x)**2) - 3
assert solve(eq) == solve(eq, x)
i = symbols('i', imaginary=True)
assert solve(abs(i) - 3) == [-3*I, 3*I]
raises(NotImplementedError, lambda: solve(abs(x) - 3))
w = symbols('w', integer=True)
assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w)
x, y = symbols('x y', real=True)
assert solve(x + y*I + 3) == {y: 0, x: -3}
# issue 2642
assert solve(x*(1 + I)) == [0]
x, y = symbols('x y', imaginary=True)
assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I}
x = symbols('x', real=True)
assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I}
# issue 6248
f = Function('f')
assert solve(f(x + 1) - f(2*x - 1)) == [2]
assert solve(log(x + 1) - log(2*x - 1)) == [2]
x = symbols('x')
assert solve(2**x + 4**x) == [I*pi/log(2)]
def test_issue_14607():
# issue 14607
s, tau_c, tau_1, tau_2, phi, K = symbols(
's, tau_c, tau_1, tau_2, phi, K')
target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c))
K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D',
positive=True, nonzero=True)
PID = K_C*(1 + 1/(tau_I*s) + tau_D*s)
eq = (target - PID).together()
eq *= denom(eq).simplify()
eq = Poly(eq, s)
c = eq.coeffs()
vars = [K_C, tau_I, tau_D]
s = solve(c, vars, dict=True)
assert len(s) == 1
knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)),
tau_I: tau_1 + tau_2,
tau_D: tau_1*tau_2/(tau_1 + tau_2)}
for var in vars:
assert s[0][var].simplify() == knownsolution[var].simplify()
def test_lambert_multivariate():
from sympy.abc import x, y
assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == {x, exp(x)}
assert _lambert(x, x) == []
assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3]
assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \
[LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3]
assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \
[LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3]
eq = (x*exp(x) - 3).subs(x, x*exp(x))
assert solve(eq) == [LambertW(3*exp(-LambertW(3)))]
# coverage test
raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x))
ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478...
assert solve(x**3 - 3**x, x) == ans
assert set(solve(3*log(x) - x*log(3))) == set(ans)
assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2]
@XFAIL
def test_other_lambert():
assert solve(3*sin(x) - x*sin(3), x) == [3]
assert set(solve(x**a - a**x), x) == {
a, -a*LambertW(-log(a)/a)/log(a)}
@slow
def test_lambert_bivariate():
# tests passing current implementation
assert solve((x**2 + x)*exp(x**2 + x) - 1) == [
Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2,
Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2]
assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [
Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2,
Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2]
assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)]
assert solve((a/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)]
assert solve((1/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)/4),
4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21
4*LambertW(-sqrt(2)/4, -1)]
assert solve(x*log(x) + 3*x + 1, x) == \
[exp(-3 + LambertW(-exp(3)))]
assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
ans = solve(3*x + 5 + 2**(-5*x + 3), x)
assert len(ans) == 1 and ans[0].expand() == \
Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2))
assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \
[Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7]
assert solve((log(x) + x).subs(x, x**2 + 1)) == [
-I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))]
# check collection
ax = a**(3*x + 5)
ans = solve(3*log(ax) + b*log(ax) + ax, x)
x0 = 1/log(a)
x1 = sqrt(3)*I
x2 = b + 3
x3 = x2*LambertW(1/x2)/a**5
x4 = x3**Rational(1, 3)/2
assert ans == [
x0*log(x4*(x1 - 1)),
x0*log(-x4*(x1 + 1)),
x0*log(x3)/3]
x1 = LambertW(Rational(1, 3))
x2 = a**(-5)
x3 = 3**Rational(1, 3)
x4 = 3**Rational(5, 6)*I
x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2
ans = solve(3*log(ax) + ax, x)
assert ans == [
x0*log(3*x1*x2)/3,
x0*log(x5*(-x3 + x4)),
x0*log(-x5*(x3 + x4))]
# coverage
p = symbols('p', positive=True)
eq = 4*2**(2*p + 3) - 2*p - 3
assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [
Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))]
assert set(solve(3**cos(x) - cos(x)**3)) == {
acos(3), acos(-3*LambertW(-log(3)/3)/log(3))}
# should give only one solution after using `uniq`
assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [
exp(-z + LambertW(2*z**4*exp(2*z))/2)/z]
# cases when p != S.One
# issue 4271
ans = solve((a/x + exp(x/2)).diff(x, 2), x)
x0 = (-a)**Rational(1, 3)
x1 = sqrt(3)*I
x2 = x0/6
assert ans == [
6*LambertW(x0/3),
6*LambertW(x2*(x1 - 1)),
6*LambertW(-x2*(x1 + 1))]
assert solve((1/x + exp(x/2)).diff(x, 2), x) == \
[6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \
6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)]
assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \
[{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}]
# this is slow but not exceedingly slow
assert solve((x**3)**(x/2) + pi/2, x) == [
exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))]
def test_rewrite_trig():
assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi]
assert solve(sin(x) + sec(x)) == [
-2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2),
2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half
+ sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half -
sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)]
assert solve(sinh(x) + tanh(x)) == [0, I*pi]
# issue 6157
assert solve(2*sin(x) - cos(x), x) == [atan(S.Half)]
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy import sech
assert solve(sinh(x) + sech(x)) == [
2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2),
2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2),
2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2),
2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)]
def test_uselogcombine():
eq = z - log(x) + log(y/(x*(-1 + y**2/x**2)))
assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))]
assert solve(log(x + 3) + log(1 + 3/x) - 3) in [
[-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2,
-sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2],
[-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2,
-3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2],
]
assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == []
def test_atan2():
assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)]
def test_errorinverses():
assert solve(erf(x) - y, x) == [erfinv(y)]
assert solve(erfinv(x) - y, x) == [erf(y)]
assert solve(erfc(x) - y, x) == [erfcinv(y)]
assert solve(erfcinv(x) - y, x) == [erfc(y)]
def test_issue_2725():
R = Symbol('R')
eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1)
sol = solve(eq, R, set=True)[1]
assert sol == {(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)}
def test_issue_5114_6611():
# See that it doesn't hang; this solves in about 2 seconds.
# Also check that the solution is relatively small.
# Note: the system in issue 6611 solves in about 5 seconds and has
# an op-count of 138336 (with simplify=False).
b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r')
eqs = Matrix([
[b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d],
[-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m],
[-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]])
v = Matrix([f, h, k, n, b, c])
ans = solve(list(eqs), list(v), simplify=False)
# If time is taken to simplify then then 2617 below becomes
# 1168 and the time is about 50 seconds instead of 2.
assert sum([s.count_ops() for s in ans.values()]) <= 3270
def test_det_quick():
m = Matrix(3, 3, symbols('a:9'))
assert m.det() == det_quick(m) # calls det_perm
m[0, 0] = 1
assert m.det() == det_quick(m) # calls det_minor
m = Matrix(3, 3, list(range(9)))
assert m.det() == det_quick(m) # defaults to .det()
# make sure they work with Sparse
s = SparseMatrix(2, 2, (1, 2, 1, 4))
assert det_perm(s) == det_minor(s) == s.det()
def test_real_imag_splitting():
a, b = symbols('a b', real=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == \
[-sqrt(-b**2 + 9), sqrt(-b**2 + 9)]
a, b = symbols('a b', imaginary=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == []
def test_issue_7110():
y = -2*x**3 + 4*x**2 - 2*x + 5
assert any(ask(Q.real(i)) for i in solve(y))
def test_units():
assert solve(1/x - 1/(2*cm)) == [2*cm]
def test_issue_7547():
A, B, V = symbols('A,B,V')
eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0)
eq2 = Eq(B, 1.36*10**8*(V - 39))
eq3 = Eq(A, 5.75*10**5*V*(V + 39.0))
sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0)))
assert str(sol) == str(Matrix(
[['4442890172.68209'],
['4289299466.1432'],
['70.5389666628177']]))
def test_issue_7895():
r = symbols('r', real=True)
assert solve(sqrt(r) - 2) == [4]
def test_issue_2777():
# the equations represent two circles
x, y = symbols('x y', real=True)
e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3
a, b = Rational(191, 20), 3*sqrt(391)/20
ans = [(a, -b), (a, b)]
assert solve((e1, e2), (x, y)) == ans
assert solve((e1, e2/(x - a)), (x, y)) == []
# make the 2nd circle's radius be -3
e2 += 6
assert solve((e1, e2), (x, y)) == []
assert solve((e1, e2), (x, y), check=False) == ans
def test_issue_7322():
number = 5.62527e-35
assert solve(x - number, x)[0] == number
def test_nsolve():
raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect'))
raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50)))
raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1)))
@slow
def test_high_order_multivariate():
assert len(solve(a*x**3 - x + 1, x)) == 3
assert len(solve(a*x**4 - x + 1, x)) == 4
assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed
raises(NotImplementedError, lambda:
solve(a*x**5 - x + 1, x, incomplete=False))
# result checking must always consider the denominator and CRootOf
# must be checked, too
d = x**5 - x + 1
assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)]
d = x - 1
assert solve(d*(2 + 1/d)) == [S.Half]
def test_base_0_exp_0():
assert solve(0**x - 1) == [0]
assert solve(0**(x - 2) - 1) == [2]
assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \
[0, 1]
def test__simple_dens():
assert _simple_dens(1/x**0, [x]) == set()
assert _simple_dens(1/x**y, [x]) == {x**y}
assert _simple_dens(1/root(x, 3), [x]) == {x}
def test_issue_8755():
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests the use of
# keyword `composite`.
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
@slow
def test_issue_8828():
x1 = 0
y1 = -620
r1 = 920
x2 = 126
y2 = 276
x3 = 51
y3 = 205
r3 = 104
v = x, y, z
f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2
f2 = (x2 - x)**2 + (y2 - y)**2 - z**2
f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2
F = f1,f2,f3
g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1
g2 = f2
g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3
G = g1,g2,g3
A = solve(F, v)
B = solve(G, v)
C = solve(G, v, manual=True)
p, q, r = [{tuple(i.evalf(2) for i in j) for j in R} for R in [A, B, C]]
assert p == q == r
@slow
def test_issue_2840_8155():
assert solve(sin(3*x) + sin(6*x)) == [
0, pi*Rational(-5, 3), pi*Rational(-4, 3), -pi, pi*Rational(-2, 3),
pi*Rational(-4, 9), -pi/3, pi*Rational(-2, 9), pi*Rational(2, 9),
pi/3, pi*Rational(4, 9), pi*Rational(2, 3), pi, pi*Rational(4, 3),
pi*Rational(14, 9), pi*Rational(5, 3), pi*Rational(16, 9), 2*pi,
-2*I*log(-(-1)**Rational(1, 9)), -2*I*log(-(-1)**Rational(2, 9)),
-2*I*log(-sin(pi/18) - I*cos(pi/18)),
-2*I*log(-sin(pi/18) + I*cos(pi/18)),
-2*I*log(sin(pi/18) - I*cos(pi/18)),
-2*I*log(sin(pi/18) + I*cos(pi/18))]
assert solve(2*sin(x) - 2*sin(2*x)) == [
0, pi*Rational(-5, 3), -pi, -pi/3, pi/3, pi, pi*Rational(5, 3)]
def test_issue_9567():
assert solve(1 + 1/(x - 1)) == [0]
def test_issue_11538():
assert solve(x + E) == [-E]
assert solve(x**2 + E) == [-I*sqrt(E), I*sqrt(E)]
assert solve(x**3 + 2*E) == [
-cbrt(2 * E),
cbrt(2)*cbrt(E)/2 - cbrt(2)*sqrt(3)*I*cbrt(E)/2,
cbrt(2)*cbrt(E)/2 + cbrt(2)*sqrt(3)*I*cbrt(E)/2]
assert solve([x + 4, y + E], x, y) == {x: -4, y: -E}
assert solve([x**2 + 4, y + E], x, y) == [
(-2*I, -E), (2*I, -E)]
e1 = x - y**3 + 4
e2 = x + y + 4 + 4 * E
assert len(solve([e1, e2], x, y)) == 3
@slow
def test_issue_12114():
a, b, c, d, e, f, g = symbols('a,b,c,d,e,f,g')
terms = [1 + a*b + d*e, 1 + a*c + d*f, 1 + b*c + e*f,
g - a**2 - d**2, g - b**2 - e**2, g - c**2 - f**2]
s = solve(terms, [a, b, c, d, e, f, g], dict=True)
assert s == [{a: -sqrt(-f**2 - 1), b: -sqrt(-f**2 - 1),
c: -sqrt(-f**2 - 1), d: f, e: f, g: -1},
{a: sqrt(-f**2 - 1), b: sqrt(-f**2 - 1),
c: sqrt(-f**2 - 1), d: f, e: f, g: -1},
{a: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2,
b: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2),
d: -f/2 + sqrt(-3*f**2 + 6)/2,
e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2,
b: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2),
d: -f/2 - sqrt(-3*f**2 + 6)/2,
e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2,
b: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2),
d: -f/2 - sqrt(-3*f**2 + 6)/2,
e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2,
b: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2),
d: -f/2 + sqrt(-3*f**2 + 6)/2,
e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}]
def test_inf():
assert solve(1 - oo*x) == []
assert solve(oo*x, x) == []
assert solve(oo*x - oo, x) == []
def test_issue_12448():
f = Function('f')
fun = [f(i) for i in range(15)]
sym = symbols('x:15')
reps = dict(zip(fun, sym))
(x, y, z), c = sym[:3], sym[3:]
ssym = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3]
for i in range(3)], (x, y, z))
(x, y, z), c = fun[:3], fun[3:]
sfun = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3]
for i in range(3)], (x, y, z))
assert sfun[fun[0]].xreplace(reps).count_ops() == \
ssym[sym[0]].count_ops()
def test_denoms():
assert denoms(x/2 + 1/y) == {2, y}
assert denoms(x/2 + 1/y, y) == {y}
assert denoms(x/2 + 1/y, [y]) == {y}
assert denoms(1/x + 1/y + 1/z, [x, y]) == {x, y}
assert denoms(1/x + 1/y + 1/z, x, y) == {x, y}
assert denoms(1/x + 1/y + 1/z, {x, y}) == {x, y}
def test_issue_12476():
x0, x1, x2, x3, x4, x5 = symbols('x0 x1 x2 x3 x4 x5')
eqns = [x0**2 - x0, x0*x1 - x1, x0*x2 - x2, x0*x3 - x3, x0*x4 - x4, x0*x5 - x5,
x0*x1 - x1, -x0/3 + x1**2 - 2*x2/3, x1*x2 - x1/3 - x2/3 - x3/3,
x1*x3 - x2/3 - x3/3 - x4/3, x1*x4 - 2*x3/3 - x5/3, x1*x5 - x4, x0*x2 - x2,
x1*x2 - x1/3 - x2/3 - x3/3, -x0/6 - x1/6 + x2**2 - x2/6 - x3/3 - x4/6,
-x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, x2*x4 - x2/3 - x3/3 - x4/3,
x2*x5 - x3, x0*x3 - x3, x1*x3 - x2/3 - x3/3 - x4/3,
-x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6,
-x0/6 - x1/6 - x2/6 + x3**2 - x3/3 - x4/6, -x1/3 - x2/3 + x3*x4 - x3/3,
-x2 + x3*x5, x0*x4 - x4, x1*x4 - 2*x3/3 - x5/3, x2*x4 - x2/3 - x3/3 - x4/3,
-x1/3 - x2/3 + x3*x4 - x3/3, -x0/3 - 2*x2/3 + x4**2, -x1 + x4*x5, x0*x5 - x5,
x1*x5 - x4, x2*x5 - x3, -x2 + x3*x5, -x1 + x4*x5, -x0 + x5**2, x0 - 1]
sols = [{x0: 1, x3: Rational(1, 6), x2: Rational(1, 6), x4: Rational(-2, 3), x1: Rational(-2, 3), x5: 1},
{x0: 1, x3: S.Half, x2: Rational(-1, 2), x4: 0, x1: 0, x5: -1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(-1, 3), x4: Rational(1, 3), x1: Rational(1, 3), x5: 1},
{x0: 1, x3: 1, x2: 1, x4: 1, x1: 1, x5: 1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: sqrt(5)/3, x1: -sqrt(5)/3, x5: -1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: -sqrt(5)/3, x1: sqrt(5)/3, x5: -1}]
assert solve(eqns) == sols
def test_issue_13849():
t = symbols('t')
assert solve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == []
def test_issue_14860():
from sympy.physics.units import newton, kilo
assert solve(8*kilo*newton + x + y, x) == [-8000*newton - y]
def test_issue_14721():
k, h, a, b = symbols(':4')
assert solve([
-1 + (-k + 1)**2/b**2 + (-h - 1)**2/a**2,
-1 + (-k + 1)**2/b**2 + (-h + 1)**2/a**2,
h, k + 2], h, k, a, b) == [
(0, -2, -b*sqrt(1/(b**2 - 9)), b),
(0, -2, b*sqrt(1/(b**2 - 9)), b)]
assert solve([
h, h/a + 1/b**2 - 2, -h/2 + 1/b**2 - 2], a, h, b) == [
(a, 0, -sqrt(2)/2), (a, 0, sqrt(2)/2)]
assert solve((a + b**2 - 1, a + b**2 - 2)) == []
def test_issue_14779():
x = symbols('x', real=True)
assert solve(sqrt(x**4 - 130*x**2 + 1089) + sqrt(x**4 - 130*x**2
+ 3969) - 96*Abs(x)/x,x) == [sqrt(130)]
def test_issue_15307():
assert solve((y - 2, Mul(x + 3,x - 2, evaluate=False))) == \
[{x: -3, y: 2}, {x: 2, y: 2}]
assert solve((y - 2, Mul(3, x - 2, evaluate=False))) == \
{x: 2, y: 2}
assert solve((y - 2, Add(x + 4, x - 2, evaluate=False))) == \
{x: -1, y: 2}
eq1 = Eq(12513*x + 2*y - 219093, -5726*x - y)
eq2 = Eq(-2*x + 8, 2*x - 40)
assert solve([eq1, eq2]) == {x:12, y:75}
def test_issue_15415():
assert solve(x - 3, x) == [3]
assert solve([x - 3], x) == {x:3}
assert solve(Eq(y + 3*x**2/2, y + 3*x), y) == []
assert solve([Eq(y + 3*x**2/2, y + 3*x)], y) == []
assert solve([Eq(y + 3*x**2/2, y + 3*x), Eq(x, 1)], y) == []
@slow
def test_issue_15731():
# f(x)**g(x)=c
assert solve(Eq((x**2 - 7*x + 11)**(x**2 - 13*x + 42), 1)) == [2, 3, 4, 5, 6, 7]
assert solve((x)**(x + 4) - 4) == [-2]
assert solve((-x)**(-x + 4) - 4) == [2]
assert solve((x**2 - 6)**(x**2 - 2) - 4) == [-2, 2]
assert solve((x**2 - 2*x - 1)**(x**2 - 3) - 1/(1 - 2*sqrt(2))) == [sqrt(2)]
assert solve(x**(x + S.Half) - 4*sqrt(2)) == [S(2)]
assert solve((x**2 + 1)**x - 25) == [2]
assert solve(x**(2/x) - 2) == [2, 4]
assert solve((x/2)**(2/x) - sqrt(2)) == [4, 8]
assert solve(x**(x + S.Half) - Rational(9, 4)) == [Rational(3, 2)]
# a**g(x)=c
assert solve((-sqrt(sqrt(2)))**x - 2) == [4, log(2)/(log(2**Rational(1, 4)) + I*pi)]
assert solve((sqrt(2))**x - sqrt(sqrt(2))) == [S.Half]
assert solve((-sqrt(2))**x + 2*(sqrt(2))) == [3,
(3*log(2)**2 + 4*pi**2 - 4*I*pi*log(2))/(log(2)**2 + 4*pi**2)]
assert solve((sqrt(2))**x - 2*(sqrt(2))) == [3]
assert solve(I**x + 1) == [2]
assert solve((1 + I)**x - 2*I) == [2]
assert solve((sqrt(2) + sqrt(3))**x - (2*sqrt(6) + 5)**Rational(1, 3)) == [Rational(2, 3)]
# bases of both sides are equal
b = Symbol('b')
assert solve(b**x - b**2, x) == [2]
assert solve(b**x - 1/b, x) == [-1]
assert solve(b**x - b, x) == [1]
b = Symbol('b', positive=True)
assert solve(b**x - b**2, x) == [2]
assert solve(b**x - 1/b, x) == [-1]
def test_issue_10933():
assert solve(x**4 + y*(x + 0.1), x) # doesn't fail
assert solve(I*x**4 + x**3 + x**2 + 1.) # doesn't fail
def test_Abs_handling():
x = symbols('x', real=True)
assert solve(abs(x/y), x) == [0]
def test_issue_7982():
x = Symbol('x')
# Test that no exception happens
assert solve([2*x**2 + 5*x + 20 <= 0, x >= 1.5], x) is S.false
# From #8040
assert solve([x**3 - 8.08*x**2 - 56.48*x/5 - 106 >= 0, x - 1 <= 0], [x]) is S.false
def test_issue_14645():
x, y = symbols('x y')
assert solve([x*y - x - y, x*y - x - y], [x, y]) == [(y/(y - 1), y)]
def test_issue_12024():
x, y = symbols('x y')
assert solve(Piecewise((0.0, x < 0.1), (x, x >= 0.1)) - y) == \
[{y: Piecewise((0.0, x < 0.1), (x, True))}]
def test_issue_17452():
assert solve((7**x)**x + pi, x) == [-sqrt(log(pi) + I*pi)/sqrt(log(7)),
sqrt(log(pi) + I*pi)/sqrt(log(7))]
assert solve(x**(x/11) + pi/11, x) == [exp(LambertW(-11*log(11) + 11*log(pi) + 11*I*pi))]
def test_issue_17799():
assert solve(-erf(x**(S(1)/3))**pi + I, x) == []
def test_issue_17650():
x = Symbol('x', real=True)
assert solve(abs(abs(x**2 - 1) - x) - x) == [1, -1 + sqrt(2), 1 + sqrt(2)]
def test_issue_17882():
eq = -8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3))
assert unrad(eq) == (4*x**2 - 12, [])
def test_issue_17949():
assert solve(exp(+x+x**2), x) == []
assert solve(exp(-x+x**2), x) == []
assert solve(exp(+x-x**2), x) == []
assert solve(exp(-x-x**2), x) == []
def test_issue_10993():
assert solve(Eq(binomial(x, 2), 3)) == [-2, 3]
assert solve(Eq(pow(x, 2) + binomial(x, 3), x)) == [-4, 0, 1]
assert solve(Eq(binomial(x, 2), 0)) == [0, 1]
assert solve(a+binomial(x, 3), a) == [-binomial(x, 3)]
assert solve(x-binomial(a, 3) + binomial(y, 2) + sin(a), x) == [-sin(a) + binomial(a, 3) - binomial(y, 2)]
assert solve((x+1)-binomial(x+1, 3), x) == [-2, -1, 3]
def test_issue_11553():
eq1 = x + y + 1
eq2 = x + GoldenRatio
assert solve([eq1, eq2], x, y) == {x: -GoldenRatio, y: -1 + GoldenRatio}
eq3 = x + 2 + TribonacciConstant
assert solve([eq1, eq3], x, y) == {x: -2 - TribonacciConstant, y: 1 + TribonacciConstant}
def test_issue_19113_19102():
t = S(1)/3
solve(cos(x)**5-sin(x)**5)
assert solve(4*cos(x)**3 - 2*sin(x)**3) == [
atan(2**(t)), -atan(2**(t)*(1 - sqrt(3)*I)/2),
-atan(2**(t)*(1 + sqrt(3)*I)/2)]
h = S.Half
assert solve(cos(x)**2 + sin(x)) == [
2*atan(-h + sqrt(5)/2 + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(h + sqrt(5)/2 + sqrt(2)*sqrt(1 + sqrt(5))/2),
-2*atan(-sqrt(5)/2 + h + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(-sqrt(2)*sqrt(1 + sqrt(5))/2 + h + sqrt(5)/2)]
assert solve(3*cos(x) - sin(x)) == [atan(3)]
def test_issue_19509():
a = S(3)/4
b = S(5)/8
c = sqrt(5)/8
d = sqrt(5)/4
assert solve(1/(x -1)**5 - 1) == [2,
-d + a - sqrt(-b + c),
-d + a + sqrt(-b + c),
d + a - sqrt(-b - c),
d + a + sqrt(-b - c)]
def test_issue_20747():
THT, HT, DBH, dib, c0, c1, c2, c3, c4 = symbols('THT HT DBH dib c0 c1 c2 c3 c4')
f = DBH*c3 + THT*c4 + c2
rhs = 1 - ((HT - 1)/(THT - 1))**c1*(1 - exp(c0/f))
eq = dib - DBH*(c0 - f*log(rhs))
term = ((1 - exp((DBH*c0 - dib)/(DBH*(DBH*c3 + THT*c4 + c2))))
/ (1 - exp(c0/(DBH*c3 + THT*c4 + c2))))
sol = [THT*term**(1/c1) - term**(1/c1) + 1]
assert solve(eq, HT) == sol
|
f9c966b5d9bf6937219c0d8cd3111ced251f796712b6d1b815643536b52203e6 | from sympy import (Symbol, S, exp, log, sqrt, oo, E, zoo, pi, tan, sin, cos,
cot, sec, csc, Abs, symbols, I, re, simplify,
expint, Rational)
from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
periodicity, lcim, AccumBounds, is_convex,
stationary_points, minimum, maximum)
from sympy.core import Add, Mul, Pow
from sympy.sets.sets import (Interval, FiniteSet, EmptySet, Complement,
Union)
from sympy.testing.pytest import raises
from sympy.abc import x
a = Symbol('a', real=True)
def test_function_range():
x, y, a, b = symbols('x y a b')
assert function_range(sin(x), x, Interval(-pi/2, pi/2)
) == Interval(-1, 1)
assert function_range(sin(x), x, Interval(0, pi)
) == Interval(0, 1)
assert function_range(tan(x), x, Interval(0, pi)
) == Interval(-oo, oo)
assert function_range(tan(x), x, Interval(pi/2, pi)
) == Interval(-oo, 0)
assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
assert function_range(1/(x**2), x, Interval(-1, 1)
) == Interval(1, oo)
assert function_range(exp(x), x, Interval(-1, 1)
) == Interval(exp(-1), exp(1))
assert function_range(log(x) - x, x, S.Reals
) == Interval(-oo, -1)
assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
) == Interval(0, sqrt(5))
assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
) == FiniteSet(0)
assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
) == FiniteSet(y)
assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
assert function_range(cos(x), x, Interval(-oo, -4)
) == Interval(-1, 1)
assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
raises(NotImplementedError, lambda : function_range(
exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
raises(NotImplementedError, lambda : function_range(
sin(x) + x, x, S.Reals)) # issue 13273
raises(NotImplementedError, lambda : function_range(
log(x), x, S.Integers))
raises(NotImplementedError, lambda : function_range(
sin(x)/2, x, S.Naturals))
def test_continuous_domain():
x = Symbol('x')
assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
Interval(pi*Rational(3, 2), 2*pi, True, False))
assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
Interval(Rational(1, 4), oo, True, True)
assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
assert continuous_domain(1/x - 2, x, S.Reals) == \
Union(Interval.open(-oo, 0), Interval.open(0, oo))
assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
assert not domain.contains(3*pi/2)
assert domain.contains(5)
def test_not_empty_in():
assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
Interval(S.Half, 2, True, False)
assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
Union(Interval(-sqrt(2), -1), Interval(1, 2))
assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
Union(Interval(-sqrt(17)/2 - S.Half, -2),
Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(-oo, oo)
assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(S(3)/2, 2)
assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(-1, 1))
assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
Interval(4, 5))), x) == \
Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
Interval(1, 3, True, True), Interval(4, 5))
assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
Union(Interval(-2, -1, True, False), Interval(2, oo))
raises(ValueError, lambda: not_empty_in(x))
raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
raises(NotImplementedError,
lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
def test_periodicity():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z', real=True)
assert periodicity(sin(2*x), x) == pi
assert periodicity((-2)*tan(4*x), x) == pi/4
assert periodicity(sin(x)**2, x) == 2*pi
assert periodicity(3**tan(3*x), x) == pi/3
assert periodicity(tan(x)*cos(x), x) == 2*pi
assert periodicity(sin(x)**(tan(x)), x) == 2*pi
assert periodicity(tan(x)*sec(x), x) == 2*pi
assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
assert periodicity(tan(x) + cot(x), x) == pi
assert periodicity(sin(x) - cos(2*x), x) == 2*pi
assert periodicity(sin(x) - 1, x) == 2*pi
assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
assert periodicity(exp(sin(x)), x) == 2*pi
assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
assert periodicity(tan(sin(2*x)), x) == pi
assert periodicity(2*tan(x)**2, x) == pi
assert periodicity(sin(x%4), x) == 4
assert periodicity(sin(x)%4, x) == 2*pi
assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
assert periodicity((x**2+1) % x, x) is None
assert periodicity(sin(re(x)), x) == 2*pi
assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
assert periodicity(tan(x), y) is S.Zero
assert periodicity(sin(x) + I*cos(x), x) == 2*pi
assert periodicity(x - sin(2*y), y) == pi
assert periodicity(exp(x), x) is None
assert periodicity(exp(I*x), x) == 2*pi
assert periodicity(exp(I*z), z) == 2*pi
assert periodicity(exp(z), z) is None
assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
assert periodicity(exp(sin(z)), z) == 2*pi
assert periodicity(exp(2*I*z), z) == pi
assert periodicity(exp(z + I*sin(z)), z) is None
assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
assert periodicity(log(x), x) is None
assert periodicity(exp(x)**sin(x), x) is None
assert periodicity(sin(x)**y, y) is None
assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
assert all(periodicity(Abs(f(x)), x) == pi for f in (
cos, sin, sec, csc, tan, cot))
assert periodicity(Abs(sin(tan(x))), x) == pi
assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
assert periodicity(sin(x) > S.Half, x) == 2*pi
assert periodicity(x > 2, x) is None
assert periodicity(x**3 - x**2 + 1, x) is None
assert periodicity(Abs(x), x) is None
assert periodicity(Abs(x**2 - 1), x) is None
assert periodicity((x**2 + 4)%2, x) is None
assert periodicity((E**x)%3, x) is None
assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
def test_periodicity_check():
x = Symbol('x')
y = Symbol('y')
assert periodicity(tan(x), x, check=True) == pi
assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
assert periodicity(sec(x), x) == 2*pi
assert periodicity(sin(x*y), x) == 2*pi/abs(y)
assert periodicity(Abs(sec(sec(x))), x) == pi
def test_lcim():
from sympy import pi
assert lcim([S.Half, S(2), S(3)]) == 6
assert lcim([pi/2, pi/4, pi]) == pi
assert lcim([2*pi, pi/2]) == 2*pi
assert lcim([S.One, 2*pi]) is None
assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
def test_is_convex():
assert is_convex(1/x, x, domain=Interval(0, oo)) == True
assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
assert is_convex(x**2, x, domain=Interval(0, oo)) == True
assert is_convex(log(x), x) == False
raises(NotImplementedError, lambda: is_convex(log(x), x, a))
def test_stationary_points():
x, y = symbols('x y')
assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
) == {-pi/2, pi/2}
assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
) == EmptySet()
assert stationary_points(tan(x), x,
) == EmptySet()
assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
) == {pi/4, pi*Rational(3, 4)}
assert stationary_points(sec(x), x, Interval(0, pi)
) == {0, pi}
assert stationary_points((x+3)*(x-2), x
) == FiniteSet(Rational(-1, 2))
assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
) == EmptySet()
assert stationary_points((x**2+3)/(x-2), x
) == {2 - sqrt(7), 2 + sqrt(7)}
assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
) == {2 + sqrt(7)}
assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
) == FiniteSet(-2, 0, Rational(5, 4))
assert stationary_points(exp(x), x
) == EmptySet()
assert stationary_points(log(x) - x, x, S.Reals
) == {1}
assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) == {0, -pi, pi}
assert stationary_points(y, x, S.Reals
) == S.Reals
assert stationary_points(y, x, S.EmptySet) == S.EmptySet
def test_maximum():
x, y = symbols('x y')
assert maximum(sin(x), x) is S.One
assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
assert maximum(tan(x), x) is oo
assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == sqrt(2)/4
assert maximum((x+3)*(x-2), x) is oo
assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
assert simplify(maximum(-x**4-x**3+x**2+10, x)
) == 41*sqrt(41)/512 + Rational(5419, 512)
assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.One
assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
assert maximum(y, x, S.Reals) == y
assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), sin(x)))
raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), S.One))
def test_minimum():
x, y = symbols('x y')
assert minimum(sin(x), x) is S.NegativeOne
assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
assert minimum(tan(x), x) is -oo
assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == -sqrt(2)/4
assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
assert minimum(x**4-x**3+x**2+10, x) == S(10)
assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
assert minimum(log(x) - x, x, S.Reals) is -oo
assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.NegativeOne
assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
assert minimum(y, x, S.Reals) == y
raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), sin(x)))
raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), S.One))
def test_AccumBounds():
assert AccumBounds(1, 2).args == (1, 2)
assert AccumBounds(1, 2).delta is S.One
assert AccumBounds(1, 2).mid == Rational(3, 2)
assert AccumBounds(1, 3).is_real == True
assert AccumBounds(1, 1) is S.One
assert AccumBounds(1, 2) + 1 == AccumBounds(2, 3)
assert 1 + AccumBounds(1, 2) == AccumBounds(2, 3)
assert AccumBounds(1, 2) + AccumBounds(2, 3) == AccumBounds(3, 5)
assert -AccumBounds(1, 2) == AccumBounds(-2, -1)
assert AccumBounds(1, 2) - 1 == AccumBounds(0, 1)
assert 1 - AccumBounds(1, 2) == AccumBounds(-1, 0)
assert AccumBounds(2, 3) - AccumBounds(1, 2) == AccumBounds(0, 2)
assert x + AccumBounds(1, 2) == Add(AccumBounds(1, 2), x)
assert a + AccumBounds(1, 2) == AccumBounds(1 + a, 2 + a)
assert AccumBounds(1, 2) - x == Add(AccumBounds(1, 2), -x)
assert AccumBounds(-oo, 1) + oo == AccumBounds(-oo, oo)
assert AccumBounds(1, oo) + oo is oo
assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)
assert (-oo - AccumBounds(-1, oo)) is -oo
assert AccumBounds(-oo, 1) - oo is -oo
assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)
assert AccumBounds(-oo, 1) - (-oo) == AccumBounds(-oo, oo)
assert (oo - AccumBounds(1, oo)) == AccumBounds(-oo, oo)
assert (-oo - AccumBounds(1, oo)) is -oo
assert AccumBounds(1, 2)/2 == AccumBounds(S.Half, 1)
assert 2/AccumBounds(2, 3) == AccumBounds(Rational(2, 3), 1)
assert 1/AccumBounds(-1, 1) == AccumBounds(-oo, oo)
assert abs(AccumBounds(1, 2)) == AccumBounds(1, 2)
assert abs(AccumBounds(-2, -1)) == AccumBounds(1, 2)
assert abs(AccumBounds(-2, 1)) == AccumBounds(0, 2)
assert abs(AccumBounds(-1, 2)) == AccumBounds(0, 2)
c = Symbol('c')
raises(ValueError, lambda: AccumBounds(0, c))
raises(ValueError, lambda: AccumBounds(1, -1))
def test_AccumBounds_mul():
assert AccumBounds(1, 2)*2 == AccumBounds(2, 4)
assert 2*AccumBounds(1, 2) == AccumBounds(2, 4)
assert AccumBounds(1, 2)*AccumBounds(2, 3) == AccumBounds(2, 6)
assert AccumBounds(1, 2)*0 == 0
assert AccumBounds(1, oo)*0 == AccumBounds(0, oo)
assert AccumBounds(-oo, 1)*0 == AccumBounds(-oo, 0)
assert AccumBounds(-oo, oo)*0 == AccumBounds(-oo, oo)
assert AccumBounds(1, 2)*x == Mul(AccumBounds(1, 2), x, evaluate=False)
assert AccumBounds(0, 2)*oo == AccumBounds(0, oo)
assert AccumBounds(-2, 0)*oo == AccumBounds(-oo, 0)
assert AccumBounds(0, 2)*(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-2, 0)*(-oo) == AccumBounds(0, oo)
assert AccumBounds(-1, 1)*oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, 1)*(-oo) == AccumBounds(-oo, oo)
assert AccumBounds(-oo, oo)*oo == AccumBounds(-oo, oo)
def test_AccumBounds_div():
assert AccumBounds(-1, 3)/AccumBounds(3, 4) == AccumBounds(Rational(-1, 3), 1)
assert AccumBounds(-2, 4)/AccumBounds(-3, 4) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)/AccumBounds(-4, 0) == AccumBounds(S.Half, oo)
# these two tests can have a better answer
# after Union of AccumBounds is improved
assert AccumBounds(-3, -2)/AccumBounds(-2, 1) == AccumBounds(-oo, oo)
assert AccumBounds(2, 3)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)/AccumBounds(0, 4) == AccumBounds(-oo, Rational(-1, 2))
assert AccumBounds(2, 4)/AccumBounds(-3, 0) == AccumBounds(-oo, Rational(-2, 3))
assert AccumBounds(2, 4)/AccumBounds(0, 3) == AccumBounds(Rational(2, 3), oo)
assert AccumBounds(0, 1)/AccumBounds(0, 1) == AccumBounds(0, oo)
assert AccumBounds(-1, 0)/AccumBounds(0, 1) == AccumBounds(-oo, 0)
assert AccumBounds(-1, 2)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)
assert 1/AccumBounds(-1, 2) == AccumBounds(-oo, oo)
assert 1/AccumBounds(0, 2) == AccumBounds(S.Half, oo)
assert (-1)/AccumBounds(0, 2) == AccumBounds(-oo, Rational(-1, 2))
assert 1/AccumBounds(-oo, 0) == AccumBounds(-oo, 0)
assert 1/AccumBounds(-1, 0) == AccumBounds(-oo, -1)
assert (-2)/AccumBounds(-oo, 0) == AccumBounds(0, oo)
assert 1/AccumBounds(-oo, -1) == AccumBounds(-1, 0)
assert AccumBounds(1, 2)/a == Mul(AccumBounds(1, 2), 1/a, evaluate=False)
assert AccumBounds(1, 2)/0 == AccumBounds(1, 2)*zoo
assert AccumBounds(1, oo)/oo == AccumBounds(0, oo)
assert AccumBounds(1, oo)/(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-oo, -1)/oo == AccumBounds(-oo, 0)
assert AccumBounds(-oo, -1)/(-oo) == AccumBounds(0, oo)
assert AccumBounds(-oo, oo)/oo == AccumBounds(-oo, oo)
assert AccumBounds(-oo, oo)/(-oo) == AccumBounds(-oo, oo)
assert AccumBounds(-1, oo)/oo == AccumBounds(0, oo)
assert AccumBounds(-1, oo)/(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-oo, 1)/oo == AccumBounds(-oo, 0)
assert AccumBounds(-oo, 1)/(-oo) == AccumBounds(0, oo)
def test_issue_18795():
r = Symbol('r', real=True)
a = AccumBounds(-1,1)
c = AccumBounds(7, oo)
b = AccumBounds(-oo, oo)
assert c - tan(r) == AccumBounds(7-tan(r), oo)
assert b + tan(r) == AccumBounds(-oo, oo)
assert (a + r)/a == AccumBounds(-oo, oo)*AccumBounds(r - 1, r + 1)
assert (b + a)/a == AccumBounds(-oo, oo)
def test_AccumBounds_func():
assert (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) == AccumBounds(-1, 4)
assert exp(AccumBounds(0, 1)) == AccumBounds(1, E)
assert exp(AccumBounds(-oo, oo)) == AccumBounds(0, oo)
assert log(AccumBounds(3, 6)) == AccumBounds(log(3), log(6))
def test_AccumBounds_pow():
assert AccumBounds(0, 2)**2 == AccumBounds(0, 4)
assert AccumBounds(-1, 1)**2 == AccumBounds(0, 1)
assert AccumBounds(1, 2)**2 == AccumBounds(1, 4)
assert AccumBounds(-1, 2)**3 == AccumBounds(-1, 8)
assert AccumBounds(-1, 1)**0 == 1
assert AccumBounds(1, 2)**Rational(5, 2) == AccumBounds(1, 4*sqrt(2))
assert AccumBounds(-1, 2)**Rational(1, 3) == AccumBounds(-1, 2**Rational(1, 3))
assert AccumBounds(0, 2)**S.Half == AccumBounds(0, sqrt(2))
assert AccumBounds(-4, 2)**Rational(2, 3) == AccumBounds(0, 2*2**Rational(1, 3))
assert AccumBounds(-1, 5)**S.Half == AccumBounds(0, sqrt(5))
assert AccumBounds(-oo, 2)**S.Half == AccumBounds(0, sqrt(2))
assert AccumBounds(-2, 3)**Rational(-1, 4) == AccumBounds(0, oo)
assert AccumBounds(1, 5)**(-2) == AccumBounds(Rational(1, 25), 1)
assert AccumBounds(-1, 3)**(-2) == AccumBounds(0, oo)
assert AccumBounds(0, 2)**(-2) == AccumBounds(Rational(1, 4), oo)
assert AccumBounds(-1, 2)**(-3) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)**(-3) == AccumBounds(Rational(-1, 8), Rational(-1, 27))
assert AccumBounds(-3, -2)**(-2) == AccumBounds(Rational(1, 9), Rational(1, 4))
assert AccumBounds(0, oo)**S.Half == AccumBounds(0, oo)
assert AccumBounds(-oo, -1)**Rational(1, 3) == AccumBounds(-oo, -1)
assert AccumBounds(-2, 3)**(Rational(-1, 3)) == AccumBounds(-oo, oo)
assert AccumBounds(-oo, 0)**(-2) == AccumBounds(0, oo)
assert AccumBounds(-2, 0)**(-2) == AccumBounds(Rational(1, 4), oo)
assert AccumBounds(Rational(1, 3), S.Half)**oo is S.Zero
assert AccumBounds(0, S.Half)**oo is S.Zero
assert AccumBounds(S.Half, 1)**oo == AccumBounds(0, oo)
assert AccumBounds(0, 1)**oo == AccumBounds(0, oo)
assert AccumBounds(2, 3)**oo is oo
assert AccumBounds(1, 2)**oo == AccumBounds(0, oo)
assert AccumBounds(S.Half, 3)**oo == AccumBounds(0, oo)
assert AccumBounds(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
assert AccumBounds(-1, Rational(-1, 2))**oo == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)**oo == FiniteSet(-oo, oo)
assert AccumBounds(-2, -1)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-2, Rational(-1, 2))**oo == AccumBounds(-oo, oo)
assert AccumBounds(Rational(-1, 2), S.Half)**oo is S.Zero
assert AccumBounds(Rational(-1, 2), 1)**oo == AccumBounds(0, oo)
assert AccumBounds(Rational(-2, 3), 2)**oo == AccumBounds(0, oo)
assert AccumBounds(-1, 1)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, S.Half)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, 2)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-2, S.Half)**oo == AccumBounds(-oo, oo)
assert AccumBounds(1, 2)**x == Pow(AccumBounds(1, 2), x)
assert AccumBounds(2, 3)**(-oo) is S.Zero
assert AccumBounds(0, 2)**(-oo) == AccumBounds(0, oo)
assert AccumBounds(-1, 2)**(-oo) == AccumBounds(-oo, oo)
assert (tan(x)**sin(2*x)).subs(x, AccumBounds(0, pi/2)) == \
Pow(AccumBounds(-oo, oo), AccumBounds(0, 1))
def test_comparison_AccumBounds():
assert (AccumBounds(1, 3) < 4) == S.true
assert (AccumBounds(1, 3) < -1) == S.false
assert (AccumBounds(1, 3) < 2).rel_op == '<'
assert (AccumBounds(1, 3) <= 2).rel_op == '<='
assert (AccumBounds(1, 3) > 4) == S.false
assert (AccumBounds(1, 3) > -1) == S.true
assert (AccumBounds(1, 3) > 2).rel_op == '>'
assert (AccumBounds(1, 3) >= 2).rel_op == '>='
assert (AccumBounds(1, 3) < AccumBounds(4, 6)) == S.true
assert (AccumBounds(1, 3) < AccumBounds(2, 4)).rel_op == '<'
assert (AccumBounds(1, 3) < AccumBounds(-2, 0)) == S.false
assert (AccumBounds(1, 3) <= AccumBounds(4, 6)) == S.true
assert (AccumBounds(1, 3) <= AccumBounds(-2, 0)) == S.false
assert (AccumBounds(1, 3) > AccumBounds(4, 6)) == S.false
assert (AccumBounds(1, 3) > AccumBounds(-2, 0)) == S.true
assert (AccumBounds(1, 3) >= AccumBounds(4, 6)) == S.false
assert (AccumBounds(1, 3) >= AccumBounds(-2, 0)) == S.true
# issue 13499
assert (cos(x) > 0).subs(x, oo) == (AccumBounds(-1, 1) > 0)
c = Symbol('c')
raises(TypeError, lambda: (AccumBounds(0, 1) < c))
raises(TypeError, lambda: (AccumBounds(0, 1) <= c))
raises(TypeError, lambda: (AccumBounds(0, 1) > c))
raises(TypeError, lambda: (AccumBounds(0, 1) >= c))
def test_contains_AccumBounds():
assert (1 in AccumBounds(1, 2)) == S.true
raises(TypeError, lambda: a in AccumBounds(1, 2))
assert 0 in AccumBounds(-1, 0)
raises(TypeError, lambda:
(cos(1)**2 + sin(1)**2 - 1) in AccumBounds(-1, 0))
assert (-oo in AccumBounds(1, oo)) == S.true
assert (oo in AccumBounds(-oo, 0)) == S.true
# issue 13159
assert Mul(0, AccumBounds(-1, 1)) == Mul(AccumBounds(-1, 1), 0) == 0
import itertools
for perm in itertools.permutations([0, AccumBounds(-1, 1), x]):
assert Mul(*perm) == 0
def test_intersection_AccumBounds():
assert AccumBounds(0, 3).intersection(AccumBounds(1, 2)) == AccumBounds(1, 2)
assert AccumBounds(0, 3).intersection(AccumBounds(1, 4)) == AccumBounds(1, 3)
assert AccumBounds(0, 3).intersection(AccumBounds(-1, 2)) == AccumBounds(0, 2)
assert AccumBounds(0, 3).intersection(AccumBounds(-1, 4)) == AccumBounds(0, 3)
assert AccumBounds(0, 1).intersection(AccumBounds(2, 3)) == S.EmptySet
raises(TypeError, lambda: AccumBounds(0, 3).intersection(1))
def test_union_AccumBounds():
assert AccumBounds(0, 3).union(AccumBounds(1, 2)) == AccumBounds(0, 3)
assert AccumBounds(0, 3).union(AccumBounds(1, 4)) == AccumBounds(0, 4)
assert AccumBounds(0, 3).union(AccumBounds(-1, 2)) == AccumBounds(-1, 3)
assert AccumBounds(0, 3).union(AccumBounds(-1, 4)) == AccumBounds(-1, 4)
raises(TypeError, lambda: AccumBounds(0, 3).union(1))
def test_issue_16469():
x = Symbol("x", real=True)
f = abs(x)
assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)
def test_issue_18747():
assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
|
35f6c329ebbcd9851073d55d52929ba143bff332216fa7f61d27c55b3d1db761 | import itertools
from sympy.core import S
from sympy.core.containers import Tuple
from sympy.core.function import _coeff_isneg
from sympy.core.mul import Mul
from sympy.core.numbers import Number, Rational
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.core.sympify import SympifyError
from sympy.printing.conventions import requires_partial
from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.str import sstr
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import has_variety
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \
xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \
pretty_try_use_unicode, annotated
# rename for usage from outside
pprint_use_unicode = pretty_use_unicode
pprint_try_use_unicode = pretty_try_use_unicode
class PrettyPrinter(Printer):
"""Printer, which converts an expression into 2D ASCII-art figure."""
printmethod = "_pretty"
_default_settings = {
"order": None,
"full_prec": "auto",
"use_unicode": None,
"wrap_line": True,
"num_columns": None,
"use_unicode_sqrt_char": True,
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"perm_cyclic": True
}
def __init__(self, settings=None):
Printer.__init__(self, settings)
if not isinstance(self._settings['imaginary_unit'], str):
raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit']))
elif self._settings['imaginary_unit'] not in ["i", "j"]:
raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit']))
def emptyPrinter(self, expr):
return prettyForm(str(expr))
@property
def _use_unicode(self):
if self._settings['use_unicode']:
return True
else:
return pretty_use_unicode()
def doprint(self, expr):
return self._print(expr).render(**self._settings)
# empty op so _print(stringPict) returns the same
def _print_stringPict(self, e):
return e
def _print_basestring(self, e):
return prettyForm(e)
def _print_atan2(self, e):
pform = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(*pform.left('atan2'))
return pform
def _print_Symbol(self, e, bold_name=False):
symb = pretty_symbol(e.name, bold_name)
return prettyForm(symb)
_print_RandomSymbol = _print_Symbol
def _print_MatrixSymbol(self, e):
return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold")
def _print_Float(self, e):
# we will use StrPrinter's Float printer, but we need to handle the
# full_prec ourselves, according to the self._print_level
full_prec = self._settings["full_prec"]
if full_prec == "auto":
full_prec = self._print_level == 1
return prettyForm(sstr(e, full_prec=full_prec))
def _print_Cross(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Curl(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Divergence(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Dot(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Gradient(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Laplacian(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('INCREMENT'))))
return pform
def _print_Atom(self, e):
try:
# print atoms like Exp1 or Pi
return prettyForm(pretty_atom(e.__class__.__name__, printer=self))
except KeyError:
return self.emptyPrinter(e)
# Infinity inherits from Number, so we have to override _print_XXX order
_print_Infinity = _print_Atom
_print_NegativeInfinity = _print_Atom
_print_EmptySet = _print_Atom
_print_Naturals = _print_Atom
_print_Naturals0 = _print_Atom
_print_Integers = _print_Atom
_print_Rationals = _print_Atom
_print_Complexes = _print_Atom
_print_EmptySequence = _print_Atom
def _print_Reals(self, e):
if self._use_unicode:
return self._print_Atom(e)
else:
inf_list = ['-oo', 'oo']
return self._print_seq(inf_list, '(', ')')
def _print_subfactorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('!'))
return pform
def _print_factorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!'))
return pform
def _print_factorial2(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!!'))
return pform
def _print_binomial(self, e):
n, k = e.args
n_pform = self._print(n)
k_pform = self._print(k)
bar = ' '*max(n_pform.width(), k_pform.width())
pform = prettyForm(*k_pform.above(bar))
pform = prettyForm(*pform.above(n_pform))
pform = prettyForm(*pform.parens('(', ')'))
pform.baseline = (pform.baseline + 1)//2
return pform
def _print_Relational(self, e):
op = prettyForm(' ' + xsym(e.rel_op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
def _print_Not(self, e):
from sympy import Equivalent, Implies
if self._use_unicode:
arg = e.args[0]
pform = self._print(arg)
if isinstance(arg, Equivalent):
return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}")
if isinstance(arg, Implies):
return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}")
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left("\N{NOT SIGN}"))
else:
return self._print_Function(e)
def __print_Boolean(self, e, char, sort=True):
args = e.args
if sort:
args = sorted(e.args, key=default_sort_key)
arg = args[0]
pform = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
for arg in args[1:]:
pform_arg = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform_arg = prettyForm(*pform_arg.parens())
pform = prettyForm(*pform.right(' %s ' % char))
pform = prettyForm(*pform.right(pform_arg))
return pform
def _print_And(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL AND}")
else:
return self._print_Function(e, sort=True)
def _print_Or(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL OR}")
else:
return self._print_Function(e, sort=True)
def _print_Xor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{XOR}")
else:
return self._print_Function(e, sort=True)
def _print_Nand(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NAND}")
else:
return self._print_Function(e, sort=True)
def _print_Nor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NOR}")
else:
return self._print_Function(e, sort=True)
def _print_Implies(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False)
else:
return self._print_Function(e)
def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}")
else:
return self._print_Function(e, sort=True)
def _print_conjugate(self, e):
pform = self._print(e.args[0])
return prettyForm( *pform.above( hobj('_', pform.width())) )
def _print_Abs(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('|', '|'))
return pform
_print_Determinant = _print_Abs
def _print_floor(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lfloor', 'rfloor'))
return pform
else:
return self._print_Function(e)
def _print_ceiling(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lceil', 'rceil'))
return pform
else:
return self._print_Function(e)
def _print_Derivative(self, deriv):
if requires_partial(deriv.expr) and self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
count_total_deriv = 0
for sym, num in reversed(deriv.variable_count):
s = self._print(sym)
ds = prettyForm(*s.left(deriv_symbol))
count_total_deriv += num
if (not num.is_Integer) or (num > 1):
ds = ds**prettyForm(str(num))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if (count_total_deriv > 1) != False:
pform = pform**prettyForm(str(count_total_deriv))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Cycle(self, dc):
from sympy.combinatorics.permutations import Permutation, Cycle
# for Empty Cycle
if dc == Cycle():
cyc = stringPict('')
return prettyForm(*cyc.parens())
dc_list = Permutation(dc.list()).cyclic_form
# for Identity Cycle
if dc_list == []:
cyc = self._print(dc.size - 1)
return prettyForm(*cyc.parens())
cyc = stringPict('')
for i in dc_list:
l = self._print(str(tuple(i)).replace(',', ''))
cyc = prettyForm(*cyc.right(l))
return cyc
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(Cycle(expr))
lower = expr.array_form
upper = list(range(len(lower)))
result = stringPict('')
first = True
for u, l in zip(upper, lower):
s1 = self._print(u)
s2 = self._print(l)
col = prettyForm(*s1.below(s2))
if first:
first = False
else:
col = prettyForm(*col.left(" "))
result = prettyForm(*result.right(col))
return prettyForm(*result.parens())
def _print_Integral(self, integral):
f = integral.function
# Add parentheses if arg involves addition of terms and
# create a pretty form for the argument
prettyF = self._print(f)
# XXX generalize parens
if f.is_Add:
prettyF = prettyForm(*prettyF.parens())
# dx dy dz ...
arg = prettyF
for x in integral.limits:
prettyArg = self._print(x[0])
# XXX qparens (parens if needs-parens)
if prettyArg.width() > 1:
prettyArg = prettyForm(*prettyArg.parens())
arg = prettyForm(*arg.right(' d', prettyArg))
# \int \int \int ...
firstterm = True
s = None
for lim in integral.limits:
x = lim[0]
# Create bar based on the height of the argument
h = arg.height()
H = h + 2
# XXX hack!
ascii_mode = not self._use_unicode
if ascii_mode:
H += 2
vint = vobj('int', H)
# Construct the pretty form with the integral sign and the argument
pform = prettyForm(vint)
pform.baseline = arg.baseline + (
H - h)//2 # covering the whole argument
if len(lim) > 1:
# Create pretty forms for endpoints, if definite integral.
# Do not print empty endpoints.
if len(lim) == 2:
prettyA = prettyForm("")
prettyB = self._print(lim[1])
if len(lim) == 3:
prettyA = self._print(lim[1])
prettyB = self._print(lim[2])
if ascii_mode: # XXX hack
# Add spacing so that endpoint can more easily be
# identified with the correct integral sign
spc = max(1, 3 - prettyB.width())
prettyB = prettyForm(*prettyB.left(' ' * spc))
spc = max(1, 4 - prettyA.width())
prettyA = prettyForm(*prettyA.right(' ' * spc))
pform = prettyForm(*pform.above(prettyB))
pform = prettyForm(*pform.below(prettyA))
if not ascii_mode: # XXX hack
pform = prettyForm(*pform.right(' '))
if firstterm:
s = pform # first term
firstterm = False
else:
s = prettyForm(*s.left(pform))
pform = prettyForm(*arg.left(s))
pform.binding = prettyForm.MUL
return pform
def _print_Product(self, expr):
func = expr.term
pretty_func = self._print(func)
horizontal_chr = xobj('_', 1)
corner_chr = xobj('_', 1)
vertical_chr = xobj('|', 1)
if self._use_unicode:
# use unicode corners
horizontal_chr = xobj('-', 1)
corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}'
func_height = pretty_func.height()
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim)
width = (func_height + 2) * 5 // 3 - 2
sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr]
for _ in range(func_height + 1):
sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ')
pretty_sign = stringPict('')
pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))
max_upper = max(max_upper, pretty_upper.height())
if first:
sign_height = pretty_sign.height()
pretty_sign = prettyForm(*pretty_sign.above(pretty_upper))
pretty_sign = prettyForm(*pretty_sign.below(pretty_lower))
if first:
pretty_func.baseline = 0
first = False
height = pretty_sign.height()
padding = stringPict('')
padding = prettyForm(*padding.stack(*[' ']*(height - 1)))
pretty_sign = prettyForm(*pretty_sign.right(padding))
pretty_func = prettyForm(*pretty_sign.right(pretty_func))
pretty_func.baseline = max_upper + sign_height//2
pretty_func.binding = prettyForm.MUL
return pretty_func
def __print_SumProduct_Limits(self, lim):
def print_start(lhs, rhs):
op = prettyForm(' ' + xsym("==") + ' ')
l = self._print(lhs)
r = self._print(rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
prettyUpper = self._print(lim[2])
prettyLower = print_start(lim[0], lim[1])
return prettyLower, prettyUpper
def _print_Sum(self, expr):
ascii_mode = not self._use_unicode
def asum(hrequired, lower, upper, use_ascii):
def adjust(s, wid=None, how='<^>'):
if not wid or len(s) > wid:
return s
need = wid - len(s)
if how == '<^>' or how == "<" or how not in list('<^>'):
return s + ' '*need
half = need//2
lead = ' '*half
if how == ">":
return " "*need + s
return lead + s + ' '*(need - len(lead))
h = max(hrequired, 2)
d = h//2
w = d + 1
more = hrequired % 2
lines = []
if use_ascii:
lines.append("_"*(w) + ' ')
lines.append(r"\%s`" % (' '*(w - 1)))
for i in range(1, d):
lines.append('%s\\%s' % (' '*i, ' '*(w - i)))
if more:
lines.append('%s)%s' % (' '*(d), ' '*(w - d)))
for i in reversed(range(1, d)):
lines.append('%s/%s' % (' '*i, ' '*(w - i)))
lines.append("/" + "_"*(w - 1) + ',')
return d, h + more, lines, more
else:
w = w + more
d = d + more
vsum = vobj('sum', 4)
lines.append("_"*(w))
for i in range(0, d):
lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1)))
for i in reversed(range(0, d)):
lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1)))
lines.append(vsum[8]*(w))
return d, h + 2*more, lines, more
f = expr.function
prettyF = self._print(f)
if f.is_Add: # add parens
prettyF = prettyForm(*prettyF.parens())
H = prettyF.height() + 2
# \sum \sum \sum ...
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim)
max_upper = max(max_upper, prettyUpper.height())
# Create sum sign based on the height of the argument
d, h, slines, adjustment = asum(
H, prettyLower.width(), prettyUpper.width(), ascii_mode)
prettySign = stringPict('')
prettySign = prettyForm(*prettySign.stack(*slines))
if first:
sign_height = prettySign.height()
prettySign = prettyForm(*prettySign.above(prettyUpper))
prettySign = prettyForm(*prettySign.below(prettyLower))
if first:
# change F baseline so it centers on the sign
prettyF.baseline -= d - (prettyF.height()//2 -
prettyF.baseline)
first = False
# put padding to the right
pad = stringPict('')
pad = prettyForm(*pad.stack(*[' ']*h))
prettySign = prettyForm(*prettySign.right(pad))
# put the present prettyF to the right
prettyF = prettyForm(*prettySign.right(prettyF))
# adjust baseline of ascii mode sigma with an odd height so that it is
# exactly through the center
ascii_adjustment = ascii_mode if not adjustment else 0
prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment
prettyF.binding = prettyForm.MUL
return prettyF
def _print_Limit(self, l):
e, z, z0, dir = l.args
E = self._print(e)
if precedence(e) <= PRECEDENCE["Mul"]:
E = prettyForm(*E.parens('(', ')'))
Lim = prettyForm('lim')
LimArg = self._print(z)
if self._use_unicode:
LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}'))
else:
LimArg = prettyForm(*LimArg.right('->'))
LimArg = prettyForm(*LimArg.right(self._print(z0)))
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
dir = ""
else:
if self._use_unicode:
dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}'
LimArg = prettyForm(*LimArg.right(self._print(dir)))
Lim = prettyForm(*Lim.below(LimArg))
Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL)
return Lim
def _print_matrix_contents(self, e):
"""
This method factors out what is essentially grid printing.
"""
M = e # matrix
Ms = {} # i,j -> pretty(M[i,j])
for i in range(M.rows):
for j in range(M.cols):
Ms[i, j] = self._print(M[i, j])
# h- and v- spacers
hsep = 2
vsep = 1
# max width for columns
maxw = [-1] * M.cols
for j in range(M.cols):
maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0])
# drawing result
D = None
for i in range(M.rows):
D_row = None
for j in range(M.cols):
s = Ms[i, j]
# reshape s to maxw
# XXX this should be generalized, and go to stringPict.reshape ?
assert s.width() <= maxw[j]
# hcenter it, +0.5 to the right 2
# ( it's better to align formula starts for say 0 and r )
# XXX this is not good in all cases -- maybe introduce vbaseline?
wdelta = maxw[j] - s.width()
wleft = wdelta // 2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
# we don't need vcenter cells -- this is automatically done in
# a pretty way because when their baselines are taking into
# account in .right()
if D_row is None:
D_row = s # first box in a row
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
if D is None:
D = prettyForm('') # Empty Matrix
return D
def _print_MatrixBase(self, e):
D = self._print_matrix_contents(e)
D.baseline = D.height()//2
D = prettyForm(*D.parens('[', ']'))
return D
def _print_TensorProduct(self, expr):
# This should somehow share the code with _print_WedgeProduct:
circled_times = "\u2297"
return self._print_seq(expr.args, None, None, circled_times,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_WedgeProduct(self, expr):
# This should somehow share the code with _print_TensorProduct:
wedge_symbol = "\u2227"
return self._print_seq(expr.args, None, None, wedge_symbol,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_Trace(self, e):
D = self._print(e.arg)
D = prettyForm(*D.parens('(',')'))
D.baseline = D.height()//2
D = prettyForm(*D.left('\n'*(0) + 'tr'))
return D
def _print_MatrixElement(self, expr):
from sympy.matrices import MatrixSymbol
from sympy import Symbol
if (isinstance(expr.parent, MatrixSymbol)
and expr.i.is_number and expr.j.is_number):
return self._print(
Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j)))
else:
prettyFunc = self._print(expr.parent)
prettyFunc = prettyForm(*prettyFunc.parens())
prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', '
).parens(left='[', right=']')[0]
pform = prettyForm(binding=prettyForm.FUNC,
*stringPict.next(prettyFunc, prettyIndices))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyIndices
return pform
def _print_MatrixSlice(self, m):
# XXX works only for applied functions
from sympy.matrices import MatrixSymbol
prettyFunc = self._print(m.parent)
if not isinstance(m.parent, MatrixSymbol):
prettyFunc = prettyForm(*prettyFunc.parens())
def ppslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = ''
if x[1] == dim:
x[1] = ''
return prettyForm(*self._print_seq(x, delimiter=':'))
prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows),
ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0]
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_Transpose(self, expr):
pform = self._print(expr.arg)
from sympy.matrices import MatrixSymbol
if not isinstance(expr.arg, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**(prettyForm('T'))
return pform
def _print_Adjoint(self, expr):
pform = self._print(expr.arg)
if self._use_unicode:
dag = prettyForm('\N{DAGGER}')
else:
dag = prettyForm('+')
from sympy.matrices import MatrixSymbol
if not isinstance(expr.arg, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**dag
return pform
def _print_BlockMatrix(self, B):
if B.blocks.shape == (1, 1):
return self._print(B.blocks[0, 0])
return self._print(B.blocks)
def _print_MatAdd(self, expr):
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
coeff = item.as_coeff_mmul()[0]
if _coeff_isneg(S(coeff)):
s = prettyForm(*stringPict.next(s, ' '))
pform = self._print(item)
else:
s = prettyForm(*stringPict.next(s, ' + '))
s = prettyForm(*stringPict.next(s, pform))
return s
def _print_MatMul(self, expr):
args = list(expr.args)
from sympy import Add, MatAdd, HadamardProduct, KroneckerProduct
for i, a in enumerate(args):
if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct))
and len(expr.args) > 1):
args[i] = prettyForm(*self._print(a).parens())
else:
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_Identity(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}')
else:
return prettyForm('I')
def _print_ZeroMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}')
else:
return prettyForm('0')
def _print_OneMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}')
else:
return prettyForm('1')
def _print_DotProduct(self, expr):
args = list(expr.args)
for i, a in enumerate(args):
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_MatPow(self, expr):
pform = self._print(expr.base)
from sympy.matrices import MatrixSymbol
if not isinstance(expr.base, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**(self._print(expr.exp))
return pform
def _print_HadamardProduct(self, expr):
from sympy import MatAdd, MatMul, HadamardProduct
if self._use_unicode:
delim = pretty_atom('Ring')
else:
delim = '.*'
return self._print_seq(expr.args, None, None, delim,
parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct)))
def _print_HadamardPower(self, expr):
# from sympy import MatAdd, MatMul
if self._use_unicode:
circ = pretty_atom('Ring')
else:
circ = self._print('.')
pretty_base = self._print(expr.base)
pretty_exp = self._print(expr.exp)
if precedence(expr.exp) < PRECEDENCE["Mul"]:
pretty_exp = prettyForm(*pretty_exp.parens())
pretty_circ_exp = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(circ, pretty_exp)
)
return pretty_base**pretty_circ_exp
def _print_KroneckerProduct(self, expr):
from sympy import MatAdd, MatMul
if self._use_unicode:
delim = ' \N{N-ARY CIRCLED TIMES OPERATOR} '
else:
delim = ' x '
return self._print_seq(expr.args, None, None, delim,
parenthesize=lambda x: isinstance(x, (MatAdd, MatMul)))
def _print_FunctionMatrix(self, X):
D = self._print(X.lamda.expr)
D = prettyForm(*D.parens('[', ']'))
return D
def _print_TransferFunction(self, expr):
if not expr.num == 1:
num, den = expr.num, expr.den
res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False)
return self._print_Mul(res)
else:
return self._print(1)/self._print(expr.den)
def _print_Series(self, expr):
args = list(expr.args)
for i, a in enumerate(expr.args):
args[i] = prettyForm(*self._print(a).parens())
return prettyForm.__mul__(*args)
def _print_Parallel(self, expr):
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
s = prettyForm(*stringPict.next(s, ' + '))
s = prettyForm(*stringPict.next(s, pform))
return s
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Parallel, Series
num, tf = expr.num, TransferFunction(1, 1, expr.num.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.den.args) if isinstance(expr.den, Series) else [expr.den]
if isinstance(num, Series) and isinstance(expr.den, Series):
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
elif isinstance(num, Series) and isinstance(expr.den, TransferFunction):
if expr.den == tf:
den = Parallel(tf, Series(*num_arg_list))
else:
den = Parallel(tf, Series(*num_arg_list, expr.den))
elif isinstance(num, TransferFunction) and isinstance(expr.den, Series):
if num == tf:
den = Parallel(tf, Series(*den_arg_list))
else:
den = Parallel(tf, Series(num, *den_arg_list))
else:
if num == tf:
den = Parallel(tf, *den_arg_list)
elif expr.den == tf:
den = Parallel(tf, *num_arg_list)
else:
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
return self._print(num)/self._print(den)
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented")
if expr == expr.zero:
return prettyForm(expr.zero._pretty_form)
o1 = []
vectstrs = []
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key = lambda x: x[0].__str__())
for k, v in inneritems:
#if the coef of the basis vector is 1
#we skip the 1
if v == 1:
o1.append("" +
k._pretty_form)
#Same for -1
elif v == -1:
o1.append("(-1) " +
k._pretty_form)
#For a general expr
else:
#We always wrap the measure numbers in
#parentheses
arg_str = self._print(
v).parens()[0]
o1.append(arg_str + ' ' + k._pretty_form)
vectstrs.append(k._pretty_form)
#outstr = u("").join(o1)
if o1[0].startswith(" + "):
o1[0] = o1[0][3:]
elif o1[0].startswith(" "):
o1[0] = o1[0][1:]
#Fixing the newlines
lengths = []
strs = ['']
flag = []
for i, partstr in enumerate(o1):
flag.append(0)
# XXX: What is this hack?
if '\n' in partstr:
tempstr = partstr
tempstr = tempstr.replace(vectstrs[i], '')
if '\N{right parenthesis extension}' in tempstr: # If scalar is a fraction
for paren in range(len(tempstr)):
flag[i] = 1
if tempstr[paren] == '\N{right parenthesis extension}':
tempstr = tempstr[:paren] + '\N{right parenthesis extension}'\
+ ' ' + vectstrs[i] + tempstr[paren + 1:]
break
elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr:
flag[i] = 1
tempstr = tempstr.replace('\N{RIGHT PARENTHESIS LOWER HOOK}',
'\N{RIGHT PARENTHESIS LOWER HOOK}'
+ ' ' + vectstrs[i])
else:
tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}',
'\N{RIGHT PARENTHESIS UPPER HOOK}'
+ ' ' + vectstrs[i])
o1[i] = tempstr
o1 = [x.split('\n') for x in o1]
n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form
if 1 in flag: # If there was a fractional scalar
for i, parts in enumerate(o1):
if len(parts) == 1: # If part has no newline
parts.insert(0, ' ' * (len(parts[0])))
flag[i] = 1
for i, parts in enumerate(o1):
lengths.append(len(parts[flag[i]]))
for j in range(n_newlines):
if j+1 <= len(parts):
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
if j == flag[i]:
strs[flag[i]] += parts[flag[i]] + ' + '
else:
strs[j] += parts[j] + ' '*(lengths[-1] -
len(parts[j])+
3)
else:
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
strs[j] += ' '*(lengths[-1]+3)
return prettyForm('\n'.join([s[:-3] for s in strs]))
def _print_NDimArray(self, expr):
from sympy import ImmutableMatrix
if expr.rank() == 0:
return self._print(expr[()])
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
# leave eventual matrix elements unflattened
mat = lambda x: ImmutableMatrix(x, evaluate=False)
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(expr[outer_i])
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(level_str[back_outer_i+1])
else:
level_str[back_outer_i].append(mat(
level_str[back_outer_i+1]))
if len(level_str[back_outer_i + 1]) == 1:
level_str[back_outer_i][-1] = mat(
[[level_str[back_outer_i][-1]]])
even = not even
level_str[back_outer_i+1] = []
out_expr = level_str[0][0]
if expr.rank() % 2 == 1:
out_expr = mat([out_expr])
return self._print(out_expr)
def _printer_tensor_indices(self, name, indices, index_map={}):
center = stringPict(name)
top = stringPict(" "*center.width())
bot = stringPict(" "*center.width())
last_valence = None
prev_map = None
for i, index in enumerate(indices):
indpic = self._print(index.args[0])
if ((index in index_map) or prev_map) and last_valence == index.is_up:
if index.is_up:
top = prettyForm(*stringPict.next(top, ","))
else:
bot = prettyForm(*stringPict.next(bot, ","))
if index in index_map:
indpic = prettyForm(*stringPict.next(indpic, "="))
indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index])))
prev_map = True
else:
prev_map = False
if index.is_up:
top = stringPict(*top.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
bot = stringPict(*bot.right(" "*indpic.width()))
else:
bot = stringPict(*bot.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
top = stringPict(*top.right(" "*indpic.width()))
last_valence = index.is_up
pict = prettyForm(*center.above(top))
pict = prettyForm(*pict.below(bot))
return pict
def _print_Tensor(self, expr):
name = expr.args[0].name
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].name
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
sign, args = expr._get_args_for_traditional_printer()
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in args
]
pform = prettyForm.__mul__(*args)
if sign:
return prettyForm(*pform.left(sign))
else:
return pform
def _print_TensAdd(self, expr):
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in expr.args
]
return prettyForm.__add__(*args)
def _print_TensorIndex(self, expr):
sym = expr.args[0]
if not expr.is_up:
sym = -sym
return self._print(sym)
def _print_PartialDerivative(self, deriv):
if self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
for variable in reversed(deriv.variables):
s = self._print(variable)
ds = prettyForm(*s.left(deriv_symbol))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if len(deriv.variables) > 1:
pform = pform**self._print(len(deriv.variables))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Piecewise(self, pexpr):
P = {}
for n, ec in enumerate(pexpr.args):
P[n, 0] = self._print(ec.expr)
if ec.cond == True:
P[n, 1] = prettyForm('otherwise')
else:
P[n, 1] = prettyForm(
*prettyForm('for ').right(self._print(ec.cond)))
hsep = 2
vsep = 1
len_args = len(pexpr.args)
# max widths
maxw = [max([P[i, j].width() for i in range(len_args)])
for j in range(2)]
# FIXME: Refactor this code and matrix into some tabular environment.
# drawing result
D = None
for i in range(len_args):
D_row = None
for j in range(2):
p = P[i, j]
assert p.width() <= maxw[j]
wdelta = maxw[j] - p.width()
wleft = wdelta // 2
wright = wdelta - wleft
p = prettyForm(*p.right(' '*wright))
p = prettyForm(*p.left(' '*wleft))
if D_row is None:
D_row = p
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(p))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens('{', ''))
D.baseline = D.height()//2
D.binding = prettyForm.OPEN
return D
def _print_ITE(self, ite):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(ite.rewrite(Piecewise))
def _hprint_vec(self, v):
D = None
for a in v:
p = a
if D is None:
D = p
else:
D = prettyForm(*D.right(', '))
D = prettyForm(*D.right(p))
if D is None:
D = stringPict(' ')
return D
def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False):
if ifascii_nougly and not self._use_unicode:
return self._print_seq((p1, '|', p2), left=left, right=right,
delimiter=delimiter, ifascii_nougly=True)
tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter)
sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline)
return self._print_seq((p1, sep, p2), left=left, right=right,
delimiter=delimiter)
def _print_hyper(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
ap = [self._print(a) for a in e.ap]
bq = [self._print(b) for b in e.bq]
P = self._print(e.argument)
P.baseline = P.height()//2
# Drawing result - first create the ap, bq vectors
D = None
for v in [ap, bq]:
D_row = self._hprint_vec(v)
if D is None:
D = D_row # first row in a picture
else:
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the F symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('F')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
add = (sz + 1)//2
F = prettyForm(*F.left(self._print(len(e.ap))))
F = prettyForm(*F.right(self._print(len(e.bq))))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_meijerg(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
v = {}
v[(0, 0)] = [self._print(a) for a in e.an]
v[(0, 1)] = [self._print(a) for a in e.aother]
v[(1, 0)] = [self._print(b) for b in e.bm]
v[(1, 1)] = [self._print(b) for b in e.bother]
P = self._print(e.argument)
P.baseline = P.height()//2
vp = {}
for idx in v:
vp[idx] = self._hprint_vec(v[idx])
for i in range(2):
maxw = max(vp[(0, i)].width(), vp[(1, i)].width())
for j in range(2):
s = vp[(j, i)]
left = (maxw - s.width()) // 2
right = maxw - left - s.width()
s = prettyForm(*s.left(' ' * left))
s = prettyForm(*s.right(' ' * right))
vp[(j, i)] = s
D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)]))
D1 = prettyForm(*D1.below(' '))
D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)]))
D = prettyForm(*D1.below(D2))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the G symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('G')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
pp = self._print(len(e.ap))
pq = self._print(len(e.bq))
pm = self._print(len(e.bm))
pn = self._print(len(e.an))
def adjust(p1, p2):
diff = p1.width() - p2.width()
if diff == 0:
return p1, p2
elif diff > 0:
return p1, prettyForm(*p2.left(' '*diff))
else:
return prettyForm(*p1.left(' '*-diff)), p2
pp, pm = adjust(pp, pm)
pq, pn = adjust(pq, pn)
pu = prettyForm(*pm.right(', ', pn))
pl = prettyForm(*pp.right(', ', pq))
ht = F.baseline - above - 2
if ht > 0:
pu = prettyForm(*pu.below('\n'*ht))
p = prettyForm(*pu.below(pl))
F.baseline = above
F = prettyForm(*F.right(p))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_ExpBase(self, e):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
base = prettyForm(pretty_atom('Exp1', 'e'))
return base ** self._print(e.args[0])
def _print_Exp1(self, e):
return prettyForm(pretty_atom('Exp1', 'e'))
def _print_Function(self, e, sort=False, func_name=None):
# optional argument func_name for supplying custom names
# XXX works only for applied functions
return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name)
def _print_mathieuc(self, e):
return self._print_Function(e, func_name='C')
def _print_mathieus(self, e):
return self._print_Function(e, func_name='S')
def _print_mathieucprime(self, e):
return self._print_Function(e, func_name="C'")
def _print_mathieusprime(self, e):
return self._print_Function(e, func_name="S'")
def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False):
if sort:
args = sorted(args, key=default_sort_key)
if not func_name and hasattr(func, "__name__"):
func_name = func.__name__
if func_name:
prettyFunc = self._print(Symbol(func_name))
else:
prettyFunc = prettyForm(*self._print(func).parens())
if elementwise:
if self._use_unicode:
circ = pretty_atom('Modifier Letter Low Ring')
else:
circ = '.'
circ = self._print(circ)
prettyFunc = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(prettyFunc, circ)
)
prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_ElementwiseApplyFunction(self, e):
func = e.function
arg = e.expr
args = [arg]
return self._helper_print_function(func, args, delimiter="", elementwise=True)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.zeta_functions import lerchphi
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: [greek_unicode['delta'], 'delta'],
gamma: [greek_unicode['Gamma'], 'Gamma'],
lerchphi: [greek_unicode['Phi'], 'lerchphi'],
lowergamma: [greek_unicode['gamma'], 'gamma'],
beta: [greek_unicode['Beta'], 'B'],
DiracDelta: [greek_unicode['delta'], 'delta'],
Chi: ['Chi', 'Chi']}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
if self._use_unicode:
return prettyForm(self._special_function_classes[cls][0])
else:
return prettyForm(self._special_function_classes[cls][1])
func_name = expr.__name__
return prettyForm(pretty_symbol(func_name))
def _print_GeometryEntity(self, expr):
# GeometryEntity is based on Tuple but should not print like a Tuple
return self.emptyPrinter(expr)
def _print_lerchphi(self, e):
func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi'
return self._print_Function(e, func_name=func_name)
def _print_dirichlet_eta(self, e):
func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta'
return self._print_Function(e, func_name=func_name)
def _print_Heaviside(self, e):
func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside'
return self._print_Function(e, func_name=func_name)
def _print_fresnels(self, e):
return self._print_Function(e, func_name="S")
def _print_fresnelc(self, e):
return self._print_Function(e, func_name="C")
def _print_airyai(self, e):
return self._print_Function(e, func_name="Ai")
def _print_airybi(self, e):
return self._print_Function(e, func_name="Bi")
def _print_airyaiprime(self, e):
return self._print_Function(e, func_name="Ai'")
def _print_airybiprime(self, e):
return self._print_Function(e, func_name="Bi'")
def _print_LambertW(self, e):
return self._print_Function(e, func_name="W")
def _print_Lambda(self, e):
expr = e.expr
sig = e.signature
if self._use_unicode:
arrow = " \N{RIGHTWARDS ARROW FROM BAR} "
else:
arrow = " -> "
if len(sig) == 1 and sig[0].is_symbol:
sig = sig[0]
var_form = self._print(sig)
return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8)
def _print_Order(self, expr):
pform = self._print(expr.expr)
if (expr.point and any(p != S.Zero for p in expr.point)) or \
len(expr.variables) > 1:
pform = prettyForm(*pform.right("; "))
if len(expr.variables) > 1:
pform = prettyForm(*pform.right(self._print(expr.variables)))
elif len(expr.variables):
pform = prettyForm(*pform.right(self._print(expr.variables[0])))
if self._use_unicode:
pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} "))
else:
pform = prettyForm(*pform.right(" -> "))
if len(expr.point) > 1:
pform = prettyForm(*pform.right(self._print(expr.point)))
else:
pform = prettyForm(*pform.right(self._print(expr.point[0])))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left("O"))
return pform
def _print_SingularityFunction(self, e):
if self._use_unicode:
shift = self._print(e.args[0]-e.args[1])
n = self._print(e.args[2])
base = prettyForm("<")
base = prettyForm(*base.right(shift))
base = prettyForm(*base.right(">"))
pform = base**n
return pform
else:
n = self._print(e.args[2])
shift = self._print(e.args[0]-e.args[1])
base = self._print_seq(shift, "<", ">", ' ')
return base**n
def _print_beta(self, e):
func_name = greek_unicode['Beta'] if self._use_unicode else 'B'
return self._print_Function(e, func_name=func_name)
def _print_gamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_uppergamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_lowergamma(self, e):
func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma'
return self._print_Function(e, func_name=func_name)
def _print_DiracDelta(self, e):
if self._use_unicode:
if len(e.args) == 2:
a = prettyForm(greek_unicode['delta'])
b = self._print(e.args[1])
b = prettyForm(*b.parens())
c = self._print(e.args[0])
c = prettyForm(*c.parens())
pform = a**b
pform = prettyForm(*pform.right(' '))
pform = prettyForm(*pform.right(c))
return pform
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(greek_unicode['delta']))
return pform
else:
return self._print_Function(e)
def _print_expint(self, e):
from sympy import Function
if e.args[0].is_Integer and self._use_unicode:
return self._print_Function(Function('E_%s' % e.args[0])(e.args[1]))
return self._print_Function(e)
def _print_Chi(self, e):
# This needs a special case since otherwise it comes out as greek
# letter chi...
prettyFunc = prettyForm("Chi")
prettyArgs = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_elliptic_e(self, e):
pforma0 = self._print(e.args[0])
if len(e.args) == 1:
pform = pforma0
else:
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('E'))
return pform
def _print_elliptic_k(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('K'))
return pform
def _print_elliptic_f(self, e):
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('F'))
return pform
def _print_elliptic_pi(self, e):
name = greek_unicode['Pi'] if self._use_unicode else 'Pi'
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
if len(e.args) == 2:
pform = self._hprint_vseparator(pforma0, pforma1)
else:
pforma2 = self._print(e.args[2])
pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False)
pforma = prettyForm(*pforma.left('; '))
pform = prettyForm(*pforma.left(pforma0))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(name))
return pform
def _print_GoldenRatio(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('phi'))
return self._print(Symbol("GoldenRatio"))
def _print_EulerGamma(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('gamma'))
return self._print(Symbol("EulerGamma"))
def _print_Mod(self, expr):
pform = self._print(expr.args[0])
if pform.binding > prettyForm.MUL:
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right(' mod '))
pform = prettyForm(*pform.right(self._print(expr.args[1])))
pform.binding = prettyForm.OPEN
return pform
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
pforms, indices = [], []
def pretty_negative(pform, index):
"""Prepend a minus sign to a pretty form. """
#TODO: Move this code to prettyForm
if index == 0:
if pform.height() > 1:
pform_neg = '- '
else:
pform_neg = '-'
else:
pform_neg = ' - '
if (pform.binding > prettyForm.NEG
or pform.binding == prettyForm.ADD):
p = stringPict(*pform.parens())
else:
p = pform
p = stringPict.next(pform_neg, p)
# Lower the binding to NEG, even if it was higher. Otherwise, it
# will print as a + ( - (b)), instead of a - (b).
return prettyForm(binding=prettyForm.NEG, *p)
for i, term in enumerate(terms):
if term.is_Mul and _coeff_isneg(term):
coeff, other = term.as_coeff_mul(rational=False)
if coeff == -1:
negterm = Mul(*other, evaluate=False)
else:
negterm = Mul(-coeff, *other, evaluate=False)
pform = self._print(negterm)
pforms.append(pretty_negative(pform, i))
elif term.is_Rational and term.q > 1:
pforms.append(None)
indices.append(i)
elif term.is_Number and term < 0:
pform = self._print(-term)
pforms.append(pretty_negative(pform, i))
elif term.is_Relational:
pforms.append(prettyForm(*self._print(term).parens()))
else:
pforms.append(self._print(term))
if indices:
large = True
for pform in pforms:
if pform is not None and pform.height() > 1:
break
else:
large = False
for i in indices:
term, negative = terms[i], False
if term < 0:
term, negative = -term, True
if large:
pform = prettyForm(str(term.p))/prettyForm(str(term.q))
else:
pform = self._print(term)
if negative:
pform = pretty_negative(pform, i)
pforms[i] = pform
return prettyForm.__add__(*pforms)
def _print_Mul(self, product):
from sympy.physics.units import Quantity
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
args = product.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
strargs = list(map(self._print, args))
# XXX: This is a hack to work around the fact that
# prettyForm.__mul__ absorbs a leading -1 in the args. Probably it
# would be better to fix this in prettyForm.__mul__ instead.
negone = strargs[0] == '-1'
if negone:
strargs[0] = prettyForm('1', 0, 0)
obj = prettyForm.__mul__(*strargs)
if negone:
obj = prettyForm('-' + obj.s, obj.baseline, obj.binding)
return obj
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
if self.order not in ('old', 'none'):
args = product.as_ordered_factors()
else:
args = list(product.args)
# If quantities are present append them at the back
args = sorted(args, key=lambda x: isinstance(x, Quantity) or
(isinstance(x, Pow) and isinstance(x.base, Quantity)))
# Gather terms for numerator/denominator
for item in args:
if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append( Rational(item.p) )
if item.q != 1:
b.append( Rational(item.q) )
else:
a.append(item)
from sympy import Integral, Piecewise, Product, Sum
# Convert to pretty forms. Add parens to Add instances if there
# is more than one term in the numer/denom
for i in range(0, len(a)):
if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and
isinstance(a[i], (Integral, Piecewise, Product, Sum))):
a[i] = prettyForm(*self._print(a[i]).parens())
elif a[i].is_Relational:
a[i] = prettyForm(*self._print(a[i]).parens())
else:
a[i] = self._print(a[i])
for i in range(0, len(b)):
if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and
isinstance(b[i], (Integral, Piecewise, Product, Sum))):
b[i] = prettyForm(*self._print(b[i]).parens())
else:
b[i] = self._print(b[i])
# Construct a pretty form
if len(b) == 0:
return prettyForm.__mul__(*a)
else:
if len(a) == 0:
a.append( self._print(S.One) )
return prettyForm.__mul__(*a)/prettyForm.__mul__(*b)
# A helper function for _print_Pow to print x**(1/n)
def _print_nth_root(self, base, root):
bpretty = self._print(base)
# In very simple cases, use a single-char root sign
if (self._settings['use_unicode_sqrt_char'] and self._use_unicode
and root == 2 and bpretty.height() == 1
and (bpretty.width() == 1
or (base.is_Integer and base.is_nonnegative))):
return prettyForm(*bpretty.left('\N{SQUARE ROOT}'))
# Construct root sign, start with the \/ shape
_zZ = xobj('/', 1)
rootsign = xobj('\\', 1) + _zZ
# Constructing the number to put on root
rpretty = self._print(root)
# roots look bad if they are not a single line
if rpretty.height() != 1:
return self._print(base)**self._print(1/root)
# If power is half, no number should appear on top of root sign
exp = '' if root == 2 else str(rpretty).ljust(2)
if len(exp) > 2:
rootsign = ' '*(len(exp) - 2) + rootsign
# Stack the exponent
rootsign = stringPict(exp + '\n' + rootsign)
rootsign.baseline = 0
# Diagonal: length is one less than height of base
linelength = bpretty.height() - 1
diagonal = stringPict('\n'.join(
' '*(linelength - i - 1) + _zZ + ' '*i
for i in range(linelength)
))
# Put baseline just below lowest line: next to exp
diagonal.baseline = linelength - 1
# Make the root symbol
rootsign = prettyForm(*rootsign.right(diagonal))
# Det the baseline to match contents to fix the height
# but if the height of bpretty is one, the rootsign must be one higher
rootsign.baseline = max(1, bpretty.baseline)
#build result
s = prettyForm(hobj('_', 2 + bpretty.width()))
s = prettyForm(*bpretty.above(s))
s = prettyForm(*s.left(rootsign))
return s
def _print_Pow(self, power):
from sympy.simplify.simplify import fraction
b, e = power.as_base_exp()
if power.is_commutative:
if e is S.NegativeOne:
return prettyForm("1")/self._print(b)
n, d = fraction(e)
if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \
and self._settings['root_notation']:
return self._print_nth_root(b, d)
if e.is_Rational and e < 0:
return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))
if b.is_Relational:
return prettyForm(*self._print(b).parens()).__pow__(self._print(e))
return self._print(b)**self._print(e)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def __print_numer_denom(self, p, q):
if q == 1:
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)
else:
return prettyForm(str(p))
elif abs(p) >= 10 and abs(q) >= 10:
# If more than one digit in numer and denom, print larger fraction
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q))
# Old printing method:
#pform = prettyForm(str(-p))/prettyForm(str(q))
#return prettyForm(binding=prettyForm.NEG, *pform.left('- '))
else:
return prettyForm(str(p))/prettyForm(str(q))
else:
return None
def _print_Rational(self, expr):
result = self.__print_numer_denom(expr.p, expr.q)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_Fraction(self, expr):
result = self.__print_numer_denom(expr.numerator, expr.denominator)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_ProductSet(self, p):
if len(p.sets) >= 1 and not has_variety(p.sets):
return self._print(p.sets[0]) ** self._print(len(p.sets))
else:
prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x'
return self._print_seq(p.sets, None, None, ' %s ' % prod_char,
parenthesize=lambda set: set.is_Union or
set.is_Intersection or set.is_ProductSet)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_seq(items, '{', '}', ', ' )
def _print_Range(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif len(s) > 4:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
printset = tuple(s)
return self._print_seq(printset, '{', '}', ', ' )
def _print_Interval(self, i):
if i.start == i.end:
return self._print_seq(i.args[:1], '{', '}')
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return self._print_seq(i.args[:2], left, right)
def _print_AccumulationBounds(self, i):
left = '<'
right = '>'
return self._print_seq(i.args[:2], left, right)
def _print_Intersection(self, u):
delimiter = ' %s ' % pretty_atom('Intersection', 'n')
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Union or set.is_Complement)
def _print_Union(self, u):
union_delimiter = ' %s ' % pretty_atom('Union', 'U')
return self._print_seq(u.args, None, None, union_delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Intersection or set.is_Complement)
def _print_SymmetricDifference(self, u):
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented")
sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference')
return self._print_seq(u.args, None, None, sym_delimeter)
def _print_Complement(self, u):
delimiter = r' \ '
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or set.is_Intersection
or set.is_Union)
def _print_ImageSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
fun = ts.lamda
sets = ts.base_sets
signature = fun.signature
expr = self._print(fun.expr)
# TODO: the stuff to the left of the | and the stuff to the right of
# the | should have independent baselines, that way something like
# ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part
# centered on the right instead of aligned with the fraction bar on
# the left. The same also applies to ConditionSet and ComplexRegion
if len(signature) == 1:
S = self._print_seq((signature[0], inn, sets[0]),
delimiter=' ')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
else:
pargs = tuple(j for var, setv in zip(signature, sets) for j in
(var, ' ', inn, ' ', setv, ", "))
S = self._print_seq(pargs[:-1], delimiter='')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
def _print_ConditionSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
# using _and because and is a keyword and it is bad practice to
# overwrite them
_and = "\N{LOGICAL AND}"
else:
inn = 'in'
_and = 'and'
variables = self._print_seq(Tuple(ts.sym))
as_expr = getattr(ts.condition, 'as_expr', None)
if as_expr is not None:
cond = self._print(ts.condition.as_expr())
else:
cond = self._print(ts.condition)
if self._use_unicode:
cond = self._print(cond)
cond = prettyForm(*cond.parens())
if ts.base_set is S.UniversalSet:
return self._hprint_vseparator(variables, cond, left="{",
right="}", ifascii_nougly=True,
delimiter=' ')
base = self._print(ts.base_set)
C = self._print_seq((variables, inn, base, _and, cond),
delimiter=' ')
return self._hprint_vseparator(variables, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_ComplexRegion(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
variables = self._print_seq(ts.variables)
expr = self._print(ts.expr)
prodsets = self._print(ts.sets)
C = self._print_seq((variables, inn, prodsets),
delimiter=' ')
return self._hprint_vseparator(expr, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_Contains(self, e):
var, set = e.args
if self._use_unicode:
el = " \N{ELEMENT OF} "
return prettyForm(*stringPict.next(self._print(var),
el, self._print(set)), binding=8)
else:
return prettyForm(sstr(e))
def _print_FourierSeries(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
return self._print_Add(s.truncate()) + self._print(dots)
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_SetExpr(self, se):
pretty_set = prettyForm(*self._print(se.set).parens())
pretty_name = self._print(Symbol("SetExpr"))
return prettyForm(*pretty_name.right(pretty_set))
def _print_SeqFormula(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented")
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
printset = tuple(printset)
else:
printset = tuple(s)
return self._print_list(printset)
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_seq(self, seq, left=None, right=None, delimiter=', ',
parenthesize=lambda x: False, ifascii_nougly=True):
s = None
try:
for item in seq:
pform = self._print(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if s is None:
# first element
s = pform
else:
# XXX: Under the tests from #15686 this raises:
# AttributeError: 'Fake' object has no attribute 'baseline'
# This is caught below but that is not the right way to
# fix it.
s = prettyForm(*stringPict.next(s, delimiter))
s = prettyForm(*stringPict.next(s, pform))
if s is None:
s = stringPict('')
except AttributeError:
s = None
for item in seq:
pform = self.doprint(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if s is None:
# first element
s = pform
else :
s = prettyForm(*stringPict.next(s, delimiter))
s = prettyForm(*stringPict.next(s, pform))
if s is None:
s = stringPict('')
s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly))
return s
def join(self, delimiter, args):
pform = None
for arg in args:
if pform is None:
pform = arg
else:
pform = prettyForm(*pform.right(delimiter))
pform = prettyForm(*pform.right(arg))
if pform is None:
return prettyForm("")
else:
return pform
def _print_list(self, l):
return self._print_seq(l, '[', ']')
def _print_tuple(self, t):
if len(t) == 1:
ptuple = prettyForm(*stringPict.next(self._print(t[0]), ','))
return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True))
else:
return self._print_seq(t, '(', ')')
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for k in keys:
K = self._print(k)
V = self._print(d[k])
s = prettyForm(*stringPict.next(K, ': ', V))
items.append(s)
return self._print_seq(items, '{', '}')
def _print_Dict(self, d):
return self._print_dict(d)
def _print_set(self, s):
if not s:
return prettyForm('set()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
return pretty
def _print_frozenset(self, s):
if not s:
return prettyForm('frozenset()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True))
pretty = prettyForm(*stringPict.next(type(s).__name__, pretty))
return pretty
def _print_UniversalSet(self, s):
if self._use_unicode:
return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}")
else:
return prettyForm('UniversalSet')
def _print_PolyRing(self, ring):
return prettyForm(sstr(ring))
def _print_FracField(self, field):
return prettyForm(sstr(field))
def _print_FreeGroupElement(self, elm):
return prettyForm(str(elm))
def _print_PolyElement(self, poly):
return prettyForm(sstr(poly))
def _print_FracElement(self, frac):
return prettyForm(sstr(frac))
def _print_AlgebraicNumber(self, expr):
if expr.is_aliased:
return self._print(expr.as_poly().as_expr())
else:
return self._print(expr.as_expr())
def _print_ComplexRootOf(self, expr):
args = [self._print_Add(expr.expr, order='lex'), expr.index]
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('CRootOf'))
return pform
def _print_RootSum(self, expr):
args = [self._print_Add(expr.expr, order='lex')]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('RootSum'))
return pform
def _print_FiniteField(self, expr):
if self._use_unicode:
form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d'
else:
form = 'GF(%d)'
return prettyForm(pretty_symbol(form % expr.mod))
def _print_IntegerRing(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}')
else:
return prettyForm('ZZ')
def _print_RationalField(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}')
else:
return prettyForm('QQ')
def _print_RealField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL R}'
else:
prefix = 'RR'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_ComplexField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL C}'
else:
prefix = 'CC'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_PolynomialRing(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_FractionField(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '(', ')')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_PolynomialRingBase(self, expr):
g = expr.symbols
if str(expr.order) != str(expr.default_order):
g = g + ("order=" + str(expr.order),)
pform = self._print_seq(g, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_GroebnerBasis(self, basis):
exprs = [ self._print_Add(arg, order=basis.order)
for arg in basis.exprs ]
exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]"))
gens = [ self._print(gen) for gen in basis.gens ]
domain = prettyForm(
*prettyForm("domain=").right(self._print(basis.domain)))
order = prettyForm(
*prettyForm("order=").right(self._print(basis.order)))
pform = self.join(", ", [exprs] + gens + [domain, order])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(basis.__class__.__name__))
return pform
def _print_Subs(self, e):
pform = self._print(e.expr)
pform = prettyForm(*pform.parens())
h = pform.height() if pform.height() > 1 else 2
rvert = stringPict(vobj('|', h), baseline=pform.baseline)
pform = prettyForm(*pform.right(rvert))
b = pform.baseline
pform.baseline = pform.height() - 1
pform = prettyForm(*pform.right(self._print_seq([
self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])),
delimiter='') for v in zip(e.variables, e.point) ])))
pform.baseline = b
return pform
def _print_number_function(self, e, name):
# Print name_arg[0] for one argument or name_arg[0](arg[1])
# for more than one argument
pform = prettyForm(name)
arg = self._print(e.args[0])
pform_arg = prettyForm(" "*arg.width())
pform_arg = prettyForm(*pform_arg.below(arg))
pform = prettyForm(*pform.right(pform_arg))
if len(e.args) == 1:
return pform
m, x = e.args
# TODO: copy-pasted from _print_Function: can we do better?
prettyFunc = pform
prettyArgs = prettyForm(*self._print_seq([x]).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_euler(self, e):
return self._print_number_function(e, "E")
def _print_catalan(self, e):
return self._print_number_function(e, "C")
def _print_bernoulli(self, e):
return self._print_number_function(e, "B")
_print_bell = _print_bernoulli
def _print_lucas(self, e):
return self._print_number_function(e, "L")
def _print_fibonacci(self, e):
return self._print_number_function(e, "F")
def _print_tribonacci(self, e):
return self._print_number_function(e, "T")
def _print_stieltjes(self, e):
if self._use_unicode:
return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}')
else:
return self._print_number_function(e, "stieltjes")
def _print_KroneckerDelta(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(self._print(e.args[1])))
if self._use_unicode:
a = stringPict(pretty_symbol('delta'))
else:
a = stringPict('d')
b = pform
top = stringPict(*b.left(' '*a.width()))
bot = stringPict(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.below(top))
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.as_boolean())))
return pform
elif hasattr(d, 'set'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
pform = prettyForm(*pform.right(self._print(' in ')))
pform = prettyForm(*pform.right(self._print(d.set)))
return pform
elif hasattr(d, 'symbols'):
pform = self._print('Domain on ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
return pform
else:
return self._print(None)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(pretty_symbol(object.name))
def _print_Morphism(self, morphism):
arrow = xsym("-->")
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
tail = domain.right(arrow, codomain)[0]
return prettyForm(tail)
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(pretty_symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(":", pretty_morphism)[0])
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(
NamedMorphism(morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
circle = xsym(".")
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [pretty_symbol(component.name) for
component in morphism.components]
component_names_list.reverse()
component_names = circle.join(component_names_list) + ":"
pretty_name = self._print(component_names)
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(pretty_morphism)[0])
def _print_Category(self, category):
return self._print(pretty_symbol(category.name))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
pretty_result = self._print(diagram.premises)
if diagram.conclusions:
results_arrow = " %s " % xsym("==>")
pretty_conclusions = self._print(diagram.conclusions)[0]
pretty_result = pretty_result.right(
results_arrow, pretty_conclusions)
return prettyForm(pretty_result[0])
def _print_DiagramGrid(self, grid):
from sympy.matrices import Matrix
from sympy import Symbol
matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ")
for j in range(grid.width)]
for i in range(grid.height)])
return self._print_matrix_contents(matrix)
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return self._print_seq(m, '[', ']')
def _print_SubModule(self, M):
return self._print_seq(M.gens, '<', '>')
def _print_FreeModule(self, M):
return self._print(M.ring)**self._print(M.rank)
def _print_ModuleImplementedIdeal(self, M):
return self._print_seq([x for [x] in M._module.gens], '<', '>')
def _print_QuotientRing(self, R):
return self._print(R.ring) / self._print(R.base_ideal)
def _print_QuotientRingElement(self, R):
return self._print(R.data) + self._print(R.ring.base_ideal)
def _print_QuotientModuleElement(self, m):
return self._print(m.data) + self._print(m.module.killed_module)
def _print_QuotientModule(self, M):
return self._print(M.base) / self._print(M.killed_module)
def _print_MatrixHomomorphism(self, h):
matrix = self._print(h._sympy_matrix())
matrix.baseline = matrix.height() // 2
pform = prettyForm(*matrix.right(' : ', self._print(h.domain),
' %s> ' % hobj('-', 2), self._print(h.codomain)))
return pform
def _print_Manifold(self, manifold):
return self._print(manifold.name)
def _print_Patch(self, patch):
return self._print(patch.name)
def _print_CoordSystem(self, coords):
return self._print(coords.name)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(string))
def _print_BaseVectorField(self, field):
s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(s))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return self._print('\N{DOUBLE-STRUCK ITALIC SMALL D} ' + pretty_symbol(string))
else:
pform = self._print(field)
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left("\N{DOUBLE-STRUCK ITALIC SMALL D}"))
def _print_Tr(self, p):
#TODO: Handle indices
pform = self._print(p.args[0])
pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__)))
pform = prettyForm(*pform.right(')'))
return pform
def _print_primenu(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['nu']))
else:
pform = prettyForm(*pform.left('nu'))
return pform
def _print_primeomega(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['Omega']))
else:
pform = prettyForm(*pform.left('Omega'))
return pform
def _print_Quantity(self, e):
if e.name.name == 'degree':
pform = self._print("\N{DEGREE SIGN}")
return pform
else:
return self.emptyPrinter(e)
def _print_AssignmentBase(self, e):
op = prettyForm(' ' + xsym(e.op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
def _print_Str(self, s):
return self._print(s.name)
@print_function(PrettyPrinter)
def pretty(expr, **settings):
"""Returns a string containing the prettified form of expr.
For information on keyword arguments see pretty_print function.
"""
pp = PrettyPrinter(settings)
# XXX: this is an ugly hack, but at least it works
use_unicode = pp._settings['use_unicode']
uflag = pretty_use_unicode(use_unicode)
try:
return pp.doprint(expr)
finally:
pretty_use_unicode(uflag)
def pretty_print(expr, **kwargs):
"""Prints expr in pretty form.
pprint is just a shortcut for this function.
Parameters
==========
expr : expression
The expression to print.
wrap_line : bool, optional (default=True)
Line wrapping enabled/disabled.
num_columns : int or None, optional (default=None)
Number of columns before line breaking (default to None which reads
the terminal width), useful when using SymPy without terminal.
use_unicode : bool or None, optional (default=None)
Use unicode characters, such as the Greek letter pi instead of
the string pi.
full_prec : bool or string, optional (default="auto")
Use full precision.
order : bool or string, optional (default=None)
Set to 'none' for long expressions if slow; default is None.
use_unicode_sqrt_char : bool, optional (default=True)
Use compact single-character square root symbol (when unambiguous).
root_notation : bool, optional (default=True)
Set to 'False' for printing exponents of the form 1/n in fractional form.
By default exponent is printed in root form.
mat_symbol_style : string, optional (default="plain")
Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face.
By default the standard face is used.
imaginary_unit : string, optional (default="i")
Letter to use for imaginary unit when use_unicode is True.
Can be "i" (default) or "j".
"""
print(pretty(expr, **kwargs))
pprint = pretty_print
def pager_print(expr, **settings):
"""Prints expr using the pager, in pretty form.
This invokes a pager command using pydoc. Lines are not wrapped
automatically. This routine is meant to be used with a pager that allows
sideways scrolling, like ``less -S``.
Parameters are the same as for ``pretty_print``. If you wish to wrap lines,
pass ``num_columns=None`` to auto-detect the width of the terminal.
"""
from pydoc import pager
from locale import getpreferredencoding
if 'num_columns' not in settings:
settings['num_columns'] = 500000 # disable line wrap
pager(pretty(expr, **settings).encode(getpreferredencoding()))
|
79d5bdea7367825f6f5ac7978d2cea4a03ff615b526ef9c2c280e5b7c427c6e5 | 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,
Q)
from sympy.core import Expr, Mul
from sympy.core.parameters import _exp_is_pow
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"
with _exp_is_pow(True):
assert str(exp(x)) == "E**x"
def test_factorial():
n = Symbol('n', integer=True)
assert str(factorial(-2)) == "zoo"
assert str(factorial(0)) == "1"
assert str(factorial(7)) == "5040"
assert str(factorial(n)) == "factorial(n)"
assert str(factorial(2*n)) == "factorial(2*n)"
assert str(factorial(factorial(n))) == 'factorial(factorial(n))'
assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))'
assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))'
assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))'
assert str(subfactorial(3)) == "2"
assert str(subfactorial(n)) == "subfactorial(n)"
assert str(subfactorial(2*n)) == "subfactorial(2*n)"
def test_Function():
f = Function('f')
fx = f(x)
w = WildFunction('w')
assert str(f) == "f"
assert str(fx) == "f(x)"
assert str(w) == "w_"
def test_Geometry():
assert sstr(Point(0, 0)) == 'Point2D(0, 0)'
assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)'
assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)'
assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \
'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))'
assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \
'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))'
assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \
'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))'
assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \
'Ellipse(Point2D(S(1), S(2)), S(3), S(4))'
def test_GoldenRatio():
assert str(GoldenRatio) == "GoldenRatio"
def test_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]'
def test_Predicate():
assert sstr(Q.even) == 'Q.even'
def test_AppliedPredicate():
assert sstr(Q.even(x)) == 'Q.even(x)'
|
ffa63c5717168f96a1c41b94cbd8731786402f938d70900338e1699569b2a9a9 | 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, _both_exp_pow
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}"
@_both_exp_pow
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}\; \middle|\; x \in \mathbb{N}\right\}"
y = Symbol('y')
imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
assert latex(imgset) == \
r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\} , y \in \left\{3, 4\right\}\right\}"
imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
assert latex(imgset) == \
r"\left\{x + y\; \middle|\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}"
def test_latex_ConditionSet():
x = Symbol('x')
assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \
r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
r"\left\{x\; \middle|\; x^{2} = 1 \right\}"
def test_latex_ComplexRegion():
assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\
r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
def test_latex_Contains():
x = Symbol('x')
assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
def test_latex_sum():
assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Sum(x**2, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} x^{2}"
assert latex(Sum(x**2 + y, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \
r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}"
def test_latex_product():
assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Product(x**2, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} x^{2}"
assert latex(Product(x**2 + y, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Product(x, (x, -2, 2))**2) == \
r"\left(\prod_{x=-2}^{2} x\right)^{2}"
def test_latex_limits():
assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x"
# issue 8175
f = Function('f')
assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}"
assert latex(Limit(f(x), x, 0, "-")) == \
r"\lim_{x \to 0^-} f{\left(x \right)}"
# issue #10806
assert latex(Limit(f(x), x, 0)**2) == \
r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}"
# bi-directional limit
assert latex(Limit(f(x), x, 0, dir='+-')) == \
r"\lim_{x \to 0} f{\left(x \right)}"
def test_latex_log():
assert latex(log(x)) == r"\log{\left(x \right)}"
assert latex(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)\; \middle|\; \left( x, \ a\right) \in ' \
r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \
r'\cos{\left(a x \right)} = 0 \right\}'
def test_trace():
# Issue 15303
from sympy 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
|
82eb01d2da4e3f44d6217daa2fa65816ef20db7e7bb103814ab0de860be0d2c3 | # -*- 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, _both_exp_pow
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
@_both_exp_pow
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\
"""
ucode_str_3 = \
"""\
x \n\
ℯ + 2⋅x\
"""
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
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
# TODO: The "x in N" parts below should be centered independently of the
# 1/x**2 fraction
imgset = ImageSet(Lambda(x, 1/x**2), S.Naturals)
ascii_str = '''\
1 \n\
{-- | x in Naturals}
2 \n\
x '''
ucode_str = '''\
⎧1 │ ⎫\n\
⎪── │ x ∊ ℕ⎪\n\
⎨ 2 │ ⎬\n\
⎪x │ ⎪\n\
⎩ │ ⎭'''
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
imgset = ImageSet(Lambda((x, y), 1/(x + y)**2), S.Naturals, S.Naturals)
ascii_str = '''\
1 \n\
{-------- | x in Naturals, y in Naturals}
2 \n\
(x + y) '''
ucode_str = '''\
⎧ 1 │ ⎫
⎪──────── │ x ∊ ℕ, y ∊ ℕ⎪
⎨ 2 │ ⎬
⎪(x + y) │ ⎪
⎩ │ ⎭'''
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}'
condset = ConditionSet(x, 1/x**2 > 0)
ascii_str = '''\
1 \n\
{x | -- > 0}
2 \n\
x '''
ucode_str = '''\
⎧ │ ⎛1 ⎞⎫
⎪x │ ⎜── > 0⎟⎪
⎨ │ ⎜ 2 ⎟⎬
⎪ │ ⎝x ⎠⎪
⎩ │ ⎭'''
assert pretty(condset) == ascii_str
assert upretty(condset) == ucode_str
condset = ConditionSet(x, 1/x**2 > 0, S.Reals)
ascii_str = '''\
1 \n\
{x | x in (-oo, oo) and -- > 0}
2 \n\
x '''
ucode_str = '''\
⎧ │ ⎛1 ⎞⎫
⎪x │ x ∊ ℝ ∧ ⎜── > 0⎟⎪
⎨ │ ⎜ 2 ⎟⎬
⎪ │ ⎝x ⎠⎪
⎩ │ ⎭'''
assert pretty(condset) == ascii_str
assert upretty(condset) == ucode_str
def test_pretty_ComplexRegion():
from sympy import ComplexRegion
cregion = ComplexRegion(Interval(3, 5)*Interval(4, 6))
ascii_str = '{x + y*I | x, y in [3, 5] x [4, 6]}'
ucode_str = '{x + y⋅ⅈ │ x, y ∊ [3, 5] × [4, 6]}'
assert pretty(cregion) == ascii_str
assert upretty(cregion) == ucode_str
cregion = ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)
ascii_str = '{r*(I*sin(theta) + cos(theta)) | r, theta in [0, 1] x [0, 2*pi)}'
ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ [0, 1] × [0, 2⋅π)}'
assert pretty(cregion) == ascii_str
assert upretty(cregion) == ucode_str
cregion = ComplexRegion(Interval(3, 1/a**2)*Interval(4, 6))
ascii_str = '''\
1 \n\
{x + y*I | x, y in [3, --] x [4, 6]}
2 \n\
a '''
ucode_str = '''\
⎧ │ ⎡ 1 ⎤ ⎫
⎪x + y⋅ⅈ │ x, y ∊ ⎢3, ──⎥ × [4, 6]⎪
⎨ │ ⎢ 2⎥ ⎬
⎪ │ ⎣ a ⎦ ⎪
⎩ │ ⎭'''
assert pretty(cregion) == ascii_str
assert upretty(cregion) == ucode_str
cregion = ComplexRegion(Interval(0, 1/a**2)*Interval(0, 2*pi), polar=True)
ascii_str = '''\
1 \n\
{r*(I*sin(theta) + cos(theta)) | r, theta in [0, --] x [0, 2*pi)}
2 \n\
a '''
ucode_str = '''\
⎧ │ ⎡ 1 ⎤ ⎫
⎪r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ ⎢0, ──⎥ × [0, 2⋅π)⎪
⎨ │ ⎢ 2⎥ ⎬
⎪ │ ⎣ a ⎦ ⎪
⎩ │ ⎭'''
assert pretty(cregion) == ascii_str
assert upretty(cregion) == 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))) == \
' 1 \n'\
' --\n'\
' 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_17616():
assert pretty(pi**(1/exp(1))) == \
' / -1\\\n'\
' \\e /\n'\
'pi '
assert upretty(pi**(1/exp(1))) == \
' ⎛ -1⎞\n'\
' ⎝ℯ ⎠\n'\
'π '
assert pretty(pi**(1/pi)) == \
' 1 \n'\
' --\n'\
' pi\n'\
'pi '
assert upretty(pi**(1/pi)) == \
' 1\n'\
' ─\n'\
' π\n'\
'π '
assert pretty(pi**(1/EulerGamma)) == \
' 1 \n'\
' ----------\n'\
' EulerGamma\n'\
'pi '
assert upretty(pi**(1/EulerGamma)) == \
' 1\n'\
' ─\n'\
' γ\n'\
'π '
z = Symbol("x_17")
assert upretty(7**(1/z)) == \
'x₁₇___\n'\
' ╲╱ 7 '
assert pretty(7**(1/z)) == \
'x_17___\n'\
' \\/ 7 '
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"
|
e0a808d22d4d5dad20c2200e5f93a0b762307e69096dd326a063887787b5ecce | """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')
whitelist = [
"sympy.assumptions.predicates", # tested by test_predicates()
]
def test_all_classes_are_tested():
this = os.path.split(__file__)[0]
path = os.path.join(this, os.pardir, os.pardir)
sympy_path = os.path.abspath(path)
prefix = os.path.split(sympy_path)[0] + os.sep
re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
modules = {}
for root, dirs, files in os.walk(sympy_path):
module = root.replace(prefix, "").replace(os.sep, ".")
if module in whitelist:
continue
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
if not isinstance(cls, type):
# check instance of singleton class with same name
cls = type(cls)
return issubclass(cls, Basic)
names = list(filter(is_Basic, names))
if names:
modules[submodule] = names
ns = globals()
failed = []
for module, names in modules.items():
mod = module.replace('.', '__')
for name in names:
test = 'test_' + mod + '__' + name
if test not in ns:
failed.append(module + '.' + name)
assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)
def _test_args(obj):
all_basic = all(isinstance(arg, Basic) for arg in obj.args)
# Ideally obj.func(*obj.args) would always recreate the object, but for
# now, we only require it for objects with non-empty .args
recreatable = not obj.args or obj.func(*obj.args) == obj
return all_basic and recreatable
def test_sympy__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))
@SKIP("abstract class")
def test_sympy__assumptions__assume__Predicate():
pass
def test_predicates():
from sympy.assumptions.ask import get_known_facts_keys
predicates = get_known_facts_keys()
for p in predicates:
assert _test_args(p)
def test_sympy__assumptions__assume__UndefinedPredicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
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__rv__Distribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__SingleContinuousDistribution():
pass
def test_sympy__stats__drv__SingleDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain
assert _test_args(SingleDiscreteDomain(x, S.Naturals))
def test_sympy__stats__drv__ProductDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals)
Y = SingleDiscreteDomain(y, S.Integers)
assert _test_args(ProductDiscreteDomain(X, Y))
def test_sympy__stats__drv__SingleDiscretePSpace():
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))
def test_sympy__stats__drv__DiscretePSpace():
from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain
density = Lambda(x, 2**(-x))
domain = SingleDiscreteDomain(x, S.Naturals)
assert _test_args(DiscretePSpace(domain, density))
def test_sympy__stats__drv__ConditionalDiscreteDomain():
from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals0)
assert _test_args(ConditionalDiscreteDomain(X, x > 2))
def test_sympy__stats__joint_rv__JointPSpace():
from sympy.stats.joint_rv import JointPSpace, JointDistribution
assert _test_args(JointPSpace('X', JointDistribution(1)))
def test_sympy__stats__joint_rv__JointRandomSymbol():
from sympy.stats.joint_rv import JointRandomSymbol
assert _test_args(JointRandomSymbol(x))
def test_sympy__stats__joint_rv_types__JointDistributionHandmade():
from sympy 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__LogCauchyDistribution():
from sympy.stats.crv_types import LogCauchyDistribution
assert _test_args(LogCauchyDistribution(0, 1))
def test_sympy__stats__crv_types__LogisticDistribution():
from sympy.stats.crv_types import LogisticDistribution
assert _test_args(LogisticDistribution(0, 1))
def test_sympy__stats__crv_types__LogLogisticDistribution():
from sympy.stats.crv_types import LogLogisticDistribution
assert _test_args(LogLogisticDistribution(1, 1))
def test_sympy__stats__crv_types__LogitNormalDistribution():
from sympy.stats.crv_types import LogitNormalDistribution
assert _test_args(LogitNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LomaxDistribution():
from sympy.stats.crv_types import LomaxDistribution
assert _test_args(LomaxDistribution(1, 2))
def test_sympy__stats__crv_types__MaxwellDistribution():
from sympy.stats.crv_types import MaxwellDistribution
assert _test_args(MaxwellDistribution(1))
def test_sympy__stats__crv_types__MoyalDistribution():
from sympy.stats.crv_types import MoyalDistribution
assert _test_args(MoyalDistribution(1,2))
def test_sympy__stats__crv_types__NakagamiDistribution():
from sympy.stats.crv_types import NakagamiDistribution
assert _test_args(NakagamiDistribution(1, 1))
def test_sympy__stats__crv_types__NormalDistribution():
from sympy.stats.crv_types import NormalDistribution
assert _test_args(NormalDistribution(0, 1))
def test_sympy__stats__crv_types__GaussianInverseDistribution():
from sympy.stats.crv_types import GaussianInverseDistribution
assert _test_args(GaussianInverseDistribution(1, 1))
def test_sympy__stats__crv_types__ParetoDistribution():
from sympy.stats.crv_types import ParetoDistribution
assert _test_args(ParetoDistribution(1, 1))
def test_sympy__stats__crv_types__PowerFunctionDistribution():
from sympy.stats.crv_types import PowerFunctionDistribution
assert _test_args(PowerFunctionDistribution(2,0,1))
def test_sympy__stats__crv_types__QuadraticUDistribution():
from sympy.stats.crv_types import QuadraticUDistribution
assert _test_args(QuadraticUDistribution(1, 2))
def test_sympy__stats__crv_types__RaisedCosineDistribution():
from sympy.stats.crv_types import RaisedCosineDistribution
assert _test_args(RaisedCosineDistribution(1, 1))
def test_sympy__stats__crv_types__RayleighDistribution():
from sympy.stats.crv_types import RayleighDistribution
assert _test_args(RayleighDistribution(1))
def test_sympy__stats__crv_types__ReciprocalDistribution():
from sympy.stats.crv_types import ReciprocalDistribution
assert _test_args(ReciprocalDistribution(5, 30))
def test_sympy__stats__crv_types__ShiftedGompertzDistribution():
from sympy.stats.crv_types import ShiftedGompertzDistribution
assert _test_args(ShiftedGompertzDistribution(1, 1))
def test_sympy__stats__crv_types__StudentTDistribution():
from sympy.stats.crv_types import StudentTDistribution
assert _test_args(StudentTDistribution(1))
def test_sympy__stats__crv_types__TrapezoidalDistribution():
from sympy.stats.crv_types import TrapezoidalDistribution
assert _test_args(TrapezoidalDistribution(1, 2, 3, 4))
def test_sympy__stats__crv_types__TriangularDistribution():
from sympy.stats.crv_types import TriangularDistribution
assert _test_args(TriangularDistribution(-1, 0, 1))
def test_sympy__stats__crv_types__UniformDistribution():
from sympy.stats.crv_types import UniformDistribution
assert _test_args(UniformDistribution(0, 1))
def test_sympy__stats__crv_types__UniformSumDistribution():
from sympy.stats.crv_types import UniformSumDistribution
assert _test_args(UniformSumDistribution(1))
def test_sympy__stats__crv_types__VonMisesDistribution():
from sympy.stats.crv_types import VonMisesDistribution
assert _test_args(VonMisesDistribution(1, 1))
def test_sympy__stats__crv_types__WeibullDistribution():
from sympy.stats.crv_types import WeibullDistribution
assert _test_args(WeibullDistribution(1, 1))
def test_sympy__stats__crv_types__WignerSemicircleDistribution():
from sympy.stats.crv_types import WignerSemicircleDistribution
assert _test_args(WignerSemicircleDistribution(1))
def test_sympy__stats__drv_types__GeometricDistribution():
from sympy.stats.drv_types import GeometricDistribution
assert _test_args(GeometricDistribution(.5))
def test_sympy__stats__drv_types__HermiteDistribution():
from sympy.stats.drv_types import HermiteDistribution
assert _test_args(HermiteDistribution(1, 2))
def test_sympy__stats__drv_types__LogarithmicDistribution():
from sympy.stats.drv_types import LogarithmicDistribution
assert _test_args(LogarithmicDistribution(.5))
def test_sympy__stats__drv_types__NegativeBinomialDistribution():
from sympy.stats.drv_types import NegativeBinomialDistribution
assert _test_args(NegativeBinomialDistribution(.5, .5))
def test_sympy__stats__drv_types__FlorySchulzDistribution():
from sympy.stats.drv_types import FlorySchulzDistribution
assert _test_args(FlorySchulzDistribution(.5))
def test_sympy__stats__drv_types__PoissonDistribution():
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(PoissonDistribution(1))
def test_sympy__stats__drv_types__SkellamDistribution():
from sympy.stats.drv_types import SkellamDistribution
assert _test_args(SkellamDistribution(1, 1))
def test_sympy__stats__drv_types__YuleSimonDistribution():
from sympy.stats.drv_types import YuleSimonDistribution
assert _test_args(YuleSimonDistribution(.5))
def test_sympy__stats__drv_types__ZetaDistribution():
from sympy.stats.drv_types import ZetaDistribution
assert _test_args(ZetaDistribution(1.5))
def test_sympy__stats__joint_rv__JointDistribution():
from sympy.stats.joint_rv import JointDistribution
assert _test_args(JointDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution():
from sympy.stats.joint_rv_types import MultivariateNormalDistribution
assert _test_args(
MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution():
from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution
assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateTDistribution():
from sympy.stats.joint_rv_types import MultivariateTDistribution
assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1))
def test_sympy__stats__joint_rv_types__NormalGammaDistribution():
from sympy.stats.joint_rv_types import NormalGammaDistribution
assert _test_args(NormalGammaDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution():
from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution
v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4])
assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu))
def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution():
from sympy.stats.joint_rv_types import MultivariateBetaDistribution
assert _test_args(MultivariateBetaDistribution([1, 2, 3]))
def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution():
from sympy.stats.joint_rv_types import MultivariateEwensDistribution
assert _test_args(MultivariateEwensDistribution(5, 1))
def test_sympy__stats__joint_rv_types__MultinomialDistribution():
from sympy.stats.joint_rv_types import MultinomialDistribution
assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution():
from sympy.stats.joint_rv_types import NegativeMultinomialDistribution
assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__rv__RandomIndexedSymbol():
from sympy.stats.rv import RandomIndexedSymbol, pspace
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
X = DiscreteMarkovChain("X")
assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0])))
def test_sympy__stats__rv__RandomMatrixSymbol():
from sympy.stats.rv import RandomMatrixSymbol
from sympy.stats.random_matrix import RandomMatrixPSpace
pspace = RandomMatrixPSpace('P')
assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace))
def test_sympy__stats__stochastic_process__StochasticPSpace():
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.stochastic_process_types import StochasticProcess
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0)))
def test_sympy__stats__stochastic_process_types__StochasticProcess():
from sympy.stats.stochastic_process_types import StochasticProcess
assert _test_args(StochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__MarkovProcess():
from sympy.stats.stochastic_process_types import MarkovProcess
assert _test_args(MarkovProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess():
from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess
assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess():
from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess
assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__TransitionMatrixOf():
from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain
from sympy 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__stats__matrix_distributions__MatrixStudentTDistribution():
from sympy.stats.matrix_distributions import MatrixStudentTDistribution
from sympy import MatrixSymbol
v = symbols('v', positive=True)
Omega = MatrixSymbol('Omega', 3, 3)
Sigma = MatrixSymbol('Sigma', 1, 1)
Location = MatrixSymbol('Location', 1, 3)
assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma))
def test_sympy__utilities__matchpy_connector__WildDot():
from sympy.utilities.matchpy_connector import WildDot
assert _test_args(WildDot("w_"))
def test_sympy__utilities__matchpy_connector__WildPlus():
from sympy.utilities.matchpy_connector import WildPlus
assert _test_args(WildPlus("w__"))
def test_sympy__utilities__matchpy_connector__WildStar():
from sympy.utilities.matchpy_connector import WildStar
assert _test_args(WildStar("w___"))
def test_sympy__core__symbol__Str():
from sympy.core.symbol import Str
assert _test_args(Str('t'))
def test_sympy__core__symbol__Dummy():
from sympy.core.symbol import Dummy
assert _test_args(Dummy('t'))
def test_sympy__core__symbol__Symbol():
from sympy.core.symbol import Symbol
assert _test_args(Symbol('t'))
def test_sympy__core__symbol__Wild():
from sympy.core.symbol import Wild
assert _test_args(Wild('x', exclude=[x]))
@SKIP("abstract class")
def test_sympy__functions__combinatorial__factorials__CombinatorialFunction():
pass
def test_sympy__functions__combinatorial__factorials__FallingFactorial():
from sympy.functions.combinatorial.factorials import FallingFactorial
assert _test_args(FallingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__MultiFactorial():
from sympy.functions.combinatorial.factorials import MultiFactorial
assert _test_args(MultiFactorial(x))
def test_sympy__functions__combinatorial__factorials__RisingFactorial():
from sympy.functions.combinatorial.factorials import RisingFactorial
assert _test_args(RisingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__binomial():
from sympy.functions.combinatorial.factorials import binomial
assert _test_args(binomial(2, x))
def test_sympy__functions__combinatorial__factorials__subfactorial():
from sympy.functions.combinatorial.factorials import subfactorial
assert _test_args(subfactorial(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__motzkin():
from sympy.functions.combinatorial.numbers import motzkin
assert _test_args(motzkin(5))
def test_sympy__functions__combinatorial__numbers__fibonacci():
from sympy.functions.combinatorial.numbers import fibonacci
assert _test_args(fibonacci(x))
def test_sympy__functions__combinatorial__numbers__tribonacci():
from sympy.functions.combinatorial.numbers import tribonacci
assert _test_args(tribonacci(x))
def test_sympy__functions__combinatorial__numbers__harmonic():
from sympy.functions.combinatorial.numbers import harmonic
assert _test_args(harmonic(x, 2))
def test_sympy__functions__combinatorial__numbers__lucas():
from sympy.functions.combinatorial.numbers import lucas
assert _test_args(lucas(x))
def test_sympy__functions__combinatorial__numbers__partition():
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.numbers import partition
assert _test_args(partition(Symbol('a', integer=True)))
def test_sympy__functions__elementary__complexes__Abs():
from sympy.functions.elementary.complexes import Abs
assert _test_args(Abs(x))
def test_sympy__functions__elementary__complexes__adjoint():
from sympy.functions.elementary.complexes import adjoint
assert _test_args(adjoint(x))
def test_sympy__functions__elementary__complexes__arg():
from sympy.functions.elementary.complexes import arg
assert _test_args(arg(x))
def test_sympy__functions__elementary__complexes__conjugate():
from sympy.functions.elementary.complexes import conjugate
assert _test_args(conjugate(x))
def test_sympy__functions__elementary__complexes__im():
from sympy.functions.elementary.complexes import im
assert _test_args(im(x))
def test_sympy__functions__elementary__complexes__re():
from sympy.functions.elementary.complexes import re
assert _test_args(re(x))
def test_sympy__functions__elementary__complexes__sign():
from sympy.functions.elementary.complexes import sign
assert _test_args(sign(x))
def test_sympy__functions__elementary__complexes__polar_lift():
from sympy.functions.elementary.complexes import polar_lift
assert _test_args(polar_lift(x))
def test_sympy__functions__elementary__complexes__periodic_argument():
from sympy.functions.elementary.complexes import periodic_argument
assert _test_args(periodic_argument(x, y))
def test_sympy__functions__elementary__complexes__principal_branch():
from sympy.functions.elementary.complexes import principal_branch
assert _test_args(principal_branch(x, y))
def test_sympy__functions__elementary__complexes__transpose():
from sympy.functions.elementary.complexes import transpose
assert _test_args(transpose(x))
def test_sympy__functions__elementary__exponential__LambertW():
from sympy.functions.elementary.exponential import LambertW
assert _test_args(LambertW(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__exponential__ExpBase():
pass
def test_sympy__functions__elementary__exponential__exp():
from sympy.functions.elementary.exponential import exp
assert _test_args(exp(2))
def test_sympy__functions__elementary__exponential__exp_polar():
from sympy.functions.elementary.exponential import exp_polar
assert _test_args(exp_polar(2))
def test_sympy__functions__elementary__exponential__log():
from sympy.functions.elementary.exponential import log
assert _test_args(log(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction():
pass
def test_sympy__functions__elementary__hyperbolic__acosh():
from sympy.functions.elementary.hyperbolic import acosh
assert _test_args(acosh(2))
def test_sympy__functions__elementary__hyperbolic__acoth():
from sympy.functions.elementary.hyperbolic import acoth
assert _test_args(acoth(2))
def test_sympy__functions__elementary__hyperbolic__asinh():
from sympy.functions.elementary.hyperbolic import asinh
assert _test_args(asinh(2))
def test_sympy__functions__elementary__hyperbolic__atanh():
from sympy.functions.elementary.hyperbolic import atanh
assert _test_args(atanh(2))
def test_sympy__functions__elementary__hyperbolic__asech():
from sympy.functions.elementary.hyperbolic import asech
assert _test_args(asech(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__array__expressions__array_expressions__ZeroArray():
from sympy.tensor.array.expressions.array_expressions import ZeroArray
m, n, k = symbols("m n k")
za = ZeroArray(m, n, k, 2)
assert _test_args(za)
def test_sympy__tensor__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
A = MatrixSymbol("A", 4, 4)
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))
|
9211f0617a39448b21963825c7828b90865595229f87c85e513efd6e6c812808 | import numbers as nums
import decimal
from sympy import (Rational, Symbol, Float, I, sqrt, cbrt, oo, nan, pi, E,
Integer, S, factorial, Catalan, EulerGamma, GoldenRatio,
TribonacciConstant, cos, exp,
Number, zoo, log, Mul, Pow, Tuple, latex, Gt, Lt, Ge, Le,
AlgebraicNumber, simplify, sin, fibonacci, RealField,
sympify, srepr, Dummy, Sum)
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import (igcd, ilcm, igcdex, seterr,
igcd2, igcd_lehmer, mpf_norm, comp, mod_inverse)
from sympy.core.power import integer_nthroot, isqrt, integer_log
from sympy.polys.domains.groundtypes import PythonRational
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.iterables import permutations
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
from mpmath import mpf
from mpmath.rational import mpq
import mpmath
from sympy.core import numbers
t = Symbol('t', real=False)
_ninf = float(-oo)
_inf = float(oo)
def same_and_same_prec(a, b):
# stricter matching for Floats
return a == b and a._prec == b._prec
def test_seterr():
seterr(divide=True)
raises(ValueError, lambda: S.Zero/S.Zero)
seterr(divide=False)
assert S.Zero / S.Zero is S.NaN
def test_mod():
x = S.Half
y = Rational(3, 4)
z = Rational(5, 18043)
assert x % x == 0
assert x % y == S.Half
assert x % z == Rational(3, 36086)
assert y % x == Rational(1, 4)
assert y % y == 0
assert y % z == Rational(9, 72172)
assert z % x == Rational(5, 18043)
assert z % y == Rational(5, 18043)
assert z % z == 0
a = Float(2.6)
assert (a % .2) == 0.0
assert (a % 2).round(15) == 0.6
assert (a % 0.5).round(15) == 0.1
p = Symbol('p', infinite=True)
assert oo % oo is nan
assert zoo % oo is nan
assert 5 % oo is nan
assert p % 5 is nan
# In these two tests, if the precision of m does
# not match the precision of the ans, then it is
# likely that the change made now gives an answer
# with degraded accuracy.
r = Rational(500, 41)
f = Float('.36', 3)
m = r % f
ans = Float(r % Rational(f), 3)
assert m == ans and m._prec == ans._prec
f = Float('8.36', 3)
m = f % r
ans = Float(Rational(f) % r, 3)
assert m == ans and m._prec == ans._prec
s = S.Zero
assert s % float(1) == 0.0
# No rounding required since these numbers can be represented
# exactly.
assert Rational(3, 4) % Float(1.1) == 0.75
assert Float(1.5) % Rational(5, 4) == 0.25
assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25
assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25')
assert 2.75 % Float('1.5') == Float('1.25')
a = Integer(7)
b = Integer(4)
assert type(a % b) == Integer
assert a % b == Integer(3)
assert Integer(1) % Rational(2, 3) == Rational(1, 3)
assert Rational(7, 5) % Integer(1) == Rational(2, 5)
assert Integer(2) % 1.5 == 0.5
assert Integer(3).__rmod__(Integer(10)) == Integer(1)
assert Integer(10) % 4 == Integer(2)
assert 15 % Integer(4) == Integer(3)
def test_divmod():
assert divmod(S(12), S(8)) == Tuple(1, 4)
assert divmod(-S(12), S(8)) == Tuple(-2, 4)
assert divmod(S.Zero, S.One) == Tuple(0, 0)
raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero))
raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero))
assert divmod(S(12), 8) == Tuple(1, 4)
assert divmod(12, S(8)) == Tuple(1, 4)
assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2"))
assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5"))
assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0"))
assert divmod(S("2"), S(".1"))[0] == 19
assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("2"), 2) == Tuple(S("1"), S("0"))
assert divmod(2, S("2")) == Tuple(S("1"), S("0"))
assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5"))
assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2"))
assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5"))
assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6"))
assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3/2"), S("0.1"))[0] == 14
assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2"))
assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0"))
assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0"))
assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0"))
assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0"))
assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5"))
assert divmod(2, S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5"))
assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1"))
assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3"))
assert divmod(2, S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3"))
assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1"))
assert divmod(2, S("0.1"))[0] == 19
assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1"))
assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0"))
assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1"))
assert str(divmod(S("2"), 0.3)) == '(6, 0.2)'
assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)'
assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)'
assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)'
assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)'
assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)'
assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)'
assert divmod(-3, S(2)) == (-2, 1)
assert divmod(S(-3), S(2)) == (-2, 1)
assert divmod(S(-3), 2) == (-2, 1)
assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2)
assert divmod(S(4), S(-2.1)) == divmod(4, -2.1)
assert divmod(S(-8), S(-2.5) ) == Tuple(3 , -0.5)
assert divmod(oo, 1) == (S.NaN, S.NaN)
assert divmod(S.NaN, 1) == (S.NaN, S.NaN)
assert divmod(1, S.NaN) == (S.NaN, S.NaN)
ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)]
OO = float('inf')
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, oo) for i in range(-2, 3)] == ans
ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)]
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, -oo) for i in range(-2, 3)] == ans
assert [divmod(i, -OO) for i in range(-2, 3)] == ANS
assert divmod(S(3.5), S(-2)) == divmod(3.5, -2)
assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2)
assert divmod(S(0.0), S(9)) == divmod(0.0, 9)
assert divmod(S(0), S(9.0)) == divmod(0, 9.0)
def test_igcd():
assert igcd(0, 0) == 0
assert igcd(0, 1) == 1
assert igcd(1, 0) == 1
assert igcd(0, 7) == 7
assert igcd(7, 0) == 7
assert igcd(7, 1) == 1
assert igcd(1, 7) == 1
assert igcd(-1, 0) == 1
assert igcd(0, -1) == 1
assert igcd(-1, -1) == 1
assert igcd(-1, 7) == 1
assert igcd(7, -1) == 1
assert igcd(8, 2) == 2
assert igcd(4, 8) == 4
assert igcd(8, 16) == 8
assert igcd(7, -3) == 1
assert igcd(-7, 3) == 1
assert igcd(-7, -3) == 1
assert igcd(*[10, 20, 30]) == 10
raises(TypeError, lambda: igcd())
raises(TypeError, lambda: igcd(2))
raises(ValueError, lambda: igcd(0, None))
raises(ValueError, lambda: igcd(1, 2.2))
for args in permutations((45.1, 1, 30)):
raises(ValueError, lambda: igcd(*args))
for args in permutations((1, 2, None)):
raises(ValueError, lambda: igcd(*args))
def test_igcd_lehmer():
a, b = fibonacci(10001), fibonacci(10000)
# len(str(a)) == 2090
# small divisors, long Euclidean sequence
assert igcd_lehmer(a, b) == 1
c = fibonacci(100)
assert igcd_lehmer(a*c, b*c) == c
# big divisor
assert igcd_lehmer(a, 10**1000) == 1
# swapping argmument
assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1)
def test_igcd2():
# short loop
assert igcd2(2**100 - 1, 2**99 - 1) == 1
# Lehmer's algorithm
a, b = int(fibonacci(10001)), int(fibonacci(10000))
assert igcd2(a, b) == 1
def test_ilcm():
assert ilcm(0, 0) == 0
assert ilcm(1, 0) == 0
assert ilcm(0, 1) == 0
assert ilcm(1, 1) == 1
assert ilcm(2, 1) == 2
assert ilcm(8, 2) == 8
assert ilcm(8, 6) == 24
assert ilcm(8, 7) == 56
assert ilcm(*[10, 20, 30]) == 60
raises(ValueError, lambda: ilcm(8.1, 7))
raises(ValueError, lambda: ilcm(8, 7.1))
raises(TypeError, lambda: ilcm(8))
def test_igcdex():
assert igcdex(2, 3) == (-1, 1, 1)
assert igcdex(10, 12) == (-1, 1, 2)
assert igcdex(100, 2004) == (-20, 1, 4)
assert igcdex(0, 0) == (0, 1, 0)
assert igcdex(1, 0) == (1, 0, 1)
def _strictly_equal(a, b):
return (a.p, a.q, type(a.p), type(a.q)) == \
(b.p, b.q, type(b.p), type(b.q))
def _test_rational_new(cls):
"""
Tests that are common between Integer and Rational.
"""
assert cls(0) is S.Zero
assert cls(1) is S.One
assert cls(-1) is S.NegativeOne
# These look odd, but are similar to int():
assert cls('1') is S.One
assert cls('-1') is S.NegativeOne
i = Integer(10)
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls(int(10)))
assert _strictly_equal(i, cls(i))
raises(TypeError, lambda: cls(Symbol('x')))
def test_Integer_new():
"""
Test for Integer constructor
"""
_test_rational_new(Integer)
assert _strictly_equal(Integer(0.9), S.Zero)
assert _strictly_equal(Integer(10.5), Integer(10))
raises(ValueError, lambda: Integer("10.5"))
assert Integer(Rational('1.' + '9'*20)) == 1
def test_Rational_new():
""""
Test for Rational constructor
"""
_test_rational_new(Rational)
n1 = S.Half
assert n1 == Rational(Integer(1), 2)
assert n1 == Rational(Integer(1), Integer(2))
assert n1 == Rational(1, Integer(2))
assert n1 == Rational(S.Half)
assert 1 == Rational(n1, n1)
assert Rational(3, 2) == Rational(S.Half, Rational(1, 3))
assert Rational(3, 1) == Rational(1, Rational(1, 3))
n3_4 = Rational(3, 4)
assert Rational('3/4') == n3_4
assert -Rational('-3/4') == n3_4
assert Rational('.76').limit_denominator(4) == n3_4
assert Rational(19, 25).limit_denominator(4) == n3_4
assert Rational('19/25').limit_denominator(4) == n3_4
assert Rational(1.0, 3) == Rational(1, 3)
assert Rational(1, 3.0) == Rational(1, 3)
assert Rational(Float(0.5)) == S.Half
assert Rational('1e2/1e-2') == Rational(10000)
assert Rational('1 234') == Rational(1234)
assert Rational('1/1 234') == Rational(1, 1234)
assert Rational(-1, 0) is S.ComplexInfinity
assert Rational(1, 0) is S.ComplexInfinity
# Make sure Rational doesn't lose precision on Floats
assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100)
raises(TypeError, lambda: Rational('3**3'))
raises(TypeError, lambda: Rational('1/2 + 2/3'))
# handle fractions.Fraction instances
try:
import fractions
assert Rational(fractions.Fraction(1, 2)) == S.Half
except ImportError:
pass
assert Rational(mpq(2, 6)) == Rational(1, 3)
assert Rational(PythonRational(2, 6)) == Rational(1, 3)
def test_Number_new():
""""
Test for Number constructor
"""
# Expected behavior on numbers and strings
assert Number(1) is S.One
assert Number(2).__class__ is Integer
assert Number(-622).__class__ is Integer
assert Number(5, 3).__class__ is Rational
assert Number(5.3).__class__ is Float
assert Number('1') is S.One
assert Number('2').__class__ is Integer
assert Number('-622').__class__ is Integer
assert Number('5/3').__class__ is Rational
assert Number('5.3').__class__ is Float
raises(ValueError, lambda: Number('cos'))
raises(TypeError, lambda: Number(cos))
a = Rational(3, 5)
assert Number(a) is a # Check idempotence on Numbers
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Number(i) is a, (i, Number(i), a)
def test_Number_cmp():
n1 = Number(1)
n2 = Number(2)
n3 = Number(-3)
assert n1 < n2
assert n1 <= n2
assert n3 < n1
assert n2 > n3
assert n2 >= n3
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Rational_cmp():
n1 = Rational(1, 4)
n2 = Rational(1, 3)
n3 = Rational(2, 4)
n4 = Rational(2, -4)
n5 = Rational(0)
n6 = Rational(1)
n7 = Rational(3)
n8 = Rational(-3)
assert n8 < n5
assert n5 < n6
assert n6 < n7
assert n8 < n7
assert n7 > n8
assert (n1 + 1)**n2 < 2
assert ((n1 + n6)/n7) < 1
assert n4 < n3
assert n2 < n3
assert n1 < n2
assert n3 > n1
assert not n3 < n1
assert not (Rational(-1) > 0)
assert Rational(-1) < 0
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Float():
def eq(a, b):
t = Float("1.0E-15")
return (-t < a - b < t)
zeros = (0, S.Zero, 0., Float(0))
for i, j in permutations(zeros, 2):
assert i == j
for z in zeros:
assert z in zeros
assert S.Zero.is_zero
a = Float(2) ** Float(3)
assert eq(a.evalf(), Float(8))
assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
a = Float(2) ** Float(4)
assert eq(a.evalf(), Float(16))
assert (S(.3) == S(.5)) is False
mpf = (0, 5404319552844595, -52, 53)
x_str = Float((0, '13333333333333', -52, 53))
x2_str = Float((0, '26666666666666', -53, 54))
x_hex = Float((0, int(0x13333333333333), -52, 53))
x_dec = Float(mpf)
assert x_str == x_hex == x_dec == Float(1.2)
# x2_str was entered slightly malformed in that the mantissa
# was even -- it should be odd and the even part should be
# included with the exponent, but this is resolved by normalization
# ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must
# be exact: double the mantissa ==> increase bc by 1
assert Float(1.2)._mpf_ == mpf
assert x2_str._mpf_ == mpf
assert Float((0, int(0), -123, -1)) is S.NaN
assert Float((0, int(0), -456, -2)) is S.Infinity
assert Float((1, int(0), -789, -3)) is S.NegativeInfinity
# if you don't give the full signature, it's not special
assert Float((0, int(0), -123)) == Float(0)
assert Float((0, int(0), -456)) == Float(0)
assert Float((1, int(0), -789)) == Float(0)
raises(ValueError, lambda: Float((0, 7, 1, 3), ''))
assert Float('0.0').is_finite is True
assert Float('0.0').is_negative is False
assert Float('0.0').is_positive is False
assert Float('0.0').is_infinite is False
assert Float('0.0').is_zero is True
# rationality properties
# if the integer test fails then the use of intlike
# should be removed from gamma_functions.py
assert Float(1).is_integer is False
assert Float(1).is_rational is None
assert Float(1).is_irrational is None
assert sqrt(2).n(15).is_rational is None
assert sqrt(2).n(15).is_irrational is None
# do not automatically evalf
def teq(a):
assert (a.evalf() == a) is False
assert (a.evalf() != a) is True
assert (a == a.evalf()) is False
assert (a != a.evalf()) is True
teq(pi)
teq(2*pi)
teq(cos(0.1, evaluate=False))
# long integer
i = 12345678901234567890
assert same_and_same_prec(Float(12, ''), Float('12', ''))
assert same_and_same_prec(Float(Integer(i), ''), Float(i, ''))
assert same_and_same_prec(Float(i, ''), Float(str(i), 20))
assert same_and_same_prec(Float(str(i)), Float(i, ''))
assert same_and_same_prec(Float(i), Float(i, ''))
# inexact floats (repeating binary = denom not multiple of 2)
# cannot have precision greater than 15
assert Float(.125, 22) == .125
assert Float(2.0, 22) == 2
assert float(Float('.12500000000000001', '')) == .125
raises(ValueError, lambda: Float(.12500000000000001, ''))
# allow spaces
Float('123 456.123 456') == Float('123456.123456')
Integer('123 456') == Integer('123456')
Rational('123 456.123 456') == Rational('123456.123456')
assert Float(' .3e2') == Float('0.3e2')
# allow underscore
assert Float('1_23.4_56') == Float('123.456')
assert Float('1_23.4_5_6', 12) == Float('123.456', 12)
# ...but not in all cases (per Py 3.6)
raises(ValueError, lambda: Float('_1'))
raises(ValueError, lambda: Float('1_'))
raises(ValueError, lambda: Float('1_.'))
raises(ValueError, lambda: Float('1._'))
raises(ValueError, lambda: Float('1__2'))
raises(ValueError, lambda: Float('_inf'))
# allow auto precision detection
assert Float('.1', '') == Float(.1, 1)
assert Float('.125', '') == Float(.125, 3)
assert Float('.100', '') == Float(.1, 3)
assert Float('2.0', '') == Float('2', 2)
raises(ValueError, lambda: Float("12.3d-4", ""))
raises(ValueError, lambda: Float(12.3, ""))
raises(ValueError, lambda: Float('.'))
raises(ValueError, lambda: Float('-.'))
zero = Float('0.0')
assert Float('-0') == zero
assert Float('.0') == zero
assert Float('-.0') == zero
assert Float('-0.0') == zero
assert Float(0.0) == zero
assert Float(0) == zero
assert Float(0, '') == Float('0', '')
assert Float(1) == Float(1.0)
assert Float(S.Zero) == zero
assert Float(S.One) == Float(1.0)
assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
assert Float(decimal.Decimal('nan')) is S.NaN
assert Float(decimal.Decimal('Infinity')) is S.Infinity
assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity
assert '{:.3f}'.format(Float(4.236622)) == '4.237'
assert '{:.35f}'.format(Float(pi.n(40), 40)) == \
'3.14159265358979323846264338327950288'
# unicode
assert Float('0.73908513321516064100000000') == \
Float('0.73908513321516064100000000')
assert Float('0.73908513321516064100000000', 28) == \
Float('0.73908513321516064100000000', 28)
# binary precision
# Decimal value 0.1 cannot be expressed precisely as a base 2 fraction
a = Float(S.One/10, dps=15)
b = Float(S.One/10, dps=16)
p = Float(S.One/10, precision=53)
q = Float(S.One/10, precision=54)
assert a._mpf_ == p._mpf_
assert not a._mpf_ == q._mpf_
assert not b._mpf_ == q._mpf_
# Precision specifying errors
raises(ValueError, lambda: Float("1.23", dps=3, precision=10))
raises(ValueError, lambda: Float("1.23", dps="", precision=10))
raises(ValueError, lambda: Float("1.23", dps=3, precision=""))
raises(ValueError, lambda: Float("1.23", dps="", precision=""))
# from NumberSymbol
assert same_and_same_prec(Float(pi, 32), pi.evalf(32))
assert same_and_same_prec(Float(Catalan), Catalan.evalf())
# oo and nan
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Float(i) is a
def test_zero_not_false():
# https://github.com/sympy/sympy/issues/20796
assert (S(0.0) == S.false) is False
assert (S.false == S(0.0)) is False
assert (S(0) == S.false) is False
assert (S.false == S(0)) is False
@conserve_mpmath_dps
def test_float_mpf():
import mpmath
mpmath.mp.dps = 100
mp_pi = mpmath.pi()
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
mpmath.mp.dps = 15
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
def test_Float_RealElement():
repi = RealField(dps=100)(pi.evalf(100))
# We still have to pass the precision because Float doesn't know what
# RealElement is, but make sure it keeps full precision from the result.
assert Float(repi, 100) == pi.evalf(100)
def test_Float_default_to_highprec_from_str():
s = str(pi.evalf(128))
assert same_and_same_prec(Float(s), Float(s, ''))
def test_Float_eval():
a = Float(3.2)
assert (a**2).is_Float
def test_Float_issue_2107():
a = Float(0.1, 10)
b = Float("0.1", 10)
assert a - a == 0
assert a + (-a) == 0
assert S.Zero + a - a == 0
assert S.Zero + a + (-a) == 0
assert b - b == 0
assert b + (-b) == 0
assert S.Zero + b - b == 0
assert S.Zero + b + (-b) == 0
def test_issue_14289():
from sympy.polys.numberfields import to_number_field
a = 1 - sqrt(2)
b = to_number_field(a)
assert b.as_expr() == a
assert b.minpoly(a).expand() == 0
def test_Float_from_tuple():
a = Float((0, '1L', 0, 1))
b = Float((0, '1', 0, 1))
assert a == b
def test_Infinity():
assert oo != 1
assert 1*oo is oo
assert 1 != oo
assert oo != -oo
assert oo != Symbol("x")**3
assert oo + 1 is oo
assert 2 + oo is oo
assert 3*oo + 2 is oo
assert S.Half**oo == 0
assert S.Half**(-oo) is oo
assert -oo*3 is -oo
assert oo + oo is oo
assert -oo + oo*(-5) is -oo
assert 1/oo == 0
assert 1/(-oo) == 0
assert 8/oo == 0
assert oo % 2 is nan
assert 2 % oo is nan
assert oo/oo is nan
assert oo/-oo is nan
assert -oo/oo is nan
assert -oo/-oo is nan
assert oo - oo is nan
assert oo - -oo is oo
assert -oo - oo is -oo
assert -oo - -oo is nan
assert oo + -oo is nan
assert -oo + oo is nan
assert oo + oo is oo
assert -oo + oo is nan
assert oo + -oo is nan
assert -oo + -oo is -oo
assert oo*oo is oo
assert -oo*oo is -oo
assert oo*-oo is -oo
assert -oo*-oo is oo
assert oo/0 is oo
assert -oo/0 is -oo
assert 0/oo == 0
assert 0/-oo == 0
assert oo*0 is nan
assert -oo*0 is nan
assert 0*oo is nan
assert 0*-oo is nan
assert oo + 0 is oo
assert -oo + 0 is -oo
assert 0 + oo is oo
assert 0 + -oo is -oo
assert oo - 0 is oo
assert -oo - 0 is -oo
assert 0 - oo is -oo
assert 0 - -oo is oo
assert oo/2 is oo
assert -oo/2 is -oo
assert oo/-2 is -oo
assert -oo/-2 is oo
assert oo*2 is oo
assert -oo*2 is -oo
assert oo*-2 is -oo
assert 2/oo == 0
assert 2/-oo == 0
assert -2/oo == 0
assert -2/-oo == 0
assert 2*oo is oo
assert 2*-oo is -oo
assert -2*oo is -oo
assert -2*-oo is oo
assert 2 + oo is oo
assert 2 - oo is -oo
assert -2 + oo is oo
assert -2 - oo is -oo
assert 2 + -oo is -oo
assert 2 - -oo is oo
assert -2 + -oo is -oo
assert -2 - -oo is oo
assert S(2) + oo is oo
assert S(2) - oo is -oo
assert oo/I == -oo*I
assert -oo/I == oo*I
assert oo*float(1) == _inf and (oo*float(1)) is oo
assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo
assert oo/float(1) == _inf and (oo/float(1)) is oo
assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo
assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo
assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo
assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo
assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo
assert oo + float(1) == _inf and (oo + float(1)) is oo
assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo
assert oo - float(1) == _inf and (oo - float(1)) is oo
assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo
assert float(1)*oo == _inf and (float(1)*oo) is oo
assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo
assert float(1)/oo == 0
assert float(1)/-oo == 0
assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo
assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo
assert float(-1)/oo == 0
assert float(-1)/-oo == 0
assert float(1) + oo is oo
assert float(1) + -oo is -oo
assert float(1) - oo is -oo
assert float(1) - -oo is oo
assert oo == float(oo)
assert (oo != float(oo)) is False
assert type(float(oo)) is float
assert -oo == float(-oo)
assert (-oo != float(-oo)) is False
assert type(float(-oo)) is float
assert Float('nan') is nan
assert nan*1.0 is nan
assert -1.0*nan is nan
assert nan*oo is nan
assert nan*-oo is nan
assert nan/oo is nan
assert nan/-oo is nan
assert nan + oo is nan
assert nan + -oo is nan
assert nan - oo is nan
assert nan - -oo is nan
assert -oo * S.Zero is nan
assert oo*nan is nan
assert -oo*nan is nan
assert oo/nan is nan
assert -oo/nan is nan
assert oo + nan is nan
assert -oo + nan is nan
assert oo - nan is nan
assert -oo - nan is nan
assert S.Zero * oo is nan
assert oo.is_Rational is False
assert isinstance(oo, Rational) is False
assert S.One/oo == 0
assert -S.One/oo == 0
assert S.One/-oo == 0
assert -S.One/-oo == 0
assert S.One*oo is oo
assert -S.One*oo is -oo
assert S.One*-oo is -oo
assert -S.One*-oo is oo
assert S.One/nan is nan
assert S.One - -oo is oo
assert S.One + nan is nan
assert S.One - nan is nan
assert nan - S.One is nan
assert nan/S.One is nan
assert -oo - S.One is -oo
def test_Infinity_2():
x = Symbol('x')
assert oo*x != oo
assert oo*(pi - 1) is oo
assert oo*(1 - pi) is -oo
assert (-oo)*x != -oo
assert (-oo)*(pi - 1) is -oo
assert (-oo)*(1 - pi) is oo
assert (-1)**S.NaN is S.NaN
assert oo - _inf is S.NaN
assert oo + _ninf is S.NaN
assert oo*0 is S.NaN
assert oo/_inf is S.NaN
assert oo/_ninf is S.NaN
assert oo**S.NaN is S.NaN
assert -oo + _inf is S.NaN
assert -oo - _ninf is S.NaN
assert -oo*S.NaN is S.NaN
assert -oo*0 is S.NaN
assert -oo/_inf is S.NaN
assert -oo/_ninf is S.NaN
assert -oo/S.NaN is S.NaN
assert abs(-oo) is oo
assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN))
assert (-oo)**3 is -oo
assert (-oo)**2 is oo
assert abs(S.ComplexInfinity) is oo
def test_Mul_Infinity_Zero():
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
def test_Div_By_Zero():
assert 1/S.Zero is zoo
assert 1/Float(0) is zoo
assert 0/S.Zero is nan
assert 0/Float(0) is nan
assert S.Zero/0 is nan
assert Float(0)/0 is nan
assert -1/S.Zero is zoo
assert -1/Float(0) is zoo
@_both_exp_pow
def test_Infinity_inequations():
assert oo > pi
assert not (oo < pi)
assert exp(-3) < oo
assert _inf > pi
assert not (_inf < pi)
assert exp(-3) < _inf
raises(TypeError, lambda: oo < I)
raises(TypeError, lambda: oo <= I)
raises(TypeError, lambda: oo > I)
raises(TypeError, lambda: oo >= I)
raises(TypeError, lambda: -oo < I)
raises(TypeError, lambda: -oo <= I)
raises(TypeError, lambda: -oo > I)
raises(TypeError, lambda: -oo >= I)
raises(TypeError, lambda: I < oo)
raises(TypeError, lambda: I <= oo)
raises(TypeError, lambda: I > oo)
raises(TypeError, lambda: I >= oo)
raises(TypeError, lambda: I < -oo)
raises(TypeError, lambda: I <= -oo)
raises(TypeError, lambda: I > -oo)
raises(TypeError, lambda: I >= -oo)
assert oo > -oo and oo >= -oo
assert (oo < -oo) == False and (oo <= -oo) == False
assert -oo < oo and -oo <= oo
assert (-oo > oo) == False and (-oo >= oo) == False
assert (oo < oo) == False # issue 7775
assert (oo > oo) == False
assert (-oo > -oo) == False and (-oo < -oo) == False
assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo
assert (-oo < -_inf) == False
assert (oo > _inf) == False
assert -oo >= -_inf
assert oo <= _inf
x = Symbol('x')
b = Symbol('b', finite=True, real=True)
assert (x < oo) == Lt(x, oo) # issue 7775
assert b < oo and b > -oo and b <= oo and b >= -oo
assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False
assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b
assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x)
assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x)
assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x)
assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x)
def test_NaN():
assert nan is nan
assert nan != 1
assert 1*nan is nan
assert 1 != nan
assert -nan is nan
assert oo != Symbol("x")**3
assert 2 + nan is nan
assert 3*nan + 2 is nan
assert -nan*3 is nan
assert nan + nan is nan
assert -nan + nan*(-5) is nan
assert 8/nan is nan
raises(TypeError, lambda: nan > 0)
raises(TypeError, lambda: nan < 0)
raises(TypeError, lambda: nan >= 0)
raises(TypeError, lambda: nan <= 0)
raises(TypeError, lambda: 0 < nan)
raises(TypeError, lambda: 0 > nan)
raises(TypeError, lambda: 0 <= nan)
raises(TypeError, lambda: 0 >= nan)
assert nan**0 == 1 # as per IEEE 754
assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work
# test Pow._eval_power's handling of NaN
assert Pow(nan, 0, evaluate=False)**2 == 1
for n in (1, 1., S.One, S.NegativeOne, Float(1)):
assert n + nan is nan
assert n - nan is nan
assert nan + n is nan
assert nan - n is nan
assert n/nan is nan
assert nan/n is nan
def test_special_numbers():
assert isinstance(S.NaN, Number) is True
assert isinstance(S.Infinity, Number) is True
assert isinstance(S.NegativeInfinity, Number) is True
assert S.NaN.is_number is True
assert S.Infinity.is_number is True
assert S.NegativeInfinity.is_number is True
assert S.ComplexInfinity.is_number is True
assert isinstance(S.NaN, Rational) is False
assert isinstance(S.Infinity, Rational) is False
assert isinstance(S.NegativeInfinity, Rational) is False
assert S.NaN.is_rational is not True
assert S.Infinity.is_rational is not True
assert S.NegativeInfinity.is_rational is not True
def test_powers():
assert integer_nthroot(1, 2) == (1, True)
assert integer_nthroot(1, 5) == (1, True)
assert integer_nthroot(2, 1) == (2, True)
assert integer_nthroot(2, 2) == (1, False)
assert integer_nthroot(2, 5) == (1, False)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(123**25, 25) == (123, True)
assert integer_nthroot(123**25 + 1, 25) == (123, False)
assert integer_nthroot(123**25 - 1, 25) == (122, False)
assert integer_nthroot(1, 1) == (1, True)
assert integer_nthroot(0, 1) == (0, True)
assert integer_nthroot(0, 3) == (0, True)
assert integer_nthroot(10000, 1) == (10000, True)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(16, 2) == (4, True)
assert integer_nthroot(26, 2) == (5, False)
assert integer_nthroot(1234567**7, 7) == (1234567, True)
assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False)
assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False)
b = 25**1000
assert integer_nthroot(b, 1000) == (25, True)
assert integer_nthroot(b + 1, 1000) == (25, False)
assert integer_nthroot(b - 1, 1000) == (24, False)
c = 10**400
c2 = c**2
assert integer_nthroot(c2, 2) == (c, True)
assert integer_nthroot(c2 + 1, 2) == (c, False)
assert integer_nthroot(c2 - 1, 2) == (c - 1, False)
assert integer_nthroot(2, 10**10) == (1, False)
p, r = integer_nthroot(int(factorial(10000)), 100)
assert p % (10**10) == 5322420655
assert not r
# Test that this is fast
assert integer_nthroot(2, 10**10) == (1, False)
# output should be int if possible
assert type(integer_nthroot(2**61, 2)[0]) is int
def test_integer_nthroot_overflow():
assert integer_nthroot(10**(50*50), 50) == (10**50, True)
assert integer_nthroot(10**100000, 10000) == (10**10, True)
def test_integer_log():
raises(ValueError, lambda: integer_log(2, 1))
raises(ValueError, lambda: integer_log(0, 2))
raises(ValueError, lambda: integer_log(1.1, 2))
raises(ValueError, lambda: integer_log(1, 2.2))
assert integer_log(1, 2) == (0, True)
assert integer_log(1, 3) == (0, True)
assert integer_log(2, 3) == (0, False)
assert integer_log(3, 3) == (1, True)
assert integer_log(3*2, 3) == (1, False)
assert integer_log(3**2, 3) == (2, True)
assert integer_log(3*4, 3) == (2, False)
assert integer_log(3**3, 3) == (3, True)
assert integer_log(27, 5) == (2, False)
assert integer_log(2, 3) == (0, False)
assert integer_log(-4, -2) == (2, False)
assert integer_log(27, -3) == (3, False)
assert integer_log(-49, 7) == (0, False)
assert integer_log(-49, -7) == (2, False)
def test_isqrt():
from math import sqrt as _sqrt
limit = 4503599761588223
assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0]
assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0]
assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0]
# Regression tests for https://github.com/sympy/sympy/issues/17034
assert isqrt(4503599761588224) == 67108864
assert isqrt(9999999999999999) == 99999999
# Other corner cases, especially involving non-integers.
raises(ValueError, lambda: isqrt(-1))
raises(ValueError, lambda: isqrt(-10**1000))
raises(ValueError, lambda: isqrt(Rational(-1, 2)))
tiny = Rational(1, 10**1000)
raises(ValueError, lambda: isqrt(-tiny))
assert isqrt(1-tiny) == 0
assert isqrt(4503599761588224-tiny) == 67108864
assert isqrt(10**100 - tiny) == 10**50 - 1
# Check that using an inaccurate math.sqrt doesn't affect the results.
from sympy.core import power
old_sqrt = power._sqrt
power._sqrt = lambda x: 2.999999999
try:
assert isqrt(9) == 3
assert isqrt(10000) == 100
finally:
power._sqrt = old_sqrt
def test_powers_Integer():
"""Test Integer._eval_power"""
# check infinity
assert S.One ** S.Infinity is S.NaN
assert S.NegativeOne** S.Infinity is S.NaN
assert S(2) ** S.Infinity is S.Infinity
assert S(-2)** S.Infinity == S.Infinity + S.Infinity * S.ImaginaryUnit
assert S(0) ** S.Infinity is S.Zero
# check Nan
assert S.One ** S.NaN is S.NaN
assert S.NegativeOne ** S.NaN is S.NaN
# check for exact roots
assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5)
assert sqrt(S(4)) == 2
assert sqrt(S(-4)) == I * 2
assert S(16) ** Rational(1, 4) == 2
assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
assert S(9) ** Rational(3, 2) == 27
assert S(-9) ** Rational(3, 2) == -27*I
assert S(27) ** Rational(2, 3) == 9
assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3))
assert (-2) ** Rational(-2, 1) == Rational(1, 4)
# not exact roots
assert sqrt(-3) == I*sqrt(3)
assert (3) ** (Rational(3, 2)) == 3 * sqrt(3)
assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3)
assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3)
assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3)
assert (2) ** (Rational(3, 2)) == 2 * sqrt(2)
assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4
assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3)))
assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3)))
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
# join roots
assert sqrt(6) + sqrt(24) == 3*sqrt(6)
assert sqrt(2) * sqrt(3) == sqrt(6)
# separate symbols & constansts
x = Symbol("x")
assert sqrt(49 * x) == 7 * sqrt(x)
assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)
# check that it is fast for big numbers
assert (2**64 + 1) ** Rational(4, 3)
assert (2**64 + 1) ** Rational(17, 25)
# negative rational power and negative base
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
assert (-2) ** Rational(-10, 3) == \
(-1)**Rational(2, 3)*2**Rational(2, 3)/16
assert abs(Pow(-2, Rational(-10, 3)).n() -
Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16
# negative base and rational power with some simplification
assert (-8) ** Rational(2, 5) == \
2*(-1)**Rational(2, 5)*2**Rational(1, 5)
assert (-4) ** Rational(9, 5) == \
-8*(-1)**Rational(4, 5)*2**Rational(3, 5)
assert S(1234).factors() == {617: 1, 2: 1}
assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}
# test that eval_power factors numbers bigger than
# the current limit in factor_trial_division (2**15)
from sympy import nextprime
n = nextprime(2**15)
assert sqrt(n**2) == n
assert sqrt(n**3) == n*sqrt(n)
assert sqrt(4*n) == 2*sqrt(n)
# check that factors of base with powers sharing gcd with power are removed
assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)
# check that bases sharing a gcd are exptracted
assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
2**Rational(8, 15)*3**Rational(9, 20)
assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
4*2**Rational(7, 10)*3**Rational(8, 15)
assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
4*(-3)**Rational(8, 15)*2**Rational(7, 10)
assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
assert 2**Rational(2, 3)*6**Rational(8, 9) == \
2*2**Rational(5, 9)*3**Rational(8, 9)
assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
assert 3*Pow(3, 2, evaluate=False) == 3**3
assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3)
assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \
-(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
5**Rational(5, 6)
assert Integer(-2)**Symbol('', even=True) == \
Integer(2)**Symbol('', even=True)
assert (-1)**Float(.5) == 1.0*I
def test_powers_Rational():
"""Test Rational._eval_power"""
# check infinity
assert S.Half ** S.Infinity == 0
assert Rational(3, 2) ** S.Infinity is S.Infinity
assert Rational(-1, 2) ** S.Infinity == 0
assert Rational(-3, 2) ** S.Infinity == \
S.Infinity + S.Infinity * S.ImaginaryUnit
# check Nan
assert Rational(3, 4) ** S.NaN is S.NaN
assert Rational(-2, 3) ** S.NaN is S.NaN
# exact roots on numerator
assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3
assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9
assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3
assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9
assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2
assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4)
# exact root on denominator
assert sqrt(Rational(1, 4)) == S.Half
assert sqrt(Rational(1, -4)) == I * S.Half
assert sqrt(Rational(3, 4)) == sqrt(3) / 2
assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2
assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3
# not exact roots
assert sqrt(S.Half) == sqrt(2) / 2
assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7))
assert Rational(-3, 2)**Rational(-7, 3) == \
-4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27
assert Rational(-3, 2)**Rational(-2, 3) == \
-(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3
assert Rational(-3, 2)**Rational(-10, 3) == \
8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81
assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() -
Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16
# negative integer power and negative rational base
assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
a = Rational(1, 10)
assert a**Float(a, 2) == Float(a, 2)**Float(a, 2)
assert Rational(-2, 3)**Symbol('', even=True) == \
Rational(2, 3)**Symbol('', even=True)
def test_powers_Float():
assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3))
def test_abs1():
assert Rational(1, 6) != Rational(-1, 6)
assert abs(Rational(1, 6)) == abs(Rational(-1, 6))
def test_accept_int():
assert Float(4) == 4
def test_dont_accept_str():
assert Float("0.2") != "0.2"
assert not (Float("0.2") == "0.2")
def test_int():
a = Rational(5)
assert int(a) == 5
a = Rational(9, 10)
assert int(a) == int(-a) == 0
assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3)
assert int(pi) == 3
assert int(E) == 2
assert int(GoldenRatio) == 1
assert int(TribonacciConstant) == 2
# issue 10368
a = Rational(32442016954, 78058255275)
assert type(int(a)) is type(int(-a)) is int
def test_real_bug():
x = Symbol("x")
assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"]
assert str(2.1*x*x) != "(2.0*x)*x"
def test_bug_sqrt():
assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1
def test_pi_Pi():
"Test that pi (instance) is imported, but Pi (class) is not"
from sympy import pi # noqa
with raises(ImportError):
from sympy import Pi # noqa
def test_no_len():
# there should be no len for numbers
raises(TypeError, lambda: len(Rational(2)))
raises(TypeError, lambda: len(Rational(2, 3)))
raises(TypeError, lambda: len(Integer(2)))
def test_issue_3321():
assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half
assert 5 * sqrt(Rational(1, 5)) == sqrt(5)
def test_issue_3692():
assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2
assert ((-5)**Rational(1, 6)).expand(complex=True) == \
5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2
assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3)
def test_issue_3423():
x = Symbol("x")
assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half)
assert sqrt(x - 1) != I*sqrt(1 - x)
def test_issue_3449():
x = Symbol("x")
assert sqrt(x - 1).subs(x, 5) == 2
def test_issue_13890():
x = Symbol("x")
e = (-x/4 - S.One/12)**x - 1
f = simplify(e)
a = Rational(9, 5)
assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15
def test_Integer_factors():
def F(i):
return Integer(i).factors()
assert F(1) == {}
assert F(2) == {2: 1}
assert F(3) == {3: 1}
assert F(4) == {2: 2}
assert F(5) == {5: 1}
assert F(6) == {2: 1, 3: 1}
assert F(7) == {7: 1}
assert F(8) == {2: 3}
assert F(9) == {3: 2}
assert F(10) == {2: 1, 5: 1}
assert F(11) == {11: 1}
assert F(12) == {2: 2, 3: 1}
assert F(13) == {13: 1}
assert F(14) == {2: 1, 7: 1}
assert F(15) == {3: 1, 5: 1}
assert F(16) == {2: 4}
assert F(17) == {17: 1}
assert F(18) == {2: 1, 3: 2}
assert F(19) == {19: 1}
assert F(20) == {2: 2, 5: 1}
assert F(21) == {3: 1, 7: 1}
assert F(22) == {2: 1, 11: 1}
assert F(23) == {23: 1}
assert F(24) == {2: 3, 3: 1}
assert F(25) == {5: 2}
assert F(26) == {2: 1, 13: 1}
assert F(27) == {3: 3}
assert F(28) == {2: 2, 7: 1}
assert F(29) == {29: 1}
assert F(30) == {2: 1, 3: 1, 5: 1}
assert F(31) == {31: 1}
assert F(32) == {2: 5}
assert F(33) == {3: 1, 11: 1}
assert F(34) == {2: 1, 17: 1}
assert F(35) == {5: 1, 7: 1}
assert F(36) == {2: 2, 3: 2}
assert F(37) == {37: 1}
assert F(38) == {2: 1, 19: 1}
assert F(39) == {3: 1, 13: 1}
assert F(40) == {2: 3, 5: 1}
assert F(41) == {41: 1}
assert F(42) == {2: 1, 3: 1, 7: 1}
assert F(43) == {43: 1}
assert F(44) == {2: 2, 11: 1}
assert F(45) == {3: 2, 5: 1}
assert F(46) == {2: 1, 23: 1}
assert F(47) == {47: 1}
assert F(48) == {2: 4, 3: 1}
assert F(49) == {7: 2}
assert F(50) == {2: 1, 5: 2}
assert F(51) == {3: 1, 17: 1}
def test_Rational_factors():
def F(p, q, visual=None):
return Rational(p, q).factors(visual=visual)
assert F(2, 3) == {2: 1, 3: -1}
assert F(2, 9) == {2: 1, 3: -2}
assert F(2, 15) == {2: 1, 3: -1, 5: -1}
assert F(6, 10) == {3: 1, 5: -1}
def test_issue_4107():
assert pi*(E + 10) + pi*(-E - 10) != 0
assert pi*(E + 10**10) + pi*(-E - 10**10) != 0
assert pi*(E + 10**20) + pi*(-E - 10**20) != 0
assert pi*(E + 10**80) + pi*(-E - 10**80) != 0
assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0
assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0
assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0
assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0
def test_IntegerInteger():
a = Integer(4)
b = Integer(a)
assert a == b
def test_Rational_gcd_lcm_cofactors():
assert Integer(4).gcd(2) == Integer(2)
assert Integer(4).lcm(2) == Integer(4)
assert Integer(4).gcd(Integer(2)) == Integer(2)
assert Integer(4).lcm(Integer(2)) == Integer(4)
a, b = 720**99911, 480**12342
assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b)
assert Integer(4).gcd(3) == Integer(1)
assert Integer(4).lcm(3) == Integer(12)
assert Integer(4).gcd(Integer(3)) == Integer(1)
assert Integer(4).lcm(Integer(3)) == Integer(12)
assert Rational(4, 3).gcd(2) == Rational(2, 3)
assert Rational(4, 3).lcm(2) == Integer(4)
assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3)
assert Rational(4, 3).lcm(Integer(2)) == Integer(4)
assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9)
assert Integer(4).lcm(Rational(2, 9)) == Integer(4)
assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9)
assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3)
assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45)
assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4)
assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7))
assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1))
assert Integer(4).cofactors(Integer(2)) == \
(Integer(2), Integer(2), Integer(1))
assert Integer(4).gcd(Float(2.0)) == S.One
assert Integer(4).lcm(Float(2.0)) == Float(8.0)
assert Integer(4).cofactors(Float(2.0)) == (S.One, Integer(4), Float(2.0))
assert S.Half.gcd(Float(2.0)) == S.One
assert S.Half.lcm(Float(2.0)) == Float(1.0)
assert S.Half.cofactors(Float(2.0)) == \
(S.One, S.Half, Float(2.0))
def test_Float_gcd_lcm_cofactors():
assert Float(2.0).gcd(Integer(4)) == S.One
assert Float(2.0).lcm(Integer(4)) == Float(8.0)
assert Float(2.0).cofactors(Integer(4)) == (S.One, Float(2.0), Integer(4))
assert Float(2.0).gcd(S.Half) == S.One
assert Float(2.0).lcm(S.Half) == Float(1.0)
assert Float(2.0).cofactors(S.Half) == \
(S.One, Float(2.0), S.Half)
def test_issue_4611():
assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10
assert abs(E._evalf(50) - 2.71828182845905) < 1e-10
assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10
assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10
assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10
assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10
x = Symbol("x")
assert (pi + x).evalf() == pi.evalf() + x
assert (E + x).evalf() == E.evalf() + x
assert (Catalan + x).evalf() == Catalan.evalf() + x
assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x
assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x
assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x
@conserve_mpmath_dps
def test_conversion_to_mpmath():
assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1)
assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5)
assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23')
assert mpmath.mpmathify(I) == mpmath.mpc(1j)
assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j)
assert mpmath.mpmathify(2*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j)
mpmath.mp.dps = 100
assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j
assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j
def test_relational():
# real
x = S(.1)
assert (x != cos) is True
assert (x == cos) is False
# rational
x = Rational(1, 3)
assert (x != cos) is True
assert (x == cos) is False
# integer defers to rational so these tests are omitted
# number symbol
x = pi
assert (x != cos) is True
assert (x == cos) is False
def test_Integer_as_index():
assert 'hello'[Integer(2):] == 'llo'
def test_Rational_int():
assert int( Rational(7, 5)) == 1
assert int( S.Half) == 0
assert int(Rational(-1, 2)) == 0
assert int(-Rational(7, 5)) == -1
def test_zoo():
b = Symbol('b', finite=True)
nz = Symbol('nz', nonzero=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
im = Symbol('i', imaginary=True)
c = Symbol('c', complex=True)
pb = Symbol('pb', positive=True, finite=True)
nb = Symbol('nb', negative=True, finite=True)
imb = Symbol('ib', imaginary=True, finite=True)
for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3),
b, nz, p, n, im, pb, nb, imb, c]:
if i.is_finite and (i.is_real or i.is_imaginary):
assert i + zoo is zoo
assert i - zoo is zoo
assert zoo + i is zoo
assert zoo - i is zoo
elif i.is_finite is not False:
assert (i + zoo).is_Add
assert (i - zoo).is_Add
assert (zoo + i).is_Add
assert (zoo - i).is_Add
else:
assert (i + zoo) is S.NaN
assert (i - zoo) is S.NaN
assert (zoo + i) is S.NaN
assert (zoo - i) is S.NaN
if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary):
assert i*zoo is zoo
assert zoo*i is zoo
elif i.is_zero:
assert i*zoo is S.NaN
assert zoo*i is S.NaN
else:
assert (i*zoo).is_Mul
assert (zoo*i).is_Mul
if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary):
assert zoo/i is zoo
elif (1/i).is_zero:
assert zoo/i is S.NaN
elif i.is_zero:
assert zoo/i is zoo
else:
assert (zoo/i).is_Mul
assert (I*oo).is_Mul # allow directed infinity
assert zoo + zoo is S.NaN
assert zoo * zoo is zoo
assert zoo - zoo is S.NaN
assert zoo/zoo is S.NaN
assert zoo**zoo is S.NaN
assert zoo**0 is S.One
assert zoo**2 is zoo
assert 1/zoo is S.Zero
assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None)
def test_issue_4122():
x = Symbol('x', nonpositive=True)
assert oo + x is oo
x = Symbol('x', extended_nonpositive=True)
assert (oo + x).is_Add
x = Symbol('x', finite=True)
assert (oo + x).is_Add # x could be imaginary
x = Symbol('x', nonnegative=True)
assert oo + x is oo
x = Symbol('x', extended_nonnegative=True)
assert oo + x is oo
x = Symbol('x', finite=True, real=True)
assert oo + x is oo
# similarly for negative infinity
x = Symbol('x', nonnegative=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonnegative=True)
assert (-oo + x).is_Add
x = Symbol('x', finite=True)
assert (-oo + x).is_Add
x = Symbol('x', nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', finite=True, real=True)
assert -oo + x is -oo
def test_GoldenRatio_expand():
assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2
def test_TribonacciConstant_expand():
assert TribonacciConstant.expand(func=True) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_as_content_primitive():
assert S.Zero.as_content_primitive() == (1, 0)
assert S.Half.as_content_primitive() == (S.Half, 1)
assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1)
assert S(3).as_content_primitive() == (3, 1)
assert S(3.1).as_content_primitive() == (1, 3.1)
def test_hashing_sympy_integers():
# Test for issue 5072
assert {Integer(3)} == {int(3)}
assert hash(Integer(4)) == hash(int(4))
def test_rounding_issue_4172():
assert int((E**100).round()) == \
26881171418161354484126255515800135873611119
assert int((pi**100).round()) == \
51878483143196131920862615246303013562686760680406
assert int((Rational(1)/EulerGamma**100).round()) == \
734833795660954410469466
@XFAIL
def test_mpmath_issues():
from mpmath.libmp.libmpf import _normalize
import mpmath.libmp as mlib
rnd = mlib.round_nearest
mpf = (0, int(0), -123, -1, 53, rnd) # nan
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (0, int(0), -456, -2, 53, rnd) # +inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (1, int(0), -789, -3, 53, rnd) # -inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
from mpmath.libmp.libmpf import fnan
assert mlib.mpf_eq(fnan, fnan)
def test_Catalan_EulerGamma_prec():
n = GoldenRatio
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(212079), -17, 18)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
n = EulerGamma
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(302627), -19, 19)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
def test_Catalan_rewrite():
k = Dummy('k', integer=True, nonnegative=True)
assert Catalan.rewrite(Sum).dummy_eq(
Sum((-1)**k/(2*k + 1)**2, (k, 0, oo)))
assert Catalan.rewrite() == Catalan
def test_bool_eq():
assert 0 == False
assert S(0) == False
assert S(0) != S.false
assert 1 == True
assert S.One == True
assert S.One != S.true
def test_Float_eq():
# all .5 values are the same
assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1)
# but floats that aren't exact in base-2 still
# don't compare the same because they have different
# underlying mpf values
assert Float(.12, 3) != Float(.12, 4)
assert Float(.12, 3) != .12
assert 0.12 != Float(.12, 3)
assert Float('.12', 22) != .12
# issue 11707
# but Float/Rational -- except for 0 --
# are exact so Rational(x) = Float(y) only if
# Rational(x) == Rational(Float(y))
assert Float('1.1') != Rational(11, 10)
assert Rational(11, 10) != Float('1.1')
# coverage
assert not Float(3) == 2
assert not Float(2**2) == S.Half
assert Float(2**2) == 4
assert not Float(2**-2) == 1
assert Float(2**-1) == S.Half
assert not Float(2*3) == 3
assert not Float(2*3) == S.Half
assert Float(2*3) == 6
assert not Float(2*3) == 8
assert Float(.75) == Rational(3, 4)
assert Float(5/18) == 5/18
# 4473
assert Float(2.) != 3
assert Float((0,1,-3)) == S.One/8
assert Float((0,1,-3)) != S.One/9
# 16196
assert 2 == Float(2) # as per Python
# but in a computation...
assert t**2 != t**2.0
def test_int_NumberSymbols():
assert [int(i) for i in [pi, EulerGamma, E, GoldenRatio, Catalan]] == \
[3, 0, 2, 1, 0]
def test_issue_6640():
from mpmath.libmp.libmpf import finf, fninf
# fnan is not included because Float no longer returns fnan,
# but otherwise, the same sort of test could apply
assert Float(finf).is_zero is False
assert Float(fninf).is_zero is False
assert bool(Float(0)) is False
def test_issue_6349():
assert Float('23.e3', '')._prec == 10
assert Float('23e3', '')._prec == 20
assert Float('23000', '')._prec == 20
assert Float('-23000', '')._prec == 20
def test_mpf_norm():
assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_
assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_
def test_latex():
assert latex(pi) == r"\pi"
assert latex(E) == r"e"
assert latex(GoldenRatio) == r"\phi"
assert latex(TribonacciConstant) == r"\text{TribonacciConstant}"
assert latex(EulerGamma) == r"\gamma"
assert latex(oo) == r"\infty"
assert latex(-oo) == r"-\infty"
assert latex(zoo) == r"\tilde{\infty}"
assert latex(nan) == r"\text{NaN}"
assert latex(I) == r"i"
def test_issue_7742():
assert -oo % 1 is nan
def test_simplify_AlgebraicNumber():
A = AlgebraicNumber
e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3)
assert simplify(A(e)) == A(12) # wester test_C20
e = (41 + 29*sqrt(2))**(S.One/5)
assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21
e = (3 + 4*I)**Rational(3, 2)
assert simplify(A(e)) == A(2 + 11*I) # issue 4401
def test_Float_idempotence():
x = Float('1.23', '')
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
x = Float(10**20)
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
def test_comp1():
# sqrt(2) = 1.414213 5623730950...
a = sqrt(2).n(7)
assert comp(a, 1.4142129) is False
assert comp(a, 1.4142130)
# ...
assert comp(a, 1.4142141)
assert comp(a, 1.4142142) is False
assert comp(sqrt(2).n(2), '1.4')
assert comp(sqrt(2).n(2), Float(1.4, 2), '')
assert comp(sqrt(2).n(2), 1.4, '')
assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1)
assert [(i, j)
for i in range(130, 150)
for j in range(170, 180)
if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [
(141, 173), (142, 173)]
raises(ValueError, lambda: comp(t, '1'))
raises(ValueError, lambda: comp(t, 1))
assert comp(0, 0.0)
assert comp(.5, S.Half)
assert comp(2 + sqrt(2), 2.0 + sqrt(2))
assert not comp(0, 1)
assert not comp(2, sqrt(2))
assert not comp(2 + I, 2.0 + sqrt(2))
assert not comp(2.0 + sqrt(2), 2 + I)
assert not comp(2.0 + sqrt(2), sqrt(3))
assert comp(1/pi.n(4), 0.3183, 1e-5)
assert not comp(1/pi.n(4), 0.3183, 8e-6)
def test_issue_9491():
assert oo**zoo is nan
def test_issue_10063():
assert 2**Float(3) == Float(8)
def test_issue_10020():
assert oo**I is S.NaN
assert oo**(1 + I) is S.ComplexInfinity
assert oo**(-1 + I) is S.Zero
assert (-oo)**I is S.NaN
assert (-oo)**(-1 + I) is S.Zero
assert oo**t == Pow(oo, t, evaluate=False)
assert (-oo)**t == Pow(-oo, t, evaluate=False)
def test_invert_numbers():
assert S(2).invert(5) == 3
assert S(2).invert(Rational(5, 2)) == S.Half
assert S(2).invert(5.) == 0.5
assert S(2).invert(S(5)) == 3
assert S(2.).invert(5) == 0.5
assert S(sqrt(2)).invert(5) == 1/sqrt(2)
assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2)
def test_mod_inverse():
assert mod_inverse(3, 11) == 4
assert mod_inverse(5, 11) == 9
assert mod_inverse(21124921, 521512) == 7713
assert mod_inverse(124215421, 5125) == 2981
assert mod_inverse(214, 12515) == 1579
assert mod_inverse(5823991, 3299) == 1442
assert mod_inverse(123, 44) == 39
assert mod_inverse(2, 5) == 3
assert mod_inverse(-2, 5) == 2
assert mod_inverse(2, -5) == -2
assert mod_inverse(-2, -5) == -3
assert mod_inverse(-3, -7) == -5
x = Symbol('x')
assert S(2).invert(x) == S.Half
raises(TypeError, lambda: mod_inverse(2, x))
raises(ValueError, lambda: mod_inverse(2, S.Half))
raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2))
def test_golden_ratio_rewrite_as_sqrt():
assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half
def test_tribonacci_constant_rewrite_as_sqrt():
assert TribonacciConstant.rewrite(sqrt) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_comparisons_with_unknown_type():
class Foo:
"""
Class that is unaware of Basic, and relies on both classes returning
the NotImplemented singleton for equivalence to evaluate to False.
"""
ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3)
foo = Foo()
for n in ni, nf, nr, oo, -oo, zoo, nan:
assert n != foo
assert foo != n
assert not n == foo
assert not foo == n
raises(TypeError, lambda: n < foo)
raises(TypeError, lambda: foo > n)
raises(TypeError, lambda: n > foo)
raises(TypeError, lambda: foo < n)
raises(TypeError, lambda: n <= foo)
raises(TypeError, lambda: foo >= n)
raises(TypeError, lambda: n >= foo)
raises(TypeError, lambda: foo <= n)
class Bar:
"""
Class that considers itself equal to any instance of Number except
infinities and nans, and relies on sympy types returning the
NotImplemented singleton for symmetric equality relations.
"""
def __eq__(self, other):
if other in (oo, -oo, zoo, nan):
return False
if isinstance(other, Number):
return True
return NotImplemented
def __ne__(self, other):
return not self == other
bar = Bar()
for n in ni, nf, nr:
assert n == bar
assert bar == n
assert not n != bar
assert not bar != n
for n in oo, -oo, zoo, nan:
assert n != bar
assert bar != n
assert not n == bar
assert not bar == n
for n in ni, nf, nr, oo, -oo, zoo, nan:
raises(TypeError, lambda: n < bar)
raises(TypeError, lambda: bar > n)
raises(TypeError, lambda: n > bar)
raises(TypeError, lambda: bar < n)
raises(TypeError, lambda: n <= bar)
raises(TypeError, lambda: bar >= n)
raises(TypeError, lambda: n >= bar)
raises(TypeError, lambda: bar <= n)
def test_NumberSymbol_comparison():
from sympy.core.tests.test_relational import rel_check
rpi = Rational('905502432259640373/288230376151711744')
fpi = Float(float(pi))
assert rel_check(rpi, fpi)
def test_Integer_precision():
# Make sure Integer inputs for keyword args work
assert Float('1.0', dps=Integer(15))._prec == 53
assert Float('1.0', precision=Integer(15))._prec == 15
assert type(Float('1.0', precision=Integer(15))._prec) == int
assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15)
def test_numpy_to_float():
from sympy.testing.pytest import skip
from sympy.external import import_module
np = import_module('numpy')
if not np:
skip('numpy not installed. Abort numpy tests.')
def check_prec_and_relerr(npval, ratval):
prec = np.finfo(npval).nmant + 1
x = Float(npval)
assert x._prec == prec
y = Float(ratval, precision=prec)
assert abs((x - y)/y) < 2**(-(prec + 1))
check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3))
# extended precision, on some arch/compilers:
x = np.longdouble(2)/3
check_prec_and_relerr(x, Rational(2, 3))
y = Float(x, precision=10)
assert same_and_same_prec(y, Float(Rational(2, 3), precision=10))
raises(TypeError, lambda: Float(np.complex64(1+2j)))
raises(TypeError, lambda: Float(np.complex128(1+2j)))
def test_Integer_ceiling_floor():
a = Integer(4)
assert a.floor() == a
assert a.ceiling() == a
def test_ComplexInfinity():
assert zoo.floor() is zoo
assert zoo.ceiling() is zoo
assert zoo**zoo is S.NaN
def test_Infinity_floor_ceiling_power():
assert oo.floor() is oo
assert oo.ceiling() is oo
assert oo**S.NaN is S.NaN
assert oo**zoo is S.NaN
def test_One_power():
assert S.One**12 is S.One
assert S.NegativeOne**S.NaN is S.NaN
def test_NegativeInfinity():
assert (-oo).floor() is -oo
assert (-oo).ceiling() is -oo
assert (-oo)**11 is -oo
assert (-oo)**12 is oo
def test_issue_6133():
raises(TypeError, lambda: (-oo < None))
raises(TypeError, lambda: (S(-2) < None))
raises(TypeError, lambda: (oo < None))
raises(TypeError, lambda: (oo > None))
raises(TypeError, lambda: (S(2) < None))
def test_abc():
x = numbers.Float(5)
assert(isinstance(x, nums.Number))
assert(isinstance(x, numbers.Number))
assert(isinstance(x, nums.Real))
y = numbers.Rational(1, 3)
assert(isinstance(y, nums.Number))
assert(y.numerator() == 1)
assert(y.denominator() == 3)
assert(isinstance(y, nums.Rational))
z = numbers.Integer(3)
assert(isinstance(z, nums.Number))
def test_floordiv():
assert S(2)//S.Half == 4
|
607f845e6c88cce0cea87f56c3187aba11aaca22961a1c3980978e186efb2c28 | from sympy import (Abs, Add, atan, ceiling, cos, E, Eq, exp, factor,
factorial, fibonacci, floor, Function, GoldenRatio, I, Integral,
integrate, log, Mul, N, oo, pi, Pow, product, Product, tan,
Rational, S, Sum, simplify, sin, sqrt, sstr, sympify, Symbol, Max, nfloat, cosh, acosh, acos)
from sympy.core.numbers import comp
from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
scaled_zero, get_integer_part, as_mpmath, evalf)
from mpmath import inf, ninf
from mpmath.libmp.libmpf import from_float
from sympy.core.expr import unchanged
from sympy.testing.pytest import raises, XFAIL
from sympy.abc import n, x, y
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_evalf_helpers():
assert complex_accuracy((from_float(2.0), None, 35, None)) == 35
assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 35, 100)) == 43
assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 100, 35)) == 35
def test_evalf_basic():
assert NS('pi', 15) == '3.14159265358979'
assert NS('2/3', 10) == '0.6666666667'
assert NS('355/113-pi', 6) == '2.66764e-7'
assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979'
def test_cancellation():
assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15,
maxn=1200) == '1.00000000000000e-1000'
def test_evalf_powers():
assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435'
assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882'
'9089887365167832438044244613405349992494711208'
'95526746555473864642912223')
assert NS('2**(1/10**50)', 15) == '1.00000000000000'
assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51'
# Evaluation of Rump's ill-conditioned polynomial
def test_evalf_rump():
a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y)
assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821'
def test_evalf_complex():
assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I'
assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I'
assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I'
assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I'
assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I'
@XFAIL
def test_evalf_complex_bug():
assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I',
'0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I')
def test_evalf_complex_powers():
assert NS('(E+pi*I)**100000000000000000') == \
'-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I'
# XXX: rewrite if a+a*I simplification introduced in sympy
#assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I')
assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I'
assert NS(
'(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I'
assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I'
assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010'
assert NS(
'(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I'
assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I'
assert NS(
'(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18'
@XFAIL
def test_evalf_complex_powers_bug():
assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I'
def test_evalf_exponentiation():
assert NS(sqrt(-pi)) == '1.77245385090552*I'
assert NS(Pow(pi*I, Rational(
1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I'
assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I'
assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I'
assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I'
assert NS(exp(pi)) == '23.1406926327793'
assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I'
assert NS(pi**pi) == '36.4621596072079'
assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I'
assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I'
# An example from Smith, "Multiple Precision Complex Arithmetic and Functions"
def test_evalf_complex_cancellation():
A = Rational('63287/100000')
B = Rational('52498/100000')
C = Rational('69301/100000')
D = Rational('83542/100000')
F = Rational('2231321613/2500000000')
# XXX: the number of returned mantissa digits in the real part could
# change with the implementation. What matters is that the returned digits are
# correct; those that are showing now are correct.
# >>> ((A+B*I)*(C+D*I)).expand()
# 64471/10000000000 + 2231321613*I/2500000000
# >>> 2231321613*4
# 8925286452L
assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I'
assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I'
assert NS((A + B*I)*(
C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I')
def test_evalf_logs():
assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I'
assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I'
assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000'
assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185'
def test_evalf_trig():
assert NS('sin(1)', 15) == '0.841470984807897'
assert NS('cos(1)', 15) == '0.540302305868140'
assert NS('sin(10**-6)', 15) == '9.99999999999833e-7'
assert NS('cos(10**-6)', 15) == '0.999999999999500'
assert NS('sin(E*10**100)', 15) == '0.409160531722613'
# Some input near roots
assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12'
assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \
'6.99999999428333e-5'
assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \
'6.99999999428333e-5'
# Check detection of various false identities
def test_evalf_near_integers():
# Binet's formula
f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5))
assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046'
# Some near-integer identities from
# http://mathworld.wolfram.com/AlmostInteger.html
assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000'
assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857'
assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17'
assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11'
def test_evalf_ramanujan():
assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13'
# A related identity
A = 262537412640768744*exp(-pi*sqrt(163))
B = 196884*exp(-2*pi*sqrt(163))
C = 103378831900730205293632*exp(-3*pi*sqrt(163))
assert NS(1 - A - B + C, 10) == '1.613679005e-59'
# Input that for various reasons have failed at some point
def test_evalf_bugs():
assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10)
assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10)
assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50'
assert NS('log(10**100,10)', 10) == '100.0000000'
assert NS('log(2)', 10) == '0.6931471806'
assert NS(
'(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667'
assert NS(sin(1) + Rational(
1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I'
assert x.evalf() == x
assert NS((1 + I)**2*I, 6) == '-2.00000'
d = {n: (
-1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)}
assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I'
assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619'
assert NS((1 + I)**2*I, 15) == '-2.00000000000000'
# issue 4758 (1/2):
assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71'
# issue 4758 (2/2): With the bug present, this still only fails if the
# terms are in the order given here. This is not generally the case,
# because the order depends on the hashes of the terms.
assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n,
subs={n: .01}) == '19.8100000000000'
assert NS(((x - 1)*(1 - x)**1000).n()
) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)'
assert NS((-x).n()) == '-x'
assert NS((-2*x).n()) == '-2.00000000000000*x'
assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n()
# issue 6660. Also NaN != mpmath.nan
# In this order:
# 0*nan, 0/nan, 0*inf, 0/inf
# 0+nan, 0-nan, 0+inf, 0-inf
# >>> n = Some Number
# n*nan, n/nan, n*inf, n/inf
# n+nan, n-nan, n+inf, n-inf
assert (0*E**(oo)).n() is S.NaN
assert (0/E**(oo)).n() is S.Zero
assert (0+E**(oo)).n() is S.Infinity
assert (0-E**(oo)).n() is S.NegativeInfinity
assert (5*E**(oo)).n() is S.Infinity
assert (5/E**(oo)).n() is S.Zero
assert (5+E**(oo)).n() is S.Infinity
assert (5-E**(oo)).n() is S.NegativeInfinity
#issue 7416
assert as_mpmath(0.0, 10, {'chop': True}) == 0
#issue 5412
assert ((oo*I).n() == S.Infinity*I)
assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I)
#issue 11518
assert NS(2*x**2.5, 5) == '2.0000*x**2.5000'
#issue 13076
assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)'
def test_evalf_integer_parts():
a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
b = floor(log(8)/log(2), evaluate=False)
assert a.evalf() == 3
assert b.evalf() == 3
# equals, as a fallback, can still fail but it might succeed as here
assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10
assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \
int(11188719610782480504630258070757734324011354208865721592720336800)
assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \
int(11188719610782480504630258070757734324011354208865721592720336801)
assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half)
.evalf(1000)) == fibonacci(999)
assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half)
.evalf(1000)) == fibonacci(1000)
assert ceiling(x).evalf(subs={x: 3}) == 3
assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I
assert ceiling(x).evalf(subs={x: 3.}) == 3
assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I
assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9
assert float((floor(0.5, evaluate=False)+20).evalf()) == 20
# issue 19991
n = 1169809367327212570704813632106852886389036911
r = 744723773141314414542111064094745678855643068
assert floor(n / (pi / 2)) == r
assert floor(80782 * sqrt(2)) == 114242
# issue 20076
assert 260515 - floor(260515/pi + 1/2) * pi == atan(tan(260515))
def test_evalf_trig_zero_detection():
a = sin(160*pi, evaluate=False)
t = a.evalf(maxn=100)
assert abs(t) < 1e-100
assert t._prec < 2
assert a.evalf(chop=True) == 0
raises(PrecisionExhausted, lambda: a.evalf(strict=True))
def test_evalf_sum():
assert Sum(n,(n,1,2)).evalf() == 3.
assert Sum(n,(n,1,2)).doit().evalf() == 3.
# the next test should return instantly
assert Sum(1/n,(n,1,2)).evalf() == 1.5
# issue 8219
assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf()
# issue 8254
assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf()
# issue 8411
s = Sum(1/x**2, (x, 100, oo))
assert s.n() == s.doit().n()
def test_evalf_divergent_series():
raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf())
raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf())
def test_evalf_product():
assert Product(n, (n, 1, 10)).evalf() == 3628800.
assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662)
assert Product(n, (n, -1, 3)).evalf() == 0
def test_evalf_py_methods():
assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(
complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10
raises(TypeError, lambda: float(pi + x))
def test_evalf_power_subs_bugs():
assert (x**2).evalf(subs={x: 0}) == 0
assert sqrt(x).evalf(subs={x: 0}) == 0
assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0
assert (x**x).evalf(subs={x: 0}) == 1
assert (3**x).evalf(subs={x: 0}) == 1
assert exp(x).evalf(subs={x: 0}) == 1
assert ((2 + I)**x).evalf(subs={x: 0}) == 1
assert (0**x).evalf(subs={x: 0}) == 1
def test_evalf_arguments():
raises(TypeError, lambda: pi.evalf(method="garbage"))
def test_implemented_function_evalf():
from sympy.utilities.lambdify import implemented_function
f = Function('f')
f = implemented_function(f, lambda x: x + 1)
assert str(f(x)) == "f(x)"
assert str(f(2)) == "f(2)"
assert f(2).evalf() == 3
assert f(x).evalf() == f(x)
f = implemented_function(Function('sin'), lambda x: x + 1)
assert f(2).evalf() != sin(2)
del f._imp_ # XXX: due to caching _imp_ would influence all other tests
def test_evaluate_false():
for no in [0, False]:
assert Add(3, 2, evaluate=no).is_Add
assert Mul(3, 2, evaluate=no).is_Mul
assert Pow(3, 2, evaluate=no).is_Pow
assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
def test_evalf_relational():
assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y)
# if this first assertion fails it should be replaced with
# one that doesn't
assert unchanged(Eq, (3 - I)**2/2 + I, 0)
assert Eq((3 - I)**2/2 + I, 0).n() is S.false
assert nfloat(Eq((3 - I)**2 + I, 0)) == S.false
def test_issue_5486():
assert not cos(sqrt(0.5 + I)).n().is_Function
def test_issue_5486_bug():
from sympy import I, Expr
assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15
def test_bugs():
from sympy import polar_lift, re
assert abs(re((1 + I)**2)) < 1e-15
# anything that evalf's to 0 will do in place of polar_lift
assert abs(polar_lift(0)).n() == 0
def test_subs():
assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \
'-4.92535585957223e-10'
assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \
'1.00000000000000'
raises(TypeError, lambda: x.evalf(subs=(x, 1)))
def test_issue_4956_5204():
# issue 4956
v = S('''(-27*12**(1/3)*sqrt(31)*I +
27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) +
(29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I +
87*2**(1/3)*3**(1/6)*I)**2)''')
assert NS(v, 1) == '0.e-118 - 0.e-118*I'
# issue 5204
v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) +
108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 +
54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 +
54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 +
54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 +
4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) +
76788*I*83**(1/2))**2)''')
assert NS(v, 5) == '0.077284 + 1.1104*I'
assert NS(v, 1) == '0.08 + 1.*I'
def test_old_docstring():
a = (E + pi*I)*(E - pi*I)
assert NS(a) == '17.2586605000200'
assert a.n() == 17.25866050002001
def test_issue_4806():
assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == 0.5
assert atan(0, evaluate=False).n() == 0
def test_evalf_mul():
# sympy should not try to expand this; it should be handled term-wise
# in evalf through mpmath
assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I'
def test_scaled_zero():
a, b = (([0], 1, 100, 1), -1)
assert scaled_zero(100) == (a, b)
assert scaled_zero(a) == (0, 1, 100, 1)
a, b = (([1], 1, 100, 1), -1)
assert scaled_zero(100, -1) == (a, b)
assert scaled_zero(a) == (1, 1, 100, 1)
raises(ValueError, lambda: scaled_zero(scaled_zero(100)))
raises(ValueError, lambda: scaled_zero(100, 2))
raises(ValueError, lambda: scaled_zero(100, 0))
raises(ValueError, lambda: scaled_zero((1, 5, 1, 3)))
def test_chop_value():
for i in range(-27, 28):
assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
def test_infinities():
assert oo.evalf(chop=True) == inf
assert (-oo).evalf(chop=True) == ninf
def test_to_mpmath():
assert sqrt(3)._to_mpmath(20)._mpf_ == (0, int(908093), -19, 20)
assert S(3.2)._to_mpmath(20)._mpf_ == (0, int(838861), -18, 20)
def test_issue_6632_evalf():
add = (-100000*sqrt(2500000001) + 5000000001)
assert add.n() == 9.999999998e-11
assert (add*add).n() == 9.999999996e-21
def test_issue_4945():
from sympy.abc import H
from sympy import zoo
assert (H/0).evalf(subs={H:1}) == zoo*H
def test_evalf_integral():
# test that workprec has to increase in order to get a result other than 0
eps = Rational(1, 1000000)
assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = N(s)
assert Abs(sin(p)) < 1e-15
p = N(s, 64)
assert Abs(sin(p)) < 1e-64
def test_issue_8853():
p = Symbol('x', even=True, positive=True)
assert floor(-p - S.Half).is_even == False
assert floor(-p + S.Half).is_even == True
assert ceiling(p - S.Half).is_even == True
assert ceiling(p + S.Half).is_even == False
assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0)
assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0)
def test_issue_17681():
class identity_func(Function):
def _eval_evalf(self, *args, **kwargs):
return self.args[0].evalf(*args, **kwargs)
assert floor(identity_func(S(0))) == 0
assert get_integer_part(S(0), 1, {}, True) == (0, 0)
def test_issue_9326():
from sympy import Dummy
d1 = Dummy('d')
d2 = Dummy('d')
e = d1 + d2
assert e.evalf(subs = {d1: 1, d2: 2}) == 3
def test_issue_10323():
assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1
def test_AssocOp_Function():
# the first arg of Min is not comparable in the imaginary part
raises(ValueError, lambda: S('''
Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 -
sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 +
I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 -
sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))'''))
# if that is changed so a non-comparable number remains as
# an arg, then the Min/Max instantiation needs to be changed
# to watch out for non-comparable args when making simplifications
# and the following test should be added instead (with e being
# the sympified expression above):
# raises(ValueError, lambda: e._eval_evalf(2))
def test_issue_10395():
eq = x*Max(0, y)
assert nfloat(eq) == eq
eq = x*Max(y, -1.1)
assert nfloat(eq) == eq
assert Max(y, 4).n() == Max(4.0, y)
def test_issue_13098():
assert floor(log(S('9.'+'9'*20), 10)) == 0
assert ceiling(log(S('9.'+'9'*20), 10)) == 1
assert floor(log(20 - S('9.'+'9'*20), 10)) == 1
assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2
def test_issue_14601():
e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2)
subst = {x:0.0, y:0.0}
e2 = e.evalf(subs=subst)
assert float(e2) == 0.0
assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0
def test_issue_11151():
z = S.Zero
e = Sum(z, (x, 1, 2))
assert e != z # it shouldn't evaluate
# when it does evaluate, this is what it should give
assert evalf(e, 15, {}) == \
evalf(z, 15, {}) == (None, None, 15, None)
# so this shouldn't fail
assert (e/2).n() == 0
# this was where the issue appeared
expr0 = Sum(x**2 + x, (x, 1, 2))
expr1 = Sum(0, (x, 1, 2))
expr2 = expr1/expr0
assert simplify(factor(expr2) - expr2) == 0
def test_issue_13425():
assert N('2**.5', 30) == N('sqrt(2)', 30)
assert N('x - x', 30) == 0
assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22
def test_issue_17421():
assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I
def test_issue_20291():
from sympy import FiniteSet, Complement, Intersection, Reals, EmptySet
a = Symbol('a')
b = Symbol('b')
A = FiniteSet(a, b)
assert A.evalf(subs={a: 1, b: 2}) == FiniteSet(1.0, 2.0)
B = FiniteSet(a-b, 1)
assert B.evalf(subs={a: 1, b: 2}) == FiniteSet(-1.0, 1.0)
sol = Complement(Intersection(FiniteSet(-b/2 - sqrt(b**2-4*pi)/2), Reals), FiniteSet(0))
assert sol.evalf(subs={b: 1}) == EmptySet
|
5c386eb13ec41daeff7ac00c29ba178c16bd42b5c38410d164b4207cd185629b | from sympy import (abc, Add, cos, collect, Derivative, diff, exp, Float, Function,
I, Integer, log, Mul, oo, Poly, Rational, S, sin, sqrt, Symbol, symbols,
Wild, pi, meijerg, Sum
)
from sympy.testing.pytest import XFAIL
def test_symbol():
x = Symbol('x')
a, b, c, p, q = map(Wild, 'abcpq')
e = x
assert e.match(x) == {}
assert e.matches(x) == {}
assert e.match(a) == {a: x}
e = Rational(5)
assert e.match(c) == {c: 5}
assert e.match(e) == {}
assert e.match(e + 1) is None
def test_add():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q, r = map(Wild, 'pqr')
e = a + b
assert e.match(p + b) == {p: a}
assert e.match(p + a) == {p: b}
e = 1 + b
assert e.match(p + b) == {p: 1}
e = a + b + c
assert e.match(a + p + c) == {p: b}
assert e.match(b + p + c) == {p: a}
e = a + b + c + x
assert e.match(a + p + x + c) == {p: b}
assert e.match(b + p + c + x) == {p: a}
assert e.match(b) is None
assert e.match(b + p) == {p: a + c + x}
assert e.match(a + p + c) == {p: b + x}
assert e.match(b + p + c) == {p: a + x}
e = 4*x + 5
assert e.match(4*x + p) == {p: 5}
assert e.match(3*x + p) == {p: x + 5}
assert e.match(p*x + 5) == {p: 4}
def test_power():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q, r = map(Wild, 'pqr')
e = (x + y)**a
assert e.match(p**q) == {p: x + y, q: a}
assert e.match(p**p) is None
e = (x + y)**(x + y)
assert e.match(p**p) == {p: x + y}
assert e.match(p**q) == {p: x + y, q: x + y}
e = (2*x)**2
assert e.match(p*q**r) == {p: 4, q: x, r: 2}
e = Integer(1)
assert e.match(x**p) == {p: 0}
def test_match_exclude():
x = Symbol('x')
y = Symbol('y')
p = Wild("p")
q = Wild("q")
r = Wild("r")
e = Rational(6)
assert e.match(2*p) == {p: 3}
e = 3/(4*x + 5)
assert e.match(3/(p*x + q)) == {p: 4, q: 5}
e = 3/(4*x + 5)
assert e.match(p/(q*x + r)) == {p: 3, q: 4, r: 5}
e = 2/(x + 1)
assert e.match(p/(q*x + r)) == {p: 2, q: 1, r: 1}
e = 1/(x + 1)
assert e.match(p/(q*x + r)) == {p: 1, q: 1, r: 1}
e = 4*x + 5
assert e.match(p*x + q) == {p: 4, q: 5}
e = 4*x + 5*y + 6
assert e.match(p*x + q*y + r) == {p: 4, q: 5, r: 6}
a = Wild('a', exclude=[x])
e = 3*x
assert e.match(p*x) == {p: 3}
assert e.match(a*x) == {a: 3}
e = 3*x**2
assert e.match(p*x) == {p: 3*x}
assert e.match(a*x) is None
e = 3*x + 3 + 6/x
assert e.match(p*x**2 + p*x + 2*p) == {p: 3/x}
assert e.match(a*x**2 + a*x + 2*a) is None
def test_mul():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q = map(Wild, 'pq')
e = 4*x
assert e.match(p*x) == {p: 4}
assert e.match(p*y) is None
assert e.match(e + p*y) == {p: 0}
e = a*x*b*c
assert e.match(p*x) == {p: a*b*c}
assert e.match(c*p*x) == {p: a*b}
e = (a + b)*(a + c)
assert e.match((p + b)*(p + c)) == {p: a}
e = x
assert e.match(p*x) == {p: 1}
e = exp(x)
assert e.match(x**p*exp(x*q)) == {p: 0, q: 1}
e = I*Poly(x, x)
assert e.match(I*p) == {p: x}
def test_mul_noncommutative():
x, y = symbols('x y')
A, B, C = symbols('A B C', commutative=False)
u, v = symbols('u v', cls=Wild)
w, z = symbols('w z', cls=Wild, commutative=False)
assert (u*v).matches(x) in ({v: x, u: 1}, {u: x, v: 1})
assert (u*v).matches(x*y) in ({v: y, u: x}, {u: y, v: x})
assert (u*v).matches(A) is None
assert (u*v).matches(A*B) is None
assert (u*v).matches(x*A) is None
assert (u*v).matches(x*y*A) is None
assert (u*v).matches(x*A*B) is None
assert (u*v).matches(x*y*A*B) is None
assert (v*w).matches(x) is None
assert (v*w).matches(x*y) is None
assert (v*w).matches(A) == {w: A, v: 1}
assert (v*w).matches(A*B) == {w: A*B, v: 1}
assert (v*w).matches(x*A) == {w: A, v: x}
assert (v*w).matches(x*y*A) == {w: A, v: x*y}
assert (v*w).matches(x*A*B) == {w: A*B, v: x}
assert (v*w).matches(x*y*A*B) == {w: A*B, v: x*y}
assert (v*w).matches(-x) is None
assert (v*w).matches(-x*y) is None
assert (v*w).matches(-A) == {w: A, v: -1}
assert (v*w).matches(-A*B) == {w: A*B, v: -1}
assert (v*w).matches(-x*A) == {w: A, v: -x}
assert (v*w).matches(-x*y*A) == {w: A, v: -x*y}
assert (v*w).matches(-x*A*B) == {w: A*B, v: -x}
assert (v*w).matches(-x*y*A*B) == {w: A*B, v: -x*y}
assert (w*z).matches(x) is None
assert (w*z).matches(x*y) is None
assert (w*z).matches(A) is None
assert (w*z).matches(A*B) == {w: A, z: B}
assert (w*z).matches(B*A) == {w: B, z: A}
assert (w*z).matches(A*B*C) in [{w: A, z: B*C}, {w: A*B, z: C}]
assert (w*z).matches(x*A) is None
assert (w*z).matches(x*y*A) is None
assert (w*z).matches(x*A*B) is None
assert (w*z).matches(x*y*A*B) is None
assert (w*A).matches(A) is None
assert (A*w*B).matches(A*B) is None
assert (u*w*z).matches(x) is None
assert (u*w*z).matches(x*y) is None
assert (u*w*z).matches(A) is None
assert (u*w*z).matches(A*B) == {u: 1, w: A, z: B}
assert (u*w*z).matches(B*A) == {u: 1, w: B, z: A}
assert (u*w*z).matches(x*A) is None
assert (u*w*z).matches(x*y*A) is None
assert (u*w*z).matches(x*A*B) == {u: x, w: A, z: B}
assert (u*w*z).matches(x*B*A) == {u: x, w: B, z: A}
assert (u*w*z).matches(x*y*A*B) == {u: x*y, w: A, z: B}
assert (u*w*z).matches(x*y*B*A) == {u: x*y, w: B, z: A}
assert (u*A).matches(x*A) == {u: x}
assert (u*A).matches(x*A*B) is None
assert (u*B).matches(x*A) is None
assert (u*A*B).matches(x*A*B) == {u: x}
assert (u*A*B).matches(x*B*A) is None
assert (u*A*B).matches(x*A) is None
assert (u*w*A).matches(x*A*B) is None
assert (u*w*B).matches(x*A*B) == {u: x, w: A}
assert (u*v*A*B).matches(x*A*B) in [{u: x, v: 1}, {v: x, u: 1}]
assert (u*v*A*B).matches(x*B*A) is None
assert (u*v*A*B).matches(u*v*A*C) is None
def test_mul_noncommutative_mismatch():
A, B, C = symbols('A B C', commutative=False)
w = symbols('w', cls=Wild, commutative=False)
assert (w*B*w).matches(A*B*A) == {w: A}
assert (w*B*w).matches(A*C*B*A*C) == {w: A*C}
assert (w*B*w).matches(A*C*B*A*B) is None
assert (w*B*w).matches(A*B*C) is None
assert (w*w*C).matches(A*B*C) is None
def test_mul_noncommutative_pow():
A, B, C = symbols('A B C', commutative=False)
w = symbols('w', cls=Wild, commutative=False)
assert (A*B*w).matches(A*B**2) == {w: B}
assert (A*(B**2)*w*(B**3)).matches(A*B**8) == {w: B**3}
assert (A*B*w*C).matches(A*(B**4)*C) == {w: B**3}
assert (A*B*(w**(-1))).matches(A*B*(C**(-1))) == {w: C}
assert (A*(B*w)**(-1)*C).matches(A*(B*C)**(-1)*C) == {w: C}
assert ((w**2)*B*C).matches((A**2)*B*C) == {w: A}
assert ((w**2)*B*(w**3)).matches((A**2)*B*(A**3)) == {w: A}
assert ((w**2)*B*(w**4)).matches((A**2)*B*(A**2)) is None
def test_complex():
a, b, c = map(Symbol, 'abc')
x, y = map(Wild, 'xy')
assert (1 + I).match(x + I) == {x: 1}
assert (a + I).match(x + I) == {x: a}
assert (2*I).match(x*I) == {x: 2}
assert (a*I).match(x*I) == {x: a}
assert (a*I).match(x*y) == {x: I, y: a}
assert (2*I).match(x*y) == {x: 2, y: I}
assert (a + b*I).match(x + y*I) == {x: a, y: b}
def test_functions():
from sympy.core.function import WildFunction
x = Symbol('x')
g = WildFunction('g')
p = Wild('p')
q = Wild('q')
f = cos(5*x)
notf = x
assert f.match(p*cos(q*x)) == {p: 1, q: 5}
assert f.match(p*g) == {p: 1, g: cos(5*x)}
assert notf.match(g) is None
@XFAIL
def test_functions_X1():
from sympy.core.function import WildFunction
x = Symbol('x')
g = WildFunction('g')
p = Wild('p')
q = Wild('q')
f = cos(5*x)
assert f.match(p*g(q*x)) == {p: 1, g: cos, q: 5}
def test_interface():
x, y = map(Symbol, 'xy')
p, q = map(Wild, 'pq')
assert (x + 1).match(p + 1) == {p: x}
assert (x*3).match(p*3) == {p: x}
assert (x**3).match(p**3) == {p: x}
assert (x*cos(y)).match(p*cos(q)) == {p: x, q: y}
assert (x*y).match(p*q) in [{p:x, q:y}, {p:y, q:x}]
assert (x + y).match(p + q) in [{p:x, q:y}, {p:y, q:x}]
assert (x*y + 1).match(p*q) in [{p:1, q:1 + x*y}, {p:1 + x*y, q:1}]
def test_derivative1():
x, y = map(Symbol, 'xy')
p, q = map(Wild, 'pq')
f = Function('f', nargs=1)
fd = Derivative(f(x), x)
assert fd.match(p) == {p: fd}
assert (fd + 1).match(p + 1) == {p: fd}
assert (fd).match(fd) == {}
assert (3*fd).match(p*fd) is not None
assert (3*fd - 1).match(p*fd + q) == {p: 3, q: -1}
def test_derivative_bug1():
f = Function("f")
x = Symbol("x")
a = Wild("a", exclude=[f, x])
b = Wild("b", exclude=[f])
pattern = a * Derivative(f(x), x, x) + b
expr = Derivative(f(x), x) + x**2
d1 = {b: x**2}
d2 = pattern.xreplace(d1).matches(expr, d1)
assert d2 is None
def test_derivative2():
f = Function("f")
x = Symbol("x")
a = Wild("a", exclude=[f, x])
b = Wild("b", exclude=[f])
e = Derivative(f(x), x)
assert e.match(Derivative(f(x), x)) == {}
assert e.match(Derivative(f(x), x, x)) is None
e = Derivative(f(x), x, x)
assert e.match(Derivative(f(x), x)) is None
assert e.match(Derivative(f(x), x, x)) == {}
e = Derivative(f(x), x) + x**2
assert e.match(a*Derivative(f(x), x) + b) == {a: 1, b: x**2}
assert e.match(a*Derivative(f(x), x, x) + b) is None
e = Derivative(f(x), x, x) + x**2
assert e.match(a*Derivative(f(x), x) + b) is None
assert e.match(a*Derivative(f(x), x, x) + b) == {a: 1, b: x**2}
def test_match_deriv_bug1():
n = Function('n')
l = Function('l')
x = Symbol('x')
p = Wild('p')
e = diff(l(x), x)/x - diff(diff(n(x), x), x)/2 - \
diff(n(x), x)**2/4 + diff(n(x), x)*diff(l(x), x)/4
e = e.subs(n(x), -l(x)).doit()
t = x*exp(-l(x))
t2 = t.diff(x, x)/t
assert e.match( (p*t2).expand() ) == {p: Rational(-1, 2)}
def test_match_bug2():
x, y = map(Symbol, 'xy')
p, q, r = map(Wild, 'pqr')
res = (x + y).match(p + q + r)
assert (p + q + r).subs(res) == x + y
def test_match_bug3():
x, a, b = map(Symbol, 'xab')
p = Wild('p')
assert (b*x*exp(a*x)).match(x*exp(p*x)) is None
def test_match_bug4():
x = Symbol('x')
p = Wild('p')
e = x
assert e.match(-p*x) == {p: -1}
def test_match_bug5():
x = Symbol('x')
p = Wild('p')
e = -x
assert e.match(-p*x) == {p: 1}
def test_match_bug6():
x = Symbol('x')
p = Wild('p')
e = x
assert e.match(3*p*x) == {p: Rational(1)/3}
def test_match_polynomial():
x = Symbol('x')
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
c = Wild('c', exclude=[x])
d = Wild('d', exclude=[x])
eq = 4*x**3 + 3*x**2 + 2*x + 1
pattern = a*x**3 + b*x**2 + c*x + d
assert eq.match(pattern) == {a: 4, b: 3, c: 2, d: 1}
assert (eq - 3*x**2).match(pattern) == {a: 4, b: 0, c: 2, d: 1}
assert (x + sqrt(2) + 3).match(a + b*x + c*x**2) == \
{b: 1, a: sqrt(2) + 3, c: 0}
def test_exclude():
x, y, a = map(Symbol, 'xya')
p = Wild('p', exclude=[1, x])
q = Wild('q')
r = Wild('r', exclude=[sin, y])
assert sin(x).match(r) is None
assert cos(y).match(r) is None
e = 3*x**2 + y*x + a
assert e.match(p*x**2 + q*x + r) == {p: 3, q: y, r: a}
e = x + 1
assert e.match(x + p) is None
assert e.match(p + 1) is None
assert e.match(x + 1 + p) == {p: 0}
e = cos(x) + 5*sin(y)
assert e.match(r) is None
assert e.match(cos(y) + r) is None
assert e.match(r + p*sin(q)) == {r: cos(x), p: 5, q: y}
def test_floats():
a, b = map(Wild, 'ab')
e = cos(0.12345, evaluate=False)**2
r = e.match(a*cos(b)**2)
assert r == {a: 1, b: Float(0.12345)}
def test_Derivative_bug1():
f = Function("f")
x = abc.x
a = Wild("a", exclude=[f(x)])
b = Wild("b", exclude=[f(x)])
eq = f(x).diff(x)
assert eq.match(a*Derivative(f(x), x) + b) == {a: 1, b: 0}
def test_match_wild_wild():
p = Wild('p')
q = Wild('q')
r = Wild('r')
assert p.match(q + r) in [ {q: p, r: 0}, {q: 0, r: p} ]
assert p.match(q*r) in [ {q: p, r: 1}, {q: 1, r: p} ]
p = Wild('p')
q = Wild('q', exclude=[p])
r = Wild('r')
assert p.match(q + r) == {q: 0, r: p}
assert p.match(q*r) == {q: 1, r: p}
p = Wild('p')
q = Wild('q', exclude=[p])
r = Wild('r', exclude=[p])
assert p.match(q + r) is None
assert p.match(q*r) is None
def test__combine_inverse():
x, y = symbols("x y")
assert Mul._combine_inverse(x*I*y, x*I) == y
assert Mul._combine_inverse(x*x**(1 + y), x**(1 + y)) == x
assert Mul._combine_inverse(x*I*y, y*I) == x
assert Mul._combine_inverse(oo*I*y, y*I) is oo
assert Mul._combine_inverse(oo*I*y, oo*I) == y
assert Mul._combine_inverse(oo*I*y, oo*I) == y
assert Mul._combine_inverse(oo*y, -oo) == -y
assert Mul._combine_inverse(-oo*y, oo) == -y
assert Mul._combine_inverse((1-exp(x/y)),(exp(x/y)-1)) == -1
assert Add._combine_inverse(oo, oo) is S.Zero
assert Add._combine_inverse(oo*I, oo*I) is S.Zero
assert Add._combine_inverse(x*oo, x*oo) is S.Zero
assert Add._combine_inverse(-x*oo, -x*oo) is S.Zero
assert Add._combine_inverse((x - oo)*(x + oo), -oo)
def test_issue_3773():
x = symbols('x')
z, phi, r = symbols('z phi r')
c, A, B, N = symbols('c A B N', cls=Wild)
l = Wild('l', exclude=(0,))
eq = z * sin(2*phi) * r**7
matcher = c * sin(phi*N)**l * r**A * log(r)**B
assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7, B: 0}
assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7, B: 0}
assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7, B: 0}
assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7, B: 0}
matcher = c*sin(phi*N)**l * r**A
assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7}
assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7}
assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7}
assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7}
def test_issue_3883():
from sympy.abc import gamma, mu, x
f = (-gamma * (x - mu)**2 - log(gamma) + log(2*pi))/2
a, b, c = symbols('a b c', cls=Wild, exclude=(gamma,))
assert f.match(a * log(gamma) + b * gamma + c) == \
{a: Rational(-1, 2), b: -(mu - x)**2/2, c: log(2*pi)/2}
assert f.expand().collect(gamma).match(a * log(gamma) + b * gamma + c) == \
{a: Rational(-1, 2), b: (-(x - mu)**2/2).expand(), c: (log(2*pi)/2).expand()}
g1 = Wild('g1', exclude=[gamma])
g2 = Wild('g2', exclude=[gamma])
g3 = Wild('g3', exclude=[gamma])
assert f.expand().match(g1 * log(gamma) + g2 * gamma + g3) == \
{g3: log(2)/2 + log(pi)/2, g1: Rational(-1, 2), g2: -mu**2/2 + mu*x - x**2/2}
def test_issue_4418():
x = Symbol('x')
a, b, c = symbols('a b c', cls=Wild, exclude=(x,))
f, g = symbols('f g', cls=Function)
eq = diff(g(x)*f(x).diff(x), x)
assert eq.match(
g(x).diff(x)*f(x).diff(x) + g(x)*f(x).diff(x, x) + c) == {c: 0}
assert eq.match(a*g(x).diff(
x)*f(x).diff(x) + b*g(x)*f(x).diff(x, x) + c) == {a: 1, b: 1, c: 0}
def test_issue_4700():
f = Function('f')
x = Symbol('x')
a, b = symbols('a b', cls=Wild, exclude=(f(x),))
p = a*f(x) + b
eq1 = sin(x)
eq2 = f(x) + sin(x)
eq3 = f(x) + x + sin(x)
eq4 = x + sin(x)
assert eq1.match(p) == {a: 0, b: sin(x)}
assert eq2.match(p) == {a: 1, b: sin(x)}
assert eq3.match(p) == {a: 1, b: x + sin(x)}
assert eq4.match(p) == {a: 0, b: x + sin(x)}
def test_issue_5168():
a, b, c = symbols('a b c', cls=Wild)
x = Symbol('x')
f = Function('f')
assert x.match(a) == {a: x}
assert x.match(a*f(x)**c) == {a: x, c: 0}
assert x.match(a*b) == {a: 1, b: x}
assert x.match(a*b*f(x)**c) == {a: 1, b: x, c: 0}
assert (-x).match(a) == {a: -x}
assert (-x).match(a*f(x)**c) == {a: -x, c: 0}
assert (-x).match(a*b) == {a: -1, b: x}
assert (-x).match(a*b*f(x)**c) == {a: -1, b: x, c: 0}
assert (2*x).match(a) == {a: 2*x}
assert (2*x).match(a*f(x)**c) == {a: 2*x, c: 0}
assert (2*x).match(a*b) == {a: 2, b: x}
assert (2*x).match(a*b*f(x)**c) == {a: 2, b: x, c: 0}
assert (-2*x).match(a) == {a: -2*x}
assert (-2*x).match(a*f(x)**c) == {a: -2*x, c: 0}
assert (-2*x).match(a*b) == {a: -2, b: x}
assert (-2*x).match(a*b*f(x)**c) == {a: -2, b: x, c: 0}
def test_issue_4559():
x = Symbol('x')
e = Symbol('e')
w = Wild('w', exclude=[x])
y = Wild('y')
# this is as it should be
assert (3/x).match(w/y) == {w: 3, y: x}
assert (3*x).match(w*y) == {w: 3, y: x}
assert (x/3).match(y/w) == {w: 3, y: x}
assert (3*x).match(y/w) == {w: S.One/3, y: x}
assert (3*x).match(y/w) == {w: Rational(1, 3), y: x}
# these could be allowed to fail
assert (x/3).match(w/y) == {w: S.One/3, y: 1/x}
assert (3*x).match(w/y) == {w: 3, y: 1/x}
assert (3/x).match(w*y) == {w: 3, y: 1/x}
# Note that solve will give
# multiple roots but match only gives one:
#
# >>> solve(x**r-y**2,y)
# [-x**(r/2), x**(r/2)]
r = Symbol('r', rational=True)
assert (x**r).match(y**2) == {y: x**(r/2)}
assert (x**e).match(y**2) == {y: sqrt(x**e)}
# since (x**i = y) -> x = y**(1/i) where i is an integer
# the following should also be valid as long as y is not
# zero when i is negative.
a = Wild('a')
e = S.Zero
assert e.match(a) == {a: e}
assert e.match(1/a) is None
assert e.match(a**.3) is None
e = S(3)
assert e.match(1/a) == {a: 1/e}
assert e.match(1/a**2) == {a: 1/sqrt(e)}
e = pi
assert e.match(1/a) == {a: 1/e}
assert e.match(1/a**2) == {a: 1/sqrt(e)}
assert (-e).match(sqrt(a)) is None
assert (-e).match(a**2) == {a: I*sqrt(pi)}
# The pattern matcher doesn't know how to handle (x - a)**2 == (a - x)**2. To
# avoid ambiguity in actual applications, don't put a coefficient (including a
# minus sign) in front of a wild.
@XFAIL
def test_issue_4883():
a = Wild('a')
x = Symbol('x')
e = [i**2 for i in (x - 2, 2 - x)]
p = [i**2 for i in (x - a, a- x)]
for eq in e:
for pat in p:
assert eq.match(pat) == {a: 2}
def test_issue_4319():
x, y = symbols('x y')
p = -x*(S.One/8 - y)
ans = {S.Zero, y - S.One/8}
def ok(pat):
assert set(p.match(pat).values()) == ans
ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
ok(Wild("w", exclude=[x])*x + Wild("rest"))
ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
ok(Wild("w", exclude=[x])*x + Wild("rest"))
ok(Wild("e", exclude=[x])*x + Wild("rest"))
ok(Wild("ress", exclude=[x])*x + Wild("rest"))
ok(Wild("resu", exclude=[x])*x + Wild("rest"))
def test_issue_3778():
p, c, q = symbols('p c q', cls=Wild)
x = Symbol('x')
assert (sin(x)**2).match(sin(p)*sin(q)*c) == {q: x, c: 1, p: x}
assert (2*sin(x)).match(sin(p) + sin(q) + c) == {q: x, c: 0, p: x}
def test_issue_6103():
x = Symbol('x')
a = Wild('a')
assert (-I*x*oo).match(I*a*oo) == {a: -x}
def test_issue_3539():
a = Wild('a')
x = Symbol('x')
assert (x - 2).match(a - x) is None
assert (6/x).match(a*x) is None
assert (6/x**2).match(a/x) == {a: 6/x}
def test_gh_issue_2711():
x = Symbol('x')
f = meijerg(((), ()), ((0,), ()), x)
a = Wild('a')
b = Wild('b')
assert f.find(a) == {(S.Zero,), ((), ()), ((S.Zero,), ()), x, S.Zero,
(), meijerg(((), ()), ((S.Zero,), ()), x)}
assert f.find(a + b) == \
{meijerg(((), ()), ((S.Zero,), ()), x), x, S.Zero}
assert f.find(a**2) == {meijerg(((), ()), ((S.Zero,), ()), x), x}
def test_match_issue_17397():
f = Function("f")
x = Symbol("x")
a3 = Wild('a3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
deq = a3*(f(x).diff(x, 2)) + b3*f(x).diff(x) + c3*f(x)
eq = (x-2)**2*(f(x).diff(x, 2)) + (x-2)*(f(x).diff(x)) + ((x-2)**2 - 4)*f(x)
r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
assert r == {a3: (x - 2)**2, c3: (x - 2)**2 - 4, b3: x - 2}
eq =x*f(x) + x*Derivative(f(x), (x, 2)) - 4*f(x) + Derivative(f(x), x) \
- 4*Derivative(f(x), (x, 2)) - 2*Derivative(f(x), x)/x + 4*Derivative(f(x), (x, 2))/x
r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
assert r == {a3: x - 4 + 4/x, b3: 1 - 2/x, c3: x - 4}
def test_match_terms():
X, Y = map(Wild, "XY")
x, y, z = symbols('x y z')
assert (5*y - x).match(5*X - Y) == {X: y, Y: x}
# 15907
assert (x + (y - 1)*z).match(x + X*z) == {X: y - 1}
# 20747
assert (x - log(x/y)*(1-exp(x/y))).match(x - log(X/y)*(1-exp(x/y))) == {X: x}
def test_match_bound():
V, W = map(Wild, "VW")
x, y = symbols('x y')
assert Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, W))) == {W: 2}
assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, W))) == {W: 2, V:x}
assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, 2))) == {V:x}
|
7a403b1dfe6fe57555ed9fa10c255459191d85303bb753faed47a9849feb10b2 | 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,
conjugate, 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 _Conjugate(a):
return conjugate(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)))),
(r"\overline{z}", _Conjugate(z)),
(r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))),
(r"\overline{x + y}", _Conjugate(_Add(x, y))),
(r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)),
("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",
"\\overline{}",
"\\overline",
"{",
"}",
"\\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)
|
cd3cccef0178b64479878c2be61c66fa2f6409b6e707e5a21289f685fcfea515 | # 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_OVERLINE():
expr = convert_expr(func.base)
return sympy.conjugate(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
|
caf18e9598ec0c0955def1544dea3bf0298c966bdd6d0c4bd36d7bc8739c59a3 |
# 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
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2")
buf.write(u"Z\u0390\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4")
buf.write(u"\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r")
buf.write(u"\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22")
buf.write(u"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4")
buf.write(u"\30\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35")
buf.write(u"\t\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4")
buf.write(u"$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t")
buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63")
buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4")
buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA")
buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t")
buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S")
buf.write(u"\tS\4T\tT\4U\tU\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\3")
buf.write(u"\2\3\2\3\3\6\3\u00bb\n\3\r\3\16\3\u00bc\3\3\3\3\3\4\3")
buf.write(u"\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4\u00cd")
buf.write(u"\n\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5")
buf.write(u"\3\5\5\5\u00dc\n\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3")
buf.write(u"\6\3\6\3\6\3\6\3\6\3\6\3\6\5\6\u00ed\n\6\3\6\3\6\3\7")
buf.write(u"\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b")
buf.write(u"\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t")
buf.write(u"\3\t\3\t\3\t\3\t\3\t\5\t\u0111\n\t\3\t\3\t\3\n\3\n\3")
buf.write(u"\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3")
buf.write(u"\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13")
buf.write(u"\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3")
buf.write(u"\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3")
buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")
buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3")
buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")
buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3")
buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\5\16\u0179\n\16")
buf.write(u"\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22\3")
buf.write(u"\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\27")
buf.write(u"\3\30\3\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3")
buf.write(u"\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35")
buf.write(u"\3\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3")
buf.write(u"\36\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 ")
buf.write(u"\3 \3 \3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3")
buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!")
buf.write(u"\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3")
buf.write(u"!\3!\3!\3!\3!\5!\u01f4\n!\3\"\3\"\3\"\3\"\3\"\3#\3#\3")
buf.write(u"#\3#\3#\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3&\3&\3&\3&")
buf.write(u"\3&\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3*")
buf.write(u"\3*\3*\3*\3*\3+\3+\3+\3+\3+\3,\3,\3,\3,\3,\3-\3-\3-\3")
buf.write(u"-\3-\3.\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3/\3/")
buf.write(u"\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\61\3\61\3")
buf.write(u"\61\3\61\3\61\3\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62")
buf.write(u"\3\62\3\62\3\62\3\63\3\63\3\63\3\63\3\63\3\63\3\63\3")
buf.write(u"\63\3\64\3\64\3\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65")
buf.write(u"\3\65\3\65\3\66\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3")
buf.write(u"\67\3\67\3\67\3\67\3\67\3\67\38\38\38\38\38\38\38\38")
buf.write(u"\39\39\39\39\39\39\39\39\3:\3:\3:\3:\3:\3:\3:\3:\3;\3")
buf.write(u";\3;\3;\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<\3<\3=\3=\3=\3=")
buf.write(u"\3=\3=\3=\3>\3>\3>\3>\3>\3>\3?\3?\3?\3?\3?\3?\3?\3?\3")
buf.write(u"?\3?\3@\3@\3@\3@\3@\3@\3@\3A\3A\3A\3A\3A\3A\3B\3B\3B")
buf.write(u"\3B\3B\3C\3C\3C\3C\3C\3C\3D\3D\3D\3D\3D\3D\3D\3E\3E\3")
buf.write(u"E\3E\3E\3E\3E\3E\3F\3F\3F\3F\3F\3F\3F\3F\3G\3G\3G\3G")
buf.write(u"\3G\3G\3G\3G\3H\3H\3I\3I\3J\3J\3K\3K\3L\3L\7L\u02fb\n")
buf.write(u"L\fL\16L\u02fe\13L\3L\3L\3L\6L\u0303\nL\rL\16L\u0304")
buf.write(u"\5L\u0307\nL\3M\3M\3N\3N\3O\6O\u030e\nO\rO\16O\u030f")
buf.write(u"\3O\3O\3O\3O\3O\7O\u0317\nO\fO\16O\u031a\13O\3O\7O\u031d")
buf.write(u"\nO\fO\16O\u0320\13O\3O\3O\3O\3O\3O\7O\u0327\nO\fO\16")
buf.write(u"O\u032a\13O\3O\3O\6O\u032e\nO\rO\16O\u032f\5O\u0332\n")
buf.write(u"O\3P\3P\7P\u0336\nP\fP\16P\u0339\13P\5P\u033b\nP\3P\3")
buf.write(u"P\3P\7P\u0340\nP\fP\16P\u0343\13P\3P\5P\u0346\nP\5P\u0348")
buf.write(u"\nP\3Q\3Q\3Q\3Q\3Q\3R\3R\3S\3S\3S\3S\3S\3S\3S\3S\3S\5")
buf.write(u"S\u035a\nS\3T\3T\3T\3T\3T\3T\3U\3U\3U\3U\3U\3U\3U\3U")
buf.write(u"\3U\3U\3V\3V\3W\3W\3W\3W\3W\3W\3W\3W\3W\5W\u0377\nW\3")
buf.write(u"X\3X\3X\3X\3X\3X\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Z\3Z")
buf.write(u"\3[\3[\6[\u038d\n[\r[\16[\u038e\5\u02fc\u0337\u0341\2")
buf.write(u"\\\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r")
buf.write(u"\31\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30")
buf.write(u"/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K")
buf.write(u"\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8")
buf.write(u"o9q:s;u<w=y>{?}@\177A\u0081B\u0083C\u0085D\u0087E\u0089")
buf.write(u"F\u008bG\u008dH\u008fI\u0091J\u0093K\u0095\2\u0097L\u0099")
buf.write(u"M\u009b\2\u009dN\u009fO\u00a1P\u00a3Q\u00a5R\u00a7S\u00a9")
buf.write(u"T\u00abU\u00adV\u00afW\u00b1X\u00b3Y\u00b5Z\3\2\5\5\2")
buf.write(u"\13\f\17\17\"\"\4\2C\\c|\3\2\62;\2\u03b7\2\3\3\2\2\2")
buf.write(u"\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r")
buf.write(u"\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25")
buf.write(u"\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35")
buf.write(u"\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2")
buf.write(u"\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3")
buf.write(u"\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3")
buf.write(u"\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2")
buf.write(u"A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2")
buf.write(u"\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2")
buf.write(u"\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2")
buf.write(u"\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3")
buf.write(u"\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2")
buf.write(u"q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2\2")
buf.write(u"\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0081\3\2\2\2")
buf.write(u"\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089")
buf.write(u"\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2")
buf.write(u"\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0097\3\2\2\2")
buf.write(u"\2\u0099\3\2\2\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1")
buf.write(u"\3\2\2\2\2\u00a3\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2")
buf.write(u"\2\2\2\u00a9\3\2\2\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2")
buf.write(u"\2\u00af\3\2\2\2\2\u00b1\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5")
buf.write(u"\3\2\2\2\3\u00b7\3\2\2\2\5\u00ba\3\2\2\2\7\u00cc\3\2")
buf.write(u"\2\2\t\u00db\3\2\2\2\13\u00ec\3\2\2\2\r\u00f0\3\2\2\2")
buf.write(u"\17\u00f8\3\2\2\2\21\u0110\3\2\2\2\23\u0114\3\2\2\2\25")
buf.write(u"\u0123\3\2\2\2\27\u0134\3\2\2\2\31\u013c\3\2\2\2\33\u0178")
buf.write(u"\3\2\2\2\35\u017c\3\2\2\2\37\u017e\3\2\2\2!\u0180\3\2")
buf.write(u"\2\2#\u0182\3\2\2\2%\u0184\3\2\2\2\'\u0186\3\2\2\2)\u0188")
buf.write(u"\3\2\2\2+\u018a\3\2\2\2-\u018c\3\2\2\2/\u018f\3\2\2\2")
buf.write(u"\61\u0192\3\2\2\2\63\u0194\3\2\2\2\65\u0196\3\2\2\2\67")
buf.write(u"\u0198\3\2\2\29\u01a0\3\2\2\2;\u01a7\3\2\2\2=\u01af\3")
buf.write(u"\2\2\2?\u01b7\3\2\2\2A\u01f3\3\2\2\2C\u01f5\3\2\2\2E")
buf.write(u"\u01fa\3\2\2\2G\u01ff\3\2\2\2I\u0205\3\2\2\2K\u020a\3")
buf.write(u"\2\2\2M\u020f\3\2\2\2O\u0213\3\2\2\2Q\u0218\3\2\2\2S")
buf.write(u"\u021d\3\2\2\2U\u0222\3\2\2\2W\u0227\3\2\2\2Y\u022c\3")
buf.write(u"\2\2\2[\u0231\3\2\2\2]\u0239\3\2\2\2_\u0241\3\2\2\2a")
buf.write(u"\u0249\3\2\2\2c\u0251\3\2\2\2e\u0259\3\2\2\2g\u0261\3")
buf.write(u"\2\2\2i\u0267\3\2\2\2k\u026d\3\2\2\2m\u0273\3\2\2\2o")
buf.write(u"\u027b\3\2\2\2q\u0283\3\2\2\2s\u028b\3\2\2\2u\u0293\3")
buf.write(u"\2\2\2w\u029b\3\2\2\2y\u02a2\3\2\2\2{\u02a9\3\2\2\2}")
buf.write(u"\u02af\3\2\2\2\177\u02b9\3\2\2\2\u0081\u02c0\3\2\2\2")
buf.write(u"\u0083\u02c6\3\2\2\2\u0085\u02cb\3\2\2\2\u0087\u02d1")
buf.write(u"\3\2\2\2\u0089\u02d8\3\2\2\2\u008b\u02e0\3\2\2\2\u008d")
buf.write(u"\u02e8\3\2\2\2\u008f\u02f0\3\2\2\2\u0091\u02f2\3\2\2")
buf.write(u"\2\u0093\u02f4\3\2\2\2\u0095\u02f6\3\2\2\2\u0097\u02f8")
buf.write(u"\3\2\2\2\u0099\u0308\3\2\2\2\u009b\u030a\3\2\2\2\u009d")
buf.write(u"\u0331\3\2\2\2\u009f\u0347\3\2\2\2\u00a1\u0349\3\2\2")
buf.write(u"\2\u00a3\u034e\3\2\2\2\u00a5\u0359\3\2\2\2\u00a7\u035b")
buf.write(u"\3\2\2\2\u00a9\u0361\3\2\2\2\u00ab\u036b\3\2\2\2\u00ad")
buf.write(u"\u0376\3\2\2\2\u00af\u0378\3\2\2\2\u00b1\u037e\3\2\2")
buf.write(u"\2\u00b3\u0388\3\2\2\2\u00b5\u038a\3\2\2\2\u00b7\u00b8")
buf.write(u"\7.\2\2\u00b8\4\3\2\2\2\u00b9\u00bb\t\2\2\2\u00ba\u00b9")
buf.write(u"\3\2\2\2\u00bb\u00bc\3\2\2\2\u00bc\u00ba\3\2\2\2\u00bc")
buf.write(u"\u00bd\3\2\2\2\u00bd\u00be\3\2\2\2\u00be\u00bf\b\3\2")
buf.write(u"\2\u00bf\6\3\2\2\2\u00c0\u00c1\7^\2\2\u00c1\u00cd\7.")
buf.write(u"\2\2\u00c2\u00c3\7^\2\2\u00c3\u00c4\7v\2\2\u00c4\u00c5")
buf.write(u"\7j\2\2\u00c5\u00c6\7k\2\2\u00c6\u00c7\7p\2\2\u00c7\u00c8")
buf.write(u"\7u\2\2\u00c8\u00c9\7r\2\2\u00c9\u00ca\7c\2\2\u00ca\u00cb")
buf.write(u"\7e\2\2\u00cb\u00cd\7g\2\2\u00cc\u00c0\3\2\2\2\u00cc")
buf.write(u"\u00c2\3\2\2\2\u00cd\u00ce\3\2\2\2\u00ce\u00cf\b\4\2")
buf.write(u"\2\u00cf\b\3\2\2\2\u00d0\u00d1\7^\2\2\u00d1\u00dc\7<")
buf.write(u"\2\2\u00d2\u00d3\7^\2\2\u00d3\u00d4\7o\2\2\u00d4\u00d5")
buf.write(u"\7g\2\2\u00d5\u00d6\7f\2\2\u00d6\u00d7\7u\2\2\u00d7\u00d8")
buf.write(u"\7r\2\2\u00d8\u00d9\7c\2\2\u00d9\u00da\7e\2\2\u00da\u00dc")
buf.write(u"\7g\2\2\u00db\u00d0\3\2\2\2\u00db\u00d2\3\2\2\2\u00dc")
buf.write(u"\u00dd\3\2\2\2\u00dd\u00de\b\5\2\2\u00de\n\3\2\2\2\u00df")
buf.write(u"\u00e0\7^\2\2\u00e0\u00ed\7=\2\2\u00e1\u00e2\7^\2\2\u00e2")
buf.write(u"\u00e3\7v\2\2\u00e3\u00e4\7j\2\2\u00e4\u00e5\7k\2\2\u00e5")
buf.write(u"\u00e6\7e\2\2\u00e6\u00e7\7m\2\2\u00e7\u00e8\7u\2\2\u00e8")
buf.write(u"\u00e9\7r\2\2\u00e9\u00ea\7c\2\2\u00ea\u00eb\7e\2\2\u00eb")
buf.write(u"\u00ed\7g\2\2\u00ec\u00df\3\2\2\2\u00ec\u00e1\3\2\2\2")
buf.write(u"\u00ed\u00ee\3\2\2\2\u00ee\u00ef\b\6\2\2\u00ef\f\3\2")
buf.write(u"\2\2\u00f0\u00f1\7^\2\2\u00f1\u00f2\7s\2\2\u00f2\u00f3")
buf.write(u"\7w\2\2\u00f3\u00f4\7c\2\2\u00f4\u00f5\7f\2\2\u00f5\u00f6")
buf.write(u"\3\2\2\2\u00f6\u00f7\b\7\2\2\u00f7\16\3\2\2\2\u00f8\u00f9")
buf.write(u"\7^\2\2\u00f9\u00fa\7s\2\2\u00fa\u00fb\7s\2\2\u00fb\u00fc")
buf.write(u"\7w\2\2\u00fc\u00fd\7c\2\2\u00fd\u00fe\7f\2\2\u00fe\u00ff")
buf.write(u"\3\2\2\2\u00ff\u0100\b\b\2\2\u0100\20\3\2\2\2\u0101\u0102")
buf.write(u"\7^\2\2\u0102\u0111\7#\2\2\u0103\u0104\7^\2\2\u0104\u0105")
buf.write(u"\7p\2\2\u0105\u0106\7g\2\2\u0106\u0107\7i\2\2\u0107\u0108")
buf.write(u"\7v\2\2\u0108\u0109\7j\2\2\u0109\u010a\7k\2\2\u010a\u010b")
buf.write(u"\7p\2\2\u010b\u010c\7u\2\2\u010c\u010d\7r\2\2\u010d\u010e")
buf.write(u"\7c\2\2\u010e\u010f\7e\2\2\u010f\u0111\7g\2\2\u0110\u0101")
buf.write(u"\3\2\2\2\u0110\u0103\3\2\2\2\u0111\u0112\3\2\2\2\u0112")
buf.write(u"\u0113\b\t\2\2\u0113\22\3\2\2\2\u0114\u0115\7^\2\2\u0115")
buf.write(u"\u0116\7p\2\2\u0116\u0117\7g\2\2\u0117\u0118\7i\2\2\u0118")
buf.write(u"\u0119\7o\2\2\u0119\u011a\7g\2\2\u011a\u011b\7f\2\2\u011b")
buf.write(u"\u011c\7u\2\2\u011c\u011d\7r\2\2\u011d\u011e\7c\2\2\u011e")
buf.write(u"\u011f\7e\2\2\u011f\u0120\7g\2\2\u0120\u0121\3\2\2\2")
buf.write(u"\u0121\u0122\b\n\2\2\u0122\24\3\2\2\2\u0123\u0124\7^")
buf.write(u"\2\2\u0124\u0125\7p\2\2\u0125\u0126\7g\2\2\u0126\u0127")
buf.write(u"\7i\2\2\u0127\u0128\7v\2\2\u0128\u0129\7j\2\2\u0129\u012a")
buf.write(u"\7k\2\2\u012a\u012b\7e\2\2\u012b\u012c\7m\2\2\u012c\u012d")
buf.write(u"\7u\2\2\u012d\u012e\7r\2\2\u012e\u012f\7c\2\2\u012f\u0130")
buf.write(u"\7e\2\2\u0130\u0131\7g\2\2\u0131\u0132\3\2\2\2\u0132")
buf.write(u"\u0133\b\13\2\2\u0133\26\3\2\2\2\u0134\u0135\7^\2\2\u0135")
buf.write(u"\u0136\7n\2\2\u0136\u0137\7g\2\2\u0137\u0138\7h\2\2\u0138")
buf.write(u"\u0139\7v\2\2\u0139\u013a\3\2\2\2\u013a\u013b\b\f\2\2")
buf.write(u"\u013b\30\3\2\2\2\u013c\u013d\7^\2\2\u013d\u013e\7t\2")
buf.write(u"\2\u013e\u013f\7k\2\2\u013f\u0140\7i\2\2\u0140\u0141")
buf.write(u"\7j\2\2\u0141\u0142\7v\2\2\u0142\u0143\3\2\2\2\u0143")
buf.write(u"\u0144\b\r\2\2\u0144\32\3\2\2\2\u0145\u0146\7^\2\2\u0146")
buf.write(u"\u0147\7x\2\2\u0147\u0148\7t\2\2\u0148\u0149\7w\2\2\u0149")
buf.write(u"\u014a\7n\2\2\u014a\u0179\7g\2\2\u014b\u014c\7^\2\2\u014c")
buf.write(u"\u014d\7x\2\2\u014d\u014e\7e\2\2\u014e\u014f\7g\2\2\u014f")
buf.write(u"\u0150\7p\2\2\u0150\u0151\7v\2\2\u0151\u0152\7g\2\2\u0152")
buf.write(u"\u0179\7t\2\2\u0153\u0154\7^\2\2\u0154\u0155\7x\2\2\u0155")
buf.write(u"\u0156\7d\2\2\u0156\u0157\7q\2\2\u0157\u0179\7z\2\2\u0158")
buf.write(u"\u0159\7^\2\2\u0159\u015a\7x\2\2\u015a\u015b\7u\2\2\u015b")
buf.write(u"\u015c\7m\2\2\u015c\u015d\7k\2\2\u015d\u0179\7r\2\2\u015e")
buf.write(u"\u015f\7^\2\2\u015f\u0160\7x\2\2\u0160\u0161\7u\2\2\u0161")
buf.write(u"\u0162\7r\2\2\u0162\u0163\7c\2\2\u0163\u0164\7e\2\2\u0164")
buf.write(u"\u0179\7g\2\2\u0165\u0166\7^\2\2\u0166\u0167\7j\2\2\u0167")
buf.write(u"\u0168\7h\2\2\u0168\u0169\7k\2\2\u0169\u0179\7n\2\2\u016a")
buf.write(u"\u016b\7^\2\2\u016b\u0179\7,\2\2\u016c\u016d\7^\2\2\u016d")
buf.write(u"\u0179\7/\2\2\u016e\u016f\7^\2\2\u016f\u0179\7\60\2\2")
buf.write(u"\u0170\u0171\7^\2\2\u0171\u0179\7\61\2\2\u0172\u0173")
buf.write(u"\7^\2\2\u0173\u0179\7$\2\2\u0174\u0175\7^\2\2\u0175\u0179")
buf.write(u"\7*\2\2\u0176\u0177\7^\2\2\u0177\u0179\7?\2\2\u0178\u0145")
buf.write(u"\3\2\2\2\u0178\u014b\3\2\2\2\u0178\u0153\3\2\2\2\u0178")
buf.write(u"\u0158\3\2\2\2\u0178\u015e\3\2\2\2\u0178\u0165\3\2\2")
buf.write(u"\2\u0178\u016a\3\2\2\2\u0178\u016c\3\2\2\2\u0178\u016e")
buf.write(u"\3\2\2\2\u0178\u0170\3\2\2\2\u0178\u0172\3\2\2\2\u0178")
buf.write(u"\u0174\3\2\2\2\u0178\u0176\3\2\2\2\u0179\u017a\3\2\2")
buf.write(u"\2\u017a\u017b\b\16\2\2\u017b\34\3\2\2\2\u017c\u017d")
buf.write(u"\7-\2\2\u017d\36\3\2\2\2\u017e\u017f\7/\2\2\u017f \3")
buf.write(u"\2\2\2\u0180\u0181\7,\2\2\u0181\"\3\2\2\2\u0182\u0183")
buf.write(u"\7\61\2\2\u0183$\3\2\2\2\u0184\u0185\7*\2\2\u0185&\3")
buf.write(u"\2\2\2\u0186\u0187\7+\2\2\u0187(\3\2\2\2\u0188\u0189")
buf.write(u"\7}\2\2\u0189*\3\2\2\2\u018a\u018b\7\177\2\2\u018b,\3")
buf.write(u"\2\2\2\u018c\u018d\7^\2\2\u018d\u018e\7}\2\2\u018e.\3")
buf.write(u"\2\2\2\u018f\u0190\7^\2\2\u0190\u0191\7\177\2\2\u0191")
buf.write(u"\60\3\2\2\2\u0192\u0193\7]\2\2\u0193\62\3\2\2\2\u0194")
buf.write(u"\u0195\7_\2\2\u0195\64\3\2\2\2\u0196\u0197\7~\2\2\u0197")
buf.write(u"\66\3\2\2\2\u0198\u0199\7^\2\2\u0199\u019a\7t\2\2\u019a")
buf.write(u"\u019b\7k\2\2\u019b\u019c\7i\2\2\u019c\u019d\7j\2\2\u019d")
buf.write(u"\u019e\7v\2\2\u019e\u019f\7~\2\2\u019f8\3\2\2\2\u01a0")
buf.write(u"\u01a1\7^\2\2\u01a1\u01a2\7n\2\2\u01a2\u01a3\7g\2\2\u01a3")
buf.write(u"\u01a4\7h\2\2\u01a4\u01a5\7v\2\2\u01a5\u01a6\7~\2\2\u01a6")
buf.write(u":\3\2\2\2\u01a7\u01a8\7^\2\2\u01a8\u01a9\7n\2\2\u01a9")
buf.write(u"\u01aa\7c\2\2\u01aa\u01ab\7p\2\2\u01ab\u01ac\7i\2\2\u01ac")
buf.write(u"\u01ad\7n\2\2\u01ad\u01ae\7g\2\2\u01ae<\3\2\2\2\u01af")
buf.write(u"\u01b0\7^\2\2\u01b0\u01b1\7t\2\2\u01b1\u01b2\7c\2\2\u01b2")
buf.write(u"\u01b3\7p\2\2\u01b3\u01b4\7i\2\2\u01b4\u01b5\7n\2\2\u01b5")
buf.write(u"\u01b6\7g\2\2\u01b6>\3\2\2\2\u01b7\u01b8\7^\2\2\u01b8")
buf.write(u"\u01b9\7n\2\2\u01b9\u01ba\7k\2\2\u01ba\u01bb\7o\2\2\u01bb")
buf.write(u"@\3\2\2\2\u01bc\u01bd\7^\2\2\u01bd\u01be\7v\2\2\u01be")
buf.write(u"\u01f4\7q\2\2\u01bf\u01c0\7^\2\2\u01c0\u01c1\7t\2\2\u01c1")
buf.write(u"\u01c2\7k\2\2\u01c2\u01c3\7i\2\2\u01c3\u01c4\7j\2\2\u01c4")
buf.write(u"\u01c5\7v\2\2\u01c5\u01c6\7c\2\2\u01c6\u01c7\7t\2\2\u01c7")
buf.write(u"\u01c8\7t\2\2\u01c8\u01c9\7q\2\2\u01c9\u01f4\7y\2\2\u01ca")
buf.write(u"\u01cb\7^\2\2\u01cb\u01cc\7T\2\2\u01cc\u01cd\7k\2\2\u01cd")
buf.write(u"\u01ce\7i\2\2\u01ce\u01cf\7j\2\2\u01cf\u01d0\7v\2\2\u01d0")
buf.write(u"\u01d1\7c\2\2\u01d1\u01d2\7t\2\2\u01d2\u01d3\7t\2\2\u01d3")
buf.write(u"\u01d4\7q\2\2\u01d4\u01f4\7y\2\2\u01d5\u01d6\7^\2\2\u01d6")
buf.write(u"\u01d7\7n\2\2\u01d7\u01d8\7q\2\2\u01d8\u01d9\7p\2\2\u01d9")
buf.write(u"\u01da\7i\2\2\u01da\u01db\7t\2\2\u01db\u01dc\7k\2\2\u01dc")
buf.write(u"\u01dd\7i\2\2\u01dd\u01de\7j\2\2\u01de\u01df\7v\2\2\u01df")
buf.write(u"\u01e0\7c\2\2\u01e0\u01e1\7t\2\2\u01e1\u01e2\7t\2\2\u01e2")
buf.write(u"\u01e3\7q\2\2\u01e3\u01f4\7y\2\2\u01e4\u01e5\7^\2\2\u01e5")
buf.write(u"\u01e6\7N\2\2\u01e6\u01e7\7q\2\2\u01e7\u01e8\7p\2\2\u01e8")
buf.write(u"\u01e9\7i\2\2\u01e9\u01ea\7t\2\2\u01ea\u01eb\7k\2\2\u01eb")
buf.write(u"\u01ec\7i\2\2\u01ec\u01ed\7j\2\2\u01ed\u01ee\7v\2\2\u01ee")
buf.write(u"\u01ef\7c\2\2\u01ef\u01f0\7t\2\2\u01f0\u01f1\7t\2\2\u01f1")
buf.write(u"\u01f2\7q\2\2\u01f2\u01f4\7y\2\2\u01f3\u01bc\3\2\2\2")
buf.write(u"\u01f3\u01bf\3\2\2\2\u01f3\u01ca\3\2\2\2\u01f3\u01d5")
buf.write(u"\3\2\2\2\u01f3\u01e4\3\2\2\2\u01f4B\3\2\2\2\u01f5\u01f6")
buf.write(u"\7^\2\2\u01f6\u01f7\7k\2\2\u01f7\u01f8\7p\2\2\u01f8\u01f9")
buf.write(u"\7v\2\2\u01f9D\3\2\2\2\u01fa\u01fb\7^\2\2\u01fb\u01fc")
buf.write(u"\7u\2\2\u01fc\u01fd\7w\2\2\u01fd\u01fe\7o\2\2\u01feF")
buf.write(u"\3\2\2\2\u01ff\u0200\7^\2\2\u0200\u0201\7r\2\2\u0201")
buf.write(u"\u0202\7t\2\2\u0202\u0203\7q\2\2\u0203\u0204\7f\2\2\u0204")
buf.write(u"H\3\2\2\2\u0205\u0206\7^\2\2\u0206\u0207\7g\2\2\u0207")
buf.write(u"\u0208\7z\2\2\u0208\u0209\7r\2\2\u0209J\3\2\2\2\u020a")
buf.write(u"\u020b\7^\2\2\u020b\u020c\7n\2\2\u020c\u020d\7q\2\2\u020d")
buf.write(u"\u020e\7i\2\2\u020eL\3\2\2\2\u020f\u0210\7^\2\2\u0210")
buf.write(u"\u0211\7n\2\2\u0211\u0212\7p\2\2\u0212N\3\2\2\2\u0213")
buf.write(u"\u0214\7^\2\2\u0214\u0215\7u\2\2\u0215\u0216\7k\2\2\u0216")
buf.write(u"\u0217\7p\2\2\u0217P\3\2\2\2\u0218\u0219\7^\2\2\u0219")
buf.write(u"\u021a\7e\2\2\u021a\u021b\7q\2\2\u021b\u021c\7u\2\2\u021c")
buf.write(u"R\3\2\2\2\u021d\u021e\7^\2\2\u021e\u021f\7v\2\2\u021f")
buf.write(u"\u0220\7c\2\2\u0220\u0221\7p\2\2\u0221T\3\2\2\2\u0222")
buf.write(u"\u0223\7^\2\2\u0223\u0224\7e\2\2\u0224\u0225\7u\2\2\u0225")
buf.write(u"\u0226\7e\2\2\u0226V\3\2\2\2\u0227\u0228\7^\2\2\u0228")
buf.write(u"\u0229\7u\2\2\u0229\u022a\7g\2\2\u022a\u022b\7e\2\2\u022b")
buf.write(u"X\3\2\2\2\u022c\u022d\7^\2\2\u022d\u022e\7e\2\2\u022e")
buf.write(u"\u022f\7q\2\2\u022f\u0230\7v\2\2\u0230Z\3\2\2\2\u0231")
buf.write(u"\u0232\7^\2\2\u0232\u0233\7c\2\2\u0233\u0234\7t\2\2\u0234")
buf.write(u"\u0235\7e\2\2\u0235\u0236\7u\2\2\u0236\u0237\7k\2\2\u0237")
buf.write(u"\u0238\7p\2\2\u0238\\\3\2\2\2\u0239\u023a\7^\2\2\u023a")
buf.write(u"\u023b\7c\2\2\u023b\u023c\7t\2\2\u023c\u023d\7e\2\2\u023d")
buf.write(u"\u023e\7e\2\2\u023e\u023f\7q\2\2\u023f\u0240\7u\2\2\u0240")
buf.write(u"^\3\2\2\2\u0241\u0242\7^\2\2\u0242\u0243\7c\2\2\u0243")
buf.write(u"\u0244\7t\2\2\u0244\u0245\7e\2\2\u0245\u0246\7v\2\2\u0246")
buf.write(u"\u0247\7c\2\2\u0247\u0248\7p\2\2\u0248`\3\2\2\2\u0249")
buf.write(u"\u024a\7^\2\2\u024a\u024b\7c\2\2\u024b\u024c\7t\2\2\u024c")
buf.write(u"\u024d\7e\2\2\u024d\u024e\7e\2\2\u024e\u024f\7u\2\2\u024f")
buf.write(u"\u0250\7e\2\2\u0250b\3\2\2\2\u0251\u0252\7^\2\2\u0252")
buf.write(u"\u0253\7c\2\2\u0253\u0254\7t\2\2\u0254\u0255\7e\2\2\u0255")
buf.write(u"\u0256\7u\2\2\u0256\u0257\7g\2\2\u0257\u0258\7e\2\2\u0258")
buf.write(u"d\3\2\2\2\u0259\u025a\7^\2\2\u025a\u025b\7c\2\2\u025b")
buf.write(u"\u025c\7t\2\2\u025c\u025d\7e\2\2\u025d\u025e\7e\2\2\u025e")
buf.write(u"\u025f\7q\2\2\u025f\u0260\7v\2\2\u0260f\3\2\2\2\u0261")
buf.write(u"\u0262\7^\2\2\u0262\u0263\7u\2\2\u0263\u0264\7k\2\2\u0264")
buf.write(u"\u0265\7p\2\2\u0265\u0266\7j\2\2\u0266h\3\2\2\2\u0267")
buf.write(u"\u0268\7^\2\2\u0268\u0269\7e\2\2\u0269\u026a\7q\2\2\u026a")
buf.write(u"\u026b\7u\2\2\u026b\u026c\7j\2\2\u026cj\3\2\2\2\u026d")
buf.write(u"\u026e\7^\2\2\u026e\u026f\7v\2\2\u026f\u0270\7c\2\2\u0270")
buf.write(u"\u0271\7p\2\2\u0271\u0272\7j\2\2\u0272l\3\2\2\2\u0273")
buf.write(u"\u0274\7^\2\2\u0274\u0275\7c\2\2\u0275\u0276\7t\2\2\u0276")
buf.write(u"\u0277\7u\2\2\u0277\u0278\7k\2\2\u0278\u0279\7p\2\2\u0279")
buf.write(u"\u027a\7j\2\2\u027an\3\2\2\2\u027b\u027c\7^\2\2\u027c")
buf.write(u"\u027d\7c\2\2\u027d\u027e\7t\2\2\u027e\u027f\7e\2\2\u027f")
buf.write(u"\u0280\7q\2\2\u0280\u0281\7u\2\2\u0281\u0282\7j\2\2\u0282")
buf.write(u"p\3\2\2\2\u0283\u0284\7^\2\2\u0284\u0285\7c\2\2\u0285")
buf.write(u"\u0286\7t\2\2\u0286\u0287\7v\2\2\u0287\u0288\7c\2\2\u0288")
buf.write(u"\u0289\7p\2\2\u0289\u028a\7j\2\2\u028ar\3\2\2\2\u028b")
buf.write(u"\u028c\7^\2\2\u028c\u028d\7n\2\2\u028d\u028e\7h\2\2\u028e")
buf.write(u"\u028f\7n\2\2\u028f\u0290\7q\2\2\u0290\u0291\7q\2\2\u0291")
buf.write(u"\u0292\7t\2\2\u0292t\3\2\2\2\u0293\u0294\7^\2\2\u0294")
buf.write(u"\u0295\7t\2\2\u0295\u0296\7h\2\2\u0296\u0297\7n\2\2\u0297")
buf.write(u"\u0298\7q\2\2\u0298\u0299\7q\2\2\u0299\u029a\7t\2\2\u029a")
buf.write(u"v\3\2\2\2\u029b\u029c\7^\2\2\u029c\u029d\7n\2\2\u029d")
buf.write(u"\u029e\7e\2\2\u029e\u029f\7g\2\2\u029f\u02a0\7k\2\2\u02a0")
buf.write(u"\u02a1\7n\2\2\u02a1x\3\2\2\2\u02a2\u02a3\7^\2\2\u02a3")
buf.write(u"\u02a4\7t\2\2\u02a4\u02a5\7e\2\2\u02a5\u02a6\7g\2\2\u02a6")
buf.write(u"\u02a7\7k\2\2\u02a7\u02a8\7n\2\2\u02a8z\3\2\2\2\u02a9")
buf.write(u"\u02aa\7^\2\2\u02aa\u02ab\7u\2\2\u02ab\u02ac\7s\2\2\u02ac")
buf.write(u"\u02ad\7t\2\2\u02ad\u02ae\7v\2\2\u02ae|\3\2\2\2\u02af")
buf.write(u"\u02b0\7^\2\2\u02b0\u02b1\7q\2\2\u02b1\u02b2\7x\2\2\u02b2")
buf.write(u"\u02b3\7g\2\2\u02b3\u02b4\7t\2\2\u02b4\u02b5\7n\2\2\u02b5")
buf.write(u"\u02b6\7k\2\2\u02b6\u02b7\7p\2\2\u02b7\u02b8\7g\2\2\u02b8")
buf.write(u"~\3\2\2\2\u02b9\u02ba\7^\2\2\u02ba\u02bb\7v\2\2\u02bb")
buf.write(u"\u02bc\7k\2\2\u02bc\u02bd\7o\2\2\u02bd\u02be\7g\2\2\u02be")
buf.write(u"\u02bf\7u\2\2\u02bf\u0080\3\2\2\2\u02c0\u02c1\7^\2\2")
buf.write(u"\u02c1\u02c2\7e\2\2\u02c2\u02c3\7f\2\2\u02c3\u02c4\7")
buf.write(u"q\2\2\u02c4\u02c5\7v\2\2\u02c5\u0082\3\2\2\2\u02c6\u02c7")
buf.write(u"\7^\2\2\u02c7\u02c8\7f\2\2\u02c8\u02c9\7k\2\2\u02c9\u02ca")
buf.write(u"\7x\2\2\u02ca\u0084\3\2\2\2\u02cb\u02cc\7^\2\2\u02cc")
buf.write(u"\u02cd\7h\2\2\u02cd\u02ce\7t\2\2\u02ce\u02cf\7c\2\2\u02cf")
buf.write(u"\u02d0\7e\2\2\u02d0\u0086\3\2\2\2\u02d1\u02d2\7^\2\2")
buf.write(u"\u02d2\u02d3\7d\2\2\u02d3\u02d4\7k\2\2\u02d4\u02d5\7")
buf.write(u"p\2\2\u02d5\u02d6\7q\2\2\u02d6\u02d7\7o\2\2\u02d7\u0088")
buf.write(u"\3\2\2\2\u02d8\u02d9\7^\2\2\u02d9\u02da\7f\2\2\u02da")
buf.write(u"\u02db\7d\2\2\u02db\u02dc\7k\2\2\u02dc\u02dd\7p\2\2\u02dd")
buf.write(u"\u02de\7q\2\2\u02de\u02df\7o\2\2\u02df\u008a\3\2\2\2")
buf.write(u"\u02e0\u02e1\7^\2\2\u02e1\u02e2\7v\2\2\u02e2\u02e3\7")
buf.write(u"d\2\2\u02e3\u02e4\7k\2\2\u02e4\u02e5\7p\2\2\u02e5\u02e6")
buf.write(u"\7q\2\2\u02e6\u02e7\7o\2\2\u02e7\u008c\3\2\2\2\u02e8")
buf.write(u"\u02e9\7^\2\2\u02e9\u02ea\7o\2\2\u02ea\u02eb\7c\2\2\u02eb")
buf.write(u"\u02ec\7v\2\2\u02ec\u02ed\7j\2\2\u02ed\u02ee\7k\2\2\u02ee")
buf.write(u"\u02ef\7v\2\2\u02ef\u008e\3\2\2\2\u02f0\u02f1\7a\2\2")
buf.write(u"\u02f1\u0090\3\2\2\2\u02f2\u02f3\7`\2\2\u02f3\u0092\3")
buf.write(u"\2\2\2\u02f4\u02f5\7<\2\2\u02f5\u0094\3\2\2\2\u02f6\u02f7")
buf.write(u"\t\2\2\2\u02f7\u0096\3\2\2\2\u02f8\u02fc\7f\2\2\u02f9")
buf.write(u"\u02fb\5\u0095K\2\u02fa\u02f9\3\2\2\2\u02fb\u02fe\3\2")
buf.write(u"\2\2\u02fc\u02fd\3\2\2\2\u02fc\u02fa\3\2\2\2\u02fd\u0306")
buf.write(u"\3\2\2\2\u02fe\u02fc\3\2\2\2\u02ff\u0307\t\3\2\2\u0300")
buf.write(u"\u0302\7^\2\2\u0301\u0303\t\3\2\2\u0302\u0301\3\2\2\2")
buf.write(u"\u0303\u0304\3\2\2\2\u0304\u0302\3\2\2\2\u0304\u0305")
buf.write(u"\3\2\2\2\u0305\u0307\3\2\2\2\u0306\u02ff\3\2\2\2\u0306")
buf.write(u"\u0300\3\2\2\2\u0307\u0098\3\2\2\2\u0308\u0309\t\3\2")
buf.write(u"\2\u0309\u009a\3\2\2\2\u030a\u030b\t\4\2\2\u030b\u009c")
buf.write(u"\3\2\2\2\u030c\u030e\5\u009bN\2\u030d\u030c\3\2\2\2\u030e")
buf.write(u"\u030f\3\2\2\2\u030f\u030d\3\2\2\2\u030f\u0310\3\2\2")
buf.write(u"\2\u0310\u0318\3\2\2\2\u0311\u0312\7.\2\2\u0312\u0313")
buf.write(u"\5\u009bN\2\u0313\u0314\5\u009bN\2\u0314\u0315\5\u009b")
buf.write(u"N\2\u0315\u0317\3\2\2\2\u0316\u0311\3\2\2\2\u0317\u031a")
buf.write(u"\3\2\2\2\u0318\u0316\3\2\2\2\u0318\u0319\3\2\2\2\u0319")
buf.write(u"\u0332\3\2\2\2\u031a\u0318\3\2\2\2\u031b\u031d\5\u009b")
buf.write(u"N\2\u031c\u031b\3\2\2\2\u031d\u0320\3\2\2\2\u031e\u031c")
buf.write(u"\3\2\2\2\u031e\u031f\3\2\2\2\u031f\u0328\3\2\2\2\u0320")
buf.write(u"\u031e\3\2\2\2\u0321\u0322\7.\2\2\u0322\u0323\5\u009b")
buf.write(u"N\2\u0323\u0324\5\u009bN\2\u0324\u0325\5\u009bN\2\u0325")
buf.write(u"\u0327\3\2\2\2\u0326\u0321\3\2\2\2\u0327\u032a\3\2\2")
buf.write(u"\2\u0328\u0326\3\2\2\2\u0328\u0329\3\2\2\2\u0329\u032b")
buf.write(u"\3\2\2\2\u032a\u0328\3\2\2\2\u032b\u032d\7\60\2\2\u032c")
buf.write(u"\u032e\5\u009bN\2\u032d\u032c\3\2\2\2\u032e\u032f\3\2")
buf.write(u"\2\2\u032f\u032d\3\2\2\2\u032f\u0330\3\2\2\2\u0330\u0332")
buf.write(u"\3\2\2\2\u0331\u030d\3\2\2\2\u0331\u031e\3\2\2\2\u0332")
buf.write(u"\u009e\3\2\2\2\u0333\u0337\7(\2\2\u0334\u0336\5\u0095")
buf.write(u"K\2\u0335\u0334\3\2\2\2\u0336\u0339\3\2\2\2\u0337\u0338")
buf.write(u"\3\2\2\2\u0337\u0335\3\2\2\2\u0338\u033b\3\2\2\2\u0339")
buf.write(u"\u0337\3\2\2\2\u033a\u0333\3\2\2\2\u033a\u033b\3\2\2")
buf.write(u"\2\u033b\u033c\3\2\2\2\u033c\u0348\7?\2\2\u033d\u0345")
buf.write(u"\7?\2\2\u033e\u0340\5\u0095K\2\u033f\u033e\3\2\2\2\u0340")
buf.write(u"\u0343\3\2\2\2\u0341\u0342\3\2\2\2\u0341\u033f\3\2\2")
buf.write(u"\2\u0342\u0344\3\2\2\2\u0343\u0341\3\2\2\2\u0344\u0346")
buf.write(u"\7(\2\2\u0345\u0341\3\2\2\2\u0345\u0346\3\2\2\2\u0346")
buf.write(u"\u0348\3\2\2\2\u0347\u033a\3\2\2\2\u0347\u033d\3\2\2")
buf.write(u"\2\u0348\u00a0\3\2\2\2\u0349\u034a\7^\2\2\u034a\u034b")
buf.write(u"\7p\2\2\u034b\u034c\7g\2\2\u034c\u034d\7s\2\2\u034d\u00a2")
buf.write(u"\3\2\2\2\u034e\u034f\7>\2\2\u034f\u00a4\3\2\2\2\u0350")
buf.write(u"\u0351\7^\2\2\u0351\u0352\7n\2\2\u0352\u0353\7g\2\2\u0353")
buf.write(u"\u035a\7s\2\2\u0354\u0355\7^\2\2\u0355\u0356\7n\2\2\u0356")
buf.write(u"\u035a\7g\2\2\u0357\u035a\5\u00a7T\2\u0358\u035a\5\u00a9")
buf.write(u"U\2\u0359\u0350\3\2\2\2\u0359\u0354\3\2\2\2\u0359\u0357")
buf.write(u"\3\2\2\2\u0359\u0358\3\2\2\2\u035a\u00a6\3\2\2\2\u035b")
buf.write(u"\u035c\7^\2\2\u035c\u035d\7n\2\2\u035d\u035e\7g\2\2\u035e")
buf.write(u"\u035f\7s\2\2\u035f\u0360\7s\2\2\u0360\u00a8\3\2\2\2")
buf.write(u"\u0361\u0362\7^\2\2\u0362\u0363\7n\2\2\u0363\u0364\7")
buf.write(u"g\2\2\u0364\u0365\7s\2\2\u0365\u0366\7u\2\2\u0366\u0367")
buf.write(u"\7n\2\2\u0367\u0368\7c\2\2\u0368\u0369\7p\2\2\u0369\u036a")
buf.write(u"\7v\2\2\u036a\u00aa\3\2\2\2\u036b\u036c\7@\2\2\u036c")
buf.write(u"\u00ac\3\2\2\2\u036d\u036e\7^\2\2\u036e\u036f\7i\2\2")
buf.write(u"\u036f\u0370\7g\2\2\u0370\u0377\7s\2\2\u0371\u0372\7")
buf.write(u"^\2\2\u0372\u0373\7i\2\2\u0373\u0377\7g\2\2\u0374\u0377")
buf.write(u"\5\u00afX\2\u0375\u0377\5\u00b1Y\2\u0376\u036d\3\2\2")
buf.write(u"\2\u0376\u0371\3\2\2\2\u0376\u0374\3\2\2\2\u0376\u0375")
buf.write(u"\3\2\2\2\u0377\u00ae\3\2\2\2\u0378\u0379\7^\2\2\u0379")
buf.write(u"\u037a\7i\2\2\u037a\u037b\7g\2\2\u037b\u037c\7s\2\2\u037c")
buf.write(u"\u037d\7s\2\2\u037d\u00b0\3\2\2\2\u037e\u037f\7^\2\2")
buf.write(u"\u037f\u0380\7i\2\2\u0380\u0381\7g\2\2\u0381\u0382\7")
buf.write(u"s\2\2\u0382\u0383\7u\2\2\u0383\u0384\7n\2\2\u0384\u0385")
buf.write(u"\7c\2\2\u0385\u0386\7p\2\2\u0386\u0387\7v\2\2\u0387\u00b2")
buf.write(u"\3\2\2\2\u0388\u0389\7#\2\2\u0389\u00b4\3\2\2\2\u038a")
buf.write(u"\u038c\7^\2\2\u038b\u038d\t\3\2\2\u038c\u038b\3\2\2\2")
buf.write(u"\u038d\u038e\3\2\2\2\u038e\u038c\3\2\2\2\u038e\u038f")
buf.write(u"\3\2\2\2\u038f\u00b6\3\2\2\2\33\2\u00bc\u00cc\u00db\u00ec")
buf.write(u"\u0110\u0178\u01f3\u02fc\u0304\u0306\u030f\u0318\u031e")
buf.write(u"\u0328\u032f\u0331\u0337\u033a\u0341\u0345\u0347\u0359")
buf.write(u"\u0376\u038e\3\b\2\2")
return buf.getvalue()
class LaTeXLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
WS = 2
THINSPACE = 3
MEDSPACE = 4
THICKSPACE = 5
QUAD = 6
QQUAD = 7
NEGTHINSPACE = 8
NEGMEDSPACE = 9
NEGTHICKSPACE = 10
CMD_LEFT = 11
CMD_RIGHT = 12
IGNORE = 13
ADD = 14
SUB = 15
MUL = 16
DIV = 17
L_PAREN = 18
R_PAREN = 19
L_BRACE = 20
R_BRACE = 21
L_BRACE_LITERAL = 22
R_BRACE_LITERAL = 23
L_BRACKET = 24
R_BRACKET = 25
BAR = 26
R_BAR = 27
L_BAR = 28
L_ANGLE = 29
R_ANGLE = 30
FUNC_LIM = 31
LIM_APPROACH_SYM = 32
FUNC_INT = 33
FUNC_SUM = 34
FUNC_PROD = 35
FUNC_EXP = 36
FUNC_LOG = 37
FUNC_LN = 38
FUNC_SIN = 39
FUNC_COS = 40
FUNC_TAN = 41
FUNC_CSC = 42
FUNC_SEC = 43
FUNC_COT = 44
FUNC_ARCSIN = 45
FUNC_ARCCOS = 46
FUNC_ARCTAN = 47
FUNC_ARCCSC = 48
FUNC_ARCSEC = 49
FUNC_ARCCOT = 50
FUNC_SINH = 51
FUNC_COSH = 52
FUNC_TANH = 53
FUNC_ARSINH = 54
FUNC_ARCOSH = 55
FUNC_ARTANH = 56
L_FLOOR = 57
R_FLOOR = 58
L_CEIL = 59
R_CEIL = 60
FUNC_SQRT = 61
FUNC_OVERLINE = 62
CMD_TIMES = 63
CMD_CDOT = 64
CMD_DIV = 65
CMD_FRAC = 66
CMD_BINOM = 67
CMD_DBINOM = 68
CMD_TBINOM = 69
CMD_MATHIT = 70
UNDERSCORE = 71
CARET = 72
COLON = 73
DIFFERENTIAL = 74
LETTER = 75
NUMBER = 76
EQUAL = 77
NEQ = 78
LT = 79
LTE = 80
LTE_Q = 81
LTE_S = 82
GT = 83
GTE = 84
GTE_Q = 85
GTE_S = 86
BANG = 87
SYMBOL = 88
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ u"DEFAULT_MODE" ]
literalNames = [ u"<INVALID>",
u"','", u"'\\quad'", u"'\\qquad'", u"'\\negmedspace'", u"'\\negthickspace'",
u"'\\left'", u"'\\right'", u"'+'", u"'-'", u"'*'", u"'/'", u"'('",
u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'",
u"'|'", u"'\\right|'", u"'\\left|'", u"'\\langle'", u"'\\rangle'",
u"'\\lim'", u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'",
u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'",
u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'",
u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'",
u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'",
u"'\\rfloor'", u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\overline'",
u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'", u"'\\binom'",
u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'",
u"':'", u"'\\neq'", u"'<'", u"'\\leqq'", u"'\\leqslant'", u"'>'",
u"'\\geqq'", u"'\\geqslant'", u"'!'" ]
symbolicNames = [ u"<INVALID>",
u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD",
u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT",
u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN",
u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL",
u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE",
u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM",
u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN",
u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT",
u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC",
u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH",
u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH",
u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT",
u"FUNC_OVERLINE", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC",
u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE",
u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL",
u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q",
u"GTE_S", u"BANG", u"SYMBOL" ]
ruleNames = [ u"T__0", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE",
u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE",
u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB",
u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE",
u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET",
u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE",
u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT",
u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN",
u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC",
u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN",
u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH",
u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH",
u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL",
u"FUNC_SQRT", u"FUNC_OVERLINE", u"CMD_TIMES", u"CMD_CDOT",
u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM",
u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET",
u"COLON", u"WS_CHAR", u"DIFFERENTIAL", u"LETTER", u"DIGIT",
u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q",
u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG",
u"SYMBOL" ]
grammarFileName = u"LaTeX.g4"
def __init__(self, input=None, output=sys.stdout):
super(LaTeXLexer, self).__init__(input, output=output)
self.checkVersion("4.7.2")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
|
5096da4c9f14859b9dab9e2bf733120be47dbd518867e55d7ca31492b914d11e |
# 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
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3")
buf.write(u"Z\u01d5\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t")
buf.write(u"\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write(u"\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4")
buf.write(u"\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30")
buf.write(u"\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t")
buf.write(u"\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$")
buf.write(u"\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\3\2\3\3\3\3\3")
buf.write(u"\3\3\3\3\3\3\3\7\3[\n\3\f\3\16\3^\13\3\3\4\3\4\3\4\3")
buf.write(u"\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\7\6l\n\6\f\6\16\6")
buf.write(u"o\13\6\3\7\3\7\3\7\3\7\3\7\3\7\7\7w\n\7\f\7\16\7z\13")
buf.write(u"\7\3\b\3\b\3\b\3\b\3\b\3\b\7\b\u0082\n\b\f\b\16\b\u0085")
buf.write(u"\13\b\3\t\3\t\3\t\6\t\u008a\n\t\r\t\16\t\u008b\5\t\u008e")
buf.write(u"\n\t\3\n\3\n\3\n\3\n\7\n\u0094\n\n\f\n\16\n\u0097\13")
buf.write(u"\n\5\n\u0099\n\n\3\13\3\13\7\13\u009d\n\13\f\13\16\13")
buf.write(u"\u00a0\13\13\3\f\3\f\7\f\u00a4\n\f\f\f\16\f\u00a7\13")
buf.write(u"\f\3\r\3\r\5\r\u00ab\n\r\3\16\3\16\3\16\3\16\3\16\3\16")
buf.write(u"\5\16\u00b3\n\16\3\17\3\17\3\17\3\17\5\17\u00b9\n\17")
buf.write(u"\3\17\3\17\3\20\3\20\3\20\3\20\5\20\u00c1\n\20\3\20\3")
buf.write(u"\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21")
buf.write(u"\5\21\u00cf\n\21\3\21\5\21\u00d2\n\21\7\21\u00d4\n\21")
buf.write(u"\f\21\16\21\u00d7\13\21\3\22\3\22\3\22\3\22\3\22\3\22")
buf.write(u"\3\22\3\22\3\22\3\22\5\22\u00e3\n\22\3\22\5\22\u00e6")
buf.write(u"\n\22\7\22\u00e8\n\22\f\22\16\22\u00eb\13\22\3\23\3\23")
buf.write(u"\3\23\3\23\3\23\3\23\3\23\3\23\5\23\u00f5\n\23\3\24\3")
buf.write(u"\24\3\24\3\24\3\24\3\24\3\24\5\24\u00fe\n\24\3\25\3\25")
buf.write(u"\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3")
buf.write(u"\25\3\25\3\25\3\25\5\25\u0110\n\25\3\26\3\26\3\26\3\26")
buf.write(u"\3\27\3\27\5\27\u0118\n\27\3\27\3\27\3\27\3\27\3\27\5")
buf.write(u"\27\u011f\n\27\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31")
buf.write(u"\3\32\3\32\3\32\3\32\3\32\3\33\7\33\u012f\n\33\f\33\16")
buf.write(u"\33\u0132\13\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3")
buf.write(u"\34\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\36\3\36")
buf.write(u"\3\36\3\36\3\37\3\37\3\37\3\37\3 \3 \3!\3!\5!\u0150\n")
buf.write(u"!\3!\5!\u0153\n!\3!\5!\u0156\n!\3!\5!\u0159\n!\5!\u015b")
buf.write(u"\n!\3!\3!\3!\3!\3!\5!\u0162\n!\3!\3!\5!\u0166\n!\3!\3")
buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\5!\u0173\n!\3!\5!\u0176")
buf.write(u"\n!\3!\3!\3!\5!\u017b\n!\3!\3!\3!\3!\3!\5!\u0182\n!\3")
buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\5!\u0194")
buf.write(u"\n!\3!\3!\3!\3!\3!\3!\5!\u019c\n!\3\"\3\"\3\"\3\"\3\"")
buf.write(u"\5\"\u01a3\n\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\5#\u01ae\n")
buf.write(u"#\3#\3#\3$\3$\3$\3$\3$\5$\u01b7\n$\3%\3%\3&\3&\3&\3&")
buf.write(u"\3&\3&\5&\u01c1\n&\3\'\3\'\3\'\3\'\3\'\3\'\5\'\u01c9")
buf.write(u"\n\'\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\2\b\4\n\f\16 \"")
buf.write(u"*\2\4\6\b\n\f\16\20\22\24\26\30\32\34\36 \"$&(*,.\60")
buf.write(u"\62\64\668:<>@BDFHJLNP\2\13\4\2ORUV\3\2\20\21\5\2\22")
buf.write(u"\23ACKK\4\2MMZZ\3\2\34\35\4\2\34\34\36\36\3\2EG\3\2&")
buf.write(u":\3\2$%\2\u01f1\2R\3\2\2\2\4T\3\2\2\2\6_\3\2\2\2\bc\3")
buf.write(u"\2\2\2\ne\3\2\2\2\fp\3\2\2\2\16{\3\2\2\2\20\u008d\3\2")
buf.write(u"\2\2\22\u0098\3\2\2\2\24\u009a\3\2\2\2\26\u00a1\3\2\2")
buf.write(u"\2\30\u00aa\3\2\2\2\32\u00ac\3\2\2\2\34\u00b4\3\2\2\2")
buf.write(u"\36\u00bc\3\2\2\2 \u00c4\3\2\2\2\"\u00d8\3\2\2\2$\u00f4")
buf.write(u"\3\2\2\2&\u00fd\3\2\2\2(\u010f\3\2\2\2*\u0111\3\2\2\2")
buf.write(u",\u011e\3\2\2\2.\u0120\3\2\2\2\60\u0124\3\2\2\2\62\u0128")
buf.write(u"\3\2\2\2\64\u0130\3\2\2\2\66\u0133\3\2\2\28\u013b\3\2")
buf.write(u"\2\2:\u0143\3\2\2\2<\u0147\3\2\2\2>\u014b\3\2\2\2@\u019b")
buf.write(u"\3\2\2\2B\u01a2\3\2\2\2D\u01a4\3\2\2\2F\u01b6\3\2\2\2")
buf.write(u"H\u01b8\3\2\2\2J\u01ba\3\2\2\2L\u01c2\3\2\2\2N\u01ca")
buf.write(u"\3\2\2\2P\u01cf\3\2\2\2RS\5\4\3\2S\3\3\2\2\2TU\b\3\1")
buf.write(u"\2UV\5\b\5\2V\\\3\2\2\2WX\f\4\2\2XY\t\2\2\2Y[\5\4\3\5")
buf.write(u"ZW\3\2\2\2[^\3\2\2\2\\Z\3\2\2\2\\]\3\2\2\2]\5\3\2\2\2")
buf.write(u"^\\\3\2\2\2_`\5\b\5\2`a\7O\2\2ab\5\b\5\2b\7\3\2\2\2c")
buf.write(u"d\5\n\6\2d\t\3\2\2\2ef\b\6\1\2fg\5\f\7\2gm\3\2\2\2hi")
buf.write(u"\f\4\2\2ij\t\3\2\2jl\5\n\6\5kh\3\2\2\2lo\3\2\2\2mk\3")
buf.write(u"\2\2\2mn\3\2\2\2n\13\3\2\2\2om\3\2\2\2pq\b\7\1\2qr\5")
buf.write(u"\20\t\2rx\3\2\2\2st\f\4\2\2tu\t\4\2\2uw\5\f\7\5vs\3\2")
buf.write(u"\2\2wz\3\2\2\2xv\3\2\2\2xy\3\2\2\2y\r\3\2\2\2zx\3\2\2")
buf.write(u"\2{|\b\b\1\2|}\5\22\n\2}\u0083\3\2\2\2~\177\f\4\2\2\177")
buf.write(u"\u0080\t\4\2\2\u0080\u0082\5\16\b\5\u0081~\3\2\2\2\u0082")
buf.write(u"\u0085\3\2\2\2\u0083\u0081\3\2\2\2\u0083\u0084\3\2\2")
buf.write(u"\2\u0084\17\3\2\2\2\u0085\u0083\3\2\2\2\u0086\u0087\t")
buf.write(u"\3\2\2\u0087\u008e\5\20\t\2\u0088\u008a\5\24\13\2\u0089")
buf.write(u"\u0088\3\2\2\2\u008a\u008b\3\2\2\2\u008b\u0089\3\2\2")
buf.write(u"\2\u008b\u008c\3\2\2\2\u008c\u008e\3\2\2\2\u008d\u0086")
buf.write(u"\3\2\2\2\u008d\u0089\3\2\2\2\u008e\21\3\2\2\2\u008f\u0090")
buf.write(u"\t\3\2\2\u0090\u0099\5\22\n\2\u0091\u0095\5\24\13\2\u0092")
buf.write(u"\u0094\5\26\f\2\u0093\u0092\3\2\2\2\u0094\u0097\3\2\2")
buf.write(u"\2\u0095\u0093\3\2\2\2\u0095\u0096\3\2\2\2\u0096\u0099")
buf.write(u"\3\2\2\2\u0097\u0095\3\2\2\2\u0098\u008f\3\2\2\2\u0098")
buf.write(u"\u0091\3\2\2\2\u0099\23\3\2\2\2\u009a\u009e\5 \21\2\u009b")
buf.write(u"\u009d\5\30\r\2\u009c\u009b\3\2\2\2\u009d\u00a0\3\2\2")
buf.write(u"\2\u009e\u009c\3\2\2\2\u009e\u009f\3\2\2\2\u009f\25\3")
buf.write(u"\2\2\2\u00a0\u009e\3\2\2\2\u00a1\u00a5\5\"\22\2\u00a2")
buf.write(u"\u00a4\5\30\r\2\u00a3\u00a2\3\2\2\2\u00a4\u00a7\3\2\2")
buf.write(u"\2\u00a5\u00a3\3\2\2\2\u00a5\u00a6\3\2\2\2\u00a6\27\3")
buf.write(u"\2\2\2\u00a7\u00a5\3\2\2\2\u00a8\u00ab\7Y\2\2\u00a9\u00ab")
buf.write(u"\5\32\16\2\u00aa\u00a8\3\2\2\2\u00aa\u00a9\3\2\2\2\u00ab")
buf.write(u"\31\3\2\2\2\u00ac\u00b2\7\34\2\2\u00ad\u00b3\5\36\20")
buf.write(u"\2\u00ae\u00b3\5\34\17\2\u00af\u00b0\5\36\20\2\u00b0")
buf.write(u"\u00b1\5\34\17\2\u00b1\u00b3\3\2\2\2\u00b2\u00ad\3\2")
buf.write(u"\2\2\u00b2\u00ae\3\2\2\2\u00b2\u00af\3\2\2\2\u00b3\33")
buf.write(u"\3\2\2\2\u00b4\u00b5\7I\2\2\u00b5\u00b8\7\26\2\2\u00b6")
buf.write(u"\u00b9\5\b\5\2\u00b7\u00b9\5\6\4\2\u00b8\u00b6\3\2\2")
buf.write(u"\2\u00b8\u00b7\3\2\2\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb")
buf.write(u"\7\27\2\2\u00bb\35\3\2\2\2\u00bc\u00bd\7J\2\2\u00bd\u00c0")
buf.write(u"\7\26\2\2\u00be\u00c1\5\b\5\2\u00bf\u00c1\5\6\4\2\u00c0")
buf.write(u"\u00be\3\2\2\2\u00c0\u00bf\3\2\2\2\u00c1\u00c2\3\2\2")
buf.write(u"\2\u00c2\u00c3\7\27\2\2\u00c3\37\3\2\2\2\u00c4\u00c5")
buf.write(u"\b\21\1\2\u00c5\u00c6\5$\23\2\u00c6\u00d5\3\2\2\2\u00c7")
buf.write(u"\u00c8\f\4\2\2\u00c8\u00ce\7J\2\2\u00c9\u00cf\5,\27\2")
buf.write(u"\u00ca\u00cb\7\26\2\2\u00cb\u00cc\5\b\5\2\u00cc\u00cd")
buf.write(u"\7\27\2\2\u00cd\u00cf\3\2\2\2\u00ce\u00c9\3\2\2\2\u00ce")
buf.write(u"\u00ca\3\2\2\2\u00cf\u00d1\3\2\2\2\u00d0\u00d2\5J&\2")
buf.write(u"\u00d1\u00d0\3\2\2\2\u00d1\u00d2\3\2\2\2\u00d2\u00d4")
buf.write(u"\3\2\2\2\u00d3\u00c7\3\2\2\2\u00d4\u00d7\3\2\2\2\u00d5")
buf.write(u"\u00d3\3\2\2\2\u00d5\u00d6\3\2\2\2\u00d6!\3\2\2\2\u00d7")
buf.write(u"\u00d5\3\2\2\2\u00d8\u00d9\b\22\1\2\u00d9\u00da\5&\24")
buf.write(u"\2\u00da\u00e9\3\2\2\2\u00db\u00dc\f\4\2\2\u00dc\u00e2")
buf.write(u"\7J\2\2\u00dd\u00e3\5,\27\2\u00de\u00df\7\26\2\2\u00df")
buf.write(u"\u00e0\5\b\5\2\u00e0\u00e1\7\27\2\2\u00e1\u00e3\3\2\2")
buf.write(u"\2\u00e2\u00dd\3\2\2\2\u00e2\u00de\3\2\2\2\u00e3\u00e5")
buf.write(u"\3\2\2\2\u00e4\u00e6\5J&\2\u00e5\u00e4\3\2\2\2\u00e5")
buf.write(u"\u00e6\3\2\2\2\u00e6\u00e8\3\2\2\2\u00e7\u00db\3\2\2")
buf.write(u"\2\u00e8\u00eb\3\2\2\2\u00e9\u00e7\3\2\2\2\u00e9\u00ea")
buf.write(u"\3\2\2\2\u00ea#\3\2\2\2\u00eb\u00e9\3\2\2\2\u00ec\u00f5")
buf.write(u"\5(\25\2\u00ed\u00f5\5*\26\2\u00ee\u00f5\5@!\2\u00ef")
buf.write(u"\u00f5\5,\27\2\u00f0\u00f5\5\66\34\2\u00f1\u00f5\58\35")
buf.write(u"\2\u00f2\u00f5\5:\36\2\u00f3\u00f5\5<\37\2\u00f4\u00ec")
buf.write(u"\3\2\2\2\u00f4\u00ed\3\2\2\2\u00f4\u00ee\3\2\2\2\u00f4")
buf.write(u"\u00ef\3\2\2\2\u00f4\u00f0\3\2\2\2\u00f4\u00f1\3\2\2")
buf.write(u"\2\u00f4\u00f2\3\2\2\2\u00f4\u00f3\3\2\2\2\u00f5%\3\2")
buf.write(u"\2\2\u00f6\u00fe\5(\25\2\u00f7\u00fe\5*\26\2\u00f8\u00fe")
buf.write(u"\5,\27\2\u00f9\u00fe\5\66\34\2\u00fa\u00fe\58\35\2\u00fb")
buf.write(u"\u00fe\5:\36\2\u00fc\u00fe\5<\37\2\u00fd\u00f6\3\2\2")
buf.write(u"\2\u00fd\u00f7\3\2\2\2\u00fd\u00f8\3\2\2\2\u00fd\u00f9")
buf.write(u"\3\2\2\2\u00fd\u00fa\3\2\2\2\u00fd\u00fb\3\2\2\2\u00fd")
buf.write(u"\u00fc\3\2\2\2\u00fe\'\3\2\2\2\u00ff\u0100\7\24\2\2\u0100")
buf.write(u"\u0101\5\b\5\2\u0101\u0102\7\25\2\2\u0102\u0110\3\2\2")
buf.write(u"\2\u0103\u0104\7\32\2\2\u0104\u0105\5\b\5\2\u0105\u0106")
buf.write(u"\7\33\2\2\u0106\u0110\3\2\2\2\u0107\u0108\7\26\2\2\u0108")
buf.write(u"\u0109\5\b\5\2\u0109\u010a\7\27\2\2\u010a\u0110\3\2\2")
buf.write(u"\2\u010b\u010c\7\30\2\2\u010c\u010d\5\b\5\2\u010d\u010e")
buf.write(u"\7\31\2\2\u010e\u0110\3\2\2\2\u010f\u00ff\3\2\2\2\u010f")
buf.write(u"\u0103\3\2\2\2\u010f\u0107\3\2\2\2\u010f\u010b\3\2\2")
buf.write(u"\2\u0110)\3\2\2\2\u0111\u0112\7\34\2\2\u0112\u0113\5")
buf.write(u"\b\5\2\u0113\u0114\7\34\2\2\u0114+\3\2\2\2\u0115\u0117")
buf.write(u"\t\5\2\2\u0116\u0118\5J&\2\u0117\u0116\3\2\2\2\u0117")
buf.write(u"\u0118\3\2\2\2\u0118\u011f\3\2\2\2\u0119\u011f\7N\2\2")
buf.write(u"\u011a\u011f\7L\2\2\u011b\u011f\5\62\32\2\u011c\u011f")
buf.write(u"\5.\30\2\u011d\u011f\5\60\31\2\u011e\u0115\3\2\2\2\u011e")
buf.write(u"\u0119\3\2\2\2\u011e\u011a\3\2\2\2\u011e\u011b\3\2\2")
buf.write(u"\2\u011e\u011c\3\2\2\2\u011e\u011d\3\2\2\2\u011f-\3\2")
buf.write(u"\2\2\u0120\u0121\7\37\2\2\u0121\u0122\5\b\5\2\u0122\u0123")
buf.write(u"\t\6\2\2\u0123/\3\2\2\2\u0124\u0125\t\7\2\2\u0125\u0126")
buf.write(u"\5\b\5\2\u0126\u0127\7 \2\2\u0127\61\3\2\2\2\u0128\u0129")
buf.write(u"\7H\2\2\u0129\u012a\7\26\2\2\u012a\u012b\5\64\33\2\u012b")
buf.write(u"\u012c\7\27\2\2\u012c\63\3\2\2\2\u012d\u012f\7M\2\2\u012e")
buf.write(u"\u012d\3\2\2\2\u012f\u0132\3\2\2\2\u0130\u012e\3\2\2")
buf.write(u"\2\u0130\u0131\3\2\2\2\u0131\65\3\2\2\2\u0132\u0130\3")
buf.write(u"\2\2\2\u0133\u0134\7D\2\2\u0134\u0135\7\26\2\2\u0135")
buf.write(u"\u0136\5\b\5\2\u0136\u0137\7\27\2\2\u0137\u0138\7\26")
buf.write(u"\2\2\u0138\u0139\5\b\5\2\u0139\u013a\7\27\2\2\u013a\67")
buf.write(u"\3\2\2\2\u013b\u013c\t\b\2\2\u013c\u013d\7\26\2\2\u013d")
buf.write(u"\u013e\5\b\5\2\u013e\u013f\7\27\2\2\u013f\u0140\7\26")
buf.write(u"\2\2\u0140\u0141\5\b\5\2\u0141\u0142\7\27\2\2\u01429")
buf.write(u"\3\2\2\2\u0143\u0144\7;\2\2\u0144\u0145\5\b\5\2\u0145")
buf.write(u"\u0146\7<\2\2\u0146;\3\2\2\2\u0147\u0148\7=\2\2\u0148")
buf.write(u"\u0149\5\b\5\2\u0149\u014a\7>\2\2\u014a=\3\2\2\2\u014b")
buf.write(u"\u014c\t\t\2\2\u014c?\3\2\2\2\u014d\u015a\5> \2\u014e")
buf.write(u"\u0150\5J&\2\u014f\u014e\3\2\2\2\u014f\u0150\3\2\2\2")
buf.write(u"\u0150\u0152\3\2\2\2\u0151\u0153\5L\'\2\u0152\u0151\3")
buf.write(u"\2\2\2\u0152\u0153\3\2\2\2\u0153\u015b\3\2\2\2\u0154")
buf.write(u"\u0156\5L\'\2\u0155\u0154\3\2\2\2\u0155\u0156\3\2\2\2")
buf.write(u"\u0156\u0158\3\2\2\2\u0157\u0159\5J&\2\u0158\u0157\3")
buf.write(u"\2\2\2\u0158\u0159\3\2\2\2\u0159\u015b\3\2\2\2\u015a")
buf.write(u"\u014f\3\2\2\2\u015a\u0155\3\2\2\2\u015b\u0161\3\2\2")
buf.write(u"\2\u015c\u015d\7\24\2\2\u015d\u015e\5F$\2\u015e\u015f")
buf.write(u"\7\25\2\2\u015f\u0162\3\2\2\2\u0160\u0162\5H%\2\u0161")
buf.write(u"\u015c\3\2\2\2\u0161\u0160\3\2\2\2\u0162\u019c\3\2\2")
buf.write(u"\2\u0163\u0165\t\5\2\2\u0164\u0166\5J&\2\u0165\u0164")
buf.write(u"\3\2\2\2\u0165\u0166\3\2\2\2\u0166\u0167\3\2\2\2\u0167")
buf.write(u"\u0168\7\24\2\2\u0168\u0169\5B\"\2\u0169\u016a\7\25\2")
buf.write(u"\2\u016a\u019c\3\2\2\2\u016b\u0172\7#\2\2\u016c\u016d")
buf.write(u"\5J&\2\u016d\u016e\5L\'\2\u016e\u0173\3\2\2\2\u016f\u0170")
buf.write(u"\5L\'\2\u0170\u0171\5J&\2\u0171\u0173\3\2\2\2\u0172\u016c")
buf.write(u"\3\2\2\2\u0172\u016f\3\2\2\2\u0172\u0173\3\2\2\2\u0173")
buf.write(u"\u017a\3\2\2\2\u0174\u0176\5\n\6\2\u0175\u0174\3\2\2")
buf.write(u"\2\u0175\u0176\3\2\2\2\u0176\u0177\3\2\2\2\u0177\u017b")
buf.write(u"\7L\2\2\u0178\u017b\5\66\34\2\u0179\u017b\5\n\6\2\u017a")
buf.write(u"\u0175\3\2\2\2\u017a\u0178\3\2\2\2\u017a\u0179\3\2\2")
buf.write(u"\2\u017b\u019c\3\2\2\2\u017c\u0181\7?\2\2\u017d\u017e")
buf.write(u"\7\32\2\2\u017e\u017f\5\b\5\2\u017f\u0180\7\33\2\2\u0180")
buf.write(u"\u0182\3\2\2\2\u0181\u017d\3\2\2\2\u0181\u0182\3\2\2")
buf.write(u"\2\u0182\u0183\3\2\2\2\u0183\u0184\7\26\2\2\u0184\u0185")
buf.write(u"\5\b\5\2\u0185\u0186\7\27\2\2\u0186\u019c\3\2\2\2\u0187")
buf.write(u"\u0188\7@\2\2\u0188\u0189\7\26\2\2\u0189\u018a\5\b\5")
buf.write(u"\2\u018a\u018b\7\27\2\2\u018b\u019c\3\2\2\2\u018c\u0193")
buf.write(u"\t\n\2\2\u018d\u018e\5N(\2\u018e\u018f\5L\'\2\u018f\u0194")
buf.write(u"\3\2\2\2\u0190\u0191\5L\'\2\u0191\u0192\5N(\2\u0192\u0194")
buf.write(u"\3\2\2\2\u0193\u018d\3\2\2\2\u0193\u0190\3\2\2\2\u0194")
buf.write(u"\u0195\3\2\2\2\u0195\u0196\5\f\7\2\u0196\u019c\3\2\2")
buf.write(u"\2\u0197\u0198\7!\2\2\u0198\u0199\5D#\2\u0199\u019a\5")
buf.write(u"\f\7\2\u019a\u019c\3\2\2\2\u019b\u014d\3\2\2\2\u019b")
buf.write(u"\u0163\3\2\2\2\u019b\u016b\3\2\2\2\u019b\u017c\3\2\2")
buf.write(u"\2\u019b\u0187\3\2\2\2\u019b\u018c\3\2\2\2\u019b\u0197")
buf.write(u"\3\2\2\2\u019cA\3\2\2\2\u019d\u019e\5\b\5\2\u019e\u019f")
buf.write(u"\7\3\2\2\u019f\u01a0\5B\"\2\u01a0\u01a3\3\2\2\2\u01a1")
buf.write(u"\u01a3\5\b\5\2\u01a2\u019d\3\2\2\2\u01a2\u01a1\3\2\2")
buf.write(u"\2\u01a3C\3\2\2\2\u01a4\u01a5\7I\2\2\u01a5\u01a6\7\26")
buf.write(u"\2\2\u01a6\u01a7\t\5\2\2\u01a7\u01a8\7\"\2\2\u01a8\u01ad")
buf.write(u"\5\b\5\2\u01a9\u01aa\7J\2\2\u01aa\u01ab\7\26\2\2\u01ab")
buf.write(u"\u01ac\t\3\2\2\u01ac\u01ae\7\27\2\2\u01ad\u01a9\3\2\2")
buf.write(u"\2\u01ad\u01ae\3\2\2\2\u01ae\u01af\3\2\2\2\u01af\u01b0")
buf.write(u"\7\27\2\2\u01b0E\3\2\2\2\u01b1\u01b7\5\b\5\2\u01b2\u01b3")
buf.write(u"\5\b\5\2\u01b3\u01b4\7\3\2\2\u01b4\u01b5\5F$\2\u01b5")
buf.write(u"\u01b7\3\2\2\2\u01b6\u01b1\3\2\2\2\u01b6\u01b2\3\2\2")
buf.write(u"\2\u01b7G\3\2\2\2\u01b8\u01b9\5\16\b\2\u01b9I\3\2\2\2")
buf.write(u"\u01ba\u01c0\7I\2\2\u01bb\u01c1\5,\27\2\u01bc\u01bd\7")
buf.write(u"\26\2\2\u01bd\u01be\5\b\5\2\u01be\u01bf\7\27\2\2\u01bf")
buf.write(u"\u01c1\3\2\2\2\u01c0\u01bb\3\2\2\2\u01c0\u01bc\3\2\2")
buf.write(u"\2\u01c1K\3\2\2\2\u01c2\u01c8\7J\2\2\u01c3\u01c9\5,\27")
buf.write(u"\2\u01c4\u01c5\7\26\2\2\u01c5\u01c6\5\b\5\2\u01c6\u01c7")
buf.write(u"\7\27\2\2\u01c7\u01c9\3\2\2\2\u01c8\u01c3\3\2\2\2\u01c8")
buf.write(u"\u01c4\3\2\2\2\u01c9M\3\2\2\2\u01ca\u01cb\7I\2\2\u01cb")
buf.write(u"\u01cc\7\26\2\2\u01cc\u01cd\5\6\4\2\u01cd\u01ce\7\27")
buf.write(u"\2\2\u01ceO\3\2\2\2\u01cf\u01d0\7I\2\2\u01d0\u01d1\7")
buf.write(u"\26\2\2\u01d1\u01d2\5\6\4\2\u01d2\u01d3\7\27\2\2\u01d3")
buf.write(u"Q\3\2\2\2.\\mx\u0083\u008b\u008d\u0095\u0098\u009e\u00a5")
buf.write(u"\u00aa\u00b2\u00b8\u00c0\u00ce\u00d1\u00d5\u00e2\u00e5")
buf.write(u"\u00e9\u00f4\u00fd\u010f\u0117\u011e\u0130\u014f\u0152")
buf.write(u"\u0155\u0158\u015a\u0161\u0165\u0172\u0175\u017a\u0181")
buf.write(u"\u0193\u019b\u01a2\u01ad\u01b6\u01c0\u01c8")
return buf.getvalue()
class LaTeXParser ( Parser ):
grammarFileName = "LaTeX.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ u"<INVALID>", u"','", u"<INVALID>", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"'\\quad'", u"'\\qquad'", u"<INVALID>",
u"'\\negmedspace'", u"'\\negthickspace'", u"'\\left'",
u"'\\right'", u"<INVALID>", u"'+'", u"'-'", u"'*'",
u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'",
u"'['", u"']'", u"'|'", u"'\\right|'", u"'\\left|'",
u"'\\langle'", u"'\\rangle'", u"'\\lim'", u"<INVALID>",
u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'",
u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'",
u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'",
u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'",
u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'",
u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'", u"'\\rfloor'",
u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\overline'",
u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'",
u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'",
u"'_'", u"'^'", u"':'", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"<INVALID>", u"'\\neq'", u"'<'", u"<INVALID>",
u"'\\leqq'", u"'\\leqslant'", u"'>'", u"<INVALID>",
u"'\\geqq'", u"'\\geqslant'", u"'!'" ]
symbolicNames = [ u"<INVALID>", u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE",
u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE",
u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT",
u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN",
u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL",
u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR",
u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM",
u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD",
u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN",
u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC",
u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN",
u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH",
u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH",
u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL",
u"R_CEIL", u"FUNC_SQRT", u"FUNC_OVERLINE", u"CMD_TIMES",
u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM",
u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE",
u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER",
u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S",
u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ]
RULE_math = 0
RULE_relation = 1
RULE_equality = 2
RULE_expr = 3
RULE_additive = 4
RULE_mp = 5
RULE_mp_nofunc = 6
RULE_unary = 7
RULE_unary_nofunc = 8
RULE_postfix = 9
RULE_postfix_nofunc = 10
RULE_postfix_op = 11
RULE_eval_at = 12
RULE_eval_at_sub = 13
RULE_eval_at_sup = 14
RULE_exp = 15
RULE_exp_nofunc = 16
RULE_comp = 17
RULE_comp_nofunc = 18
RULE_group = 19
RULE_abs_group = 20
RULE_atom = 21
RULE_bra = 22
RULE_ket = 23
RULE_mathit = 24
RULE_mathit_text = 25
RULE_frac = 26
RULE_binom = 27
RULE_floor = 28
RULE_ceil = 29
RULE_func_normal = 30
RULE_func = 31
RULE_args = 32
RULE_limit_sub = 33
RULE_func_arg = 34
RULE_func_arg_noparens = 35
RULE_subexpr = 36
RULE_supexpr = 37
RULE_subeq = 38
RULE_supeq = 39
ruleNames = [ u"math", u"relation", u"equality", u"expr", u"additive",
u"mp", u"mp_nofunc", u"unary", u"unary_nofunc", u"postfix",
u"postfix_nofunc", u"postfix_op", u"eval_at", u"eval_at_sub",
u"eval_at_sup", u"exp", u"exp_nofunc", u"comp", u"comp_nofunc",
u"group", u"abs_group", u"atom", u"bra", u"ket", u"mathit",
u"mathit_text", u"frac", u"binom", u"floor", u"ceil",
u"func_normal", u"func", u"args", u"limit_sub", u"func_arg",
u"func_arg_noparens", u"subexpr", u"supexpr", u"subeq",
u"supeq" ]
EOF = Token.EOF
T__0=1
WS=2
THINSPACE=3
MEDSPACE=4
THICKSPACE=5
QUAD=6
QQUAD=7
NEGTHINSPACE=8
NEGMEDSPACE=9
NEGTHICKSPACE=10
CMD_LEFT=11
CMD_RIGHT=12
IGNORE=13
ADD=14
SUB=15
MUL=16
DIV=17
L_PAREN=18
R_PAREN=19
L_BRACE=20
R_BRACE=21
L_BRACE_LITERAL=22
R_BRACE_LITERAL=23
L_BRACKET=24
R_BRACKET=25
BAR=26
R_BAR=27
L_BAR=28
L_ANGLE=29
R_ANGLE=30
FUNC_LIM=31
LIM_APPROACH_SYM=32
FUNC_INT=33
FUNC_SUM=34
FUNC_PROD=35
FUNC_EXP=36
FUNC_LOG=37
FUNC_LN=38
FUNC_SIN=39
FUNC_COS=40
FUNC_TAN=41
FUNC_CSC=42
FUNC_SEC=43
FUNC_COT=44
FUNC_ARCSIN=45
FUNC_ARCCOS=46
FUNC_ARCTAN=47
FUNC_ARCCSC=48
FUNC_ARCSEC=49
FUNC_ARCCOT=50
FUNC_SINH=51
FUNC_COSH=52
FUNC_TANH=53
FUNC_ARSINH=54
FUNC_ARCOSH=55
FUNC_ARTANH=56
L_FLOOR=57
R_FLOOR=58
L_CEIL=59
R_CEIL=60
FUNC_SQRT=61
FUNC_OVERLINE=62
CMD_TIMES=63
CMD_CDOT=64
CMD_DIV=65
CMD_FRAC=66
CMD_BINOM=67
CMD_DBINOM=68
CMD_TBINOM=69
CMD_MATHIT=70
UNDERSCORE=71
CARET=72
COLON=73
DIFFERENTIAL=74
LETTER=75
NUMBER=76
EQUAL=77
NEQ=78
LT=79
LTE=80
LTE_Q=81
LTE_S=82
GT=83
GTE=84
GTE_Q=85
GTE_S=86
BANG=87
SYMBOL=88
def __init__(self, input, output=sys.stdout):
super(LaTeXParser, self).__init__(input, output=output)
self.checkVersion("4.7.2")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class MathContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.MathContext, self).__init__(parent, invokingState)
self.parser = parser
def relation(self):
return self.getTypedRuleContext(LaTeXParser.RelationContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_math
def math(self):
localctx = LaTeXParser.MathContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_math)
try:
self.enterOuterAlt(localctx, 1)
self.state = 80
self.relation(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class RelationContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.RelationContext, self).__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def relation(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.RelationContext)
else:
return self.getTypedRuleContext(LaTeXParser.RelationContext,i)
def EQUAL(self):
return self.getToken(LaTeXParser.EQUAL, 0)
def LT(self):
return self.getToken(LaTeXParser.LT, 0)
def LTE(self):
return self.getToken(LaTeXParser.LTE, 0)
def GT(self):
return self.getToken(LaTeXParser.GT, 0)
def GTE(self):
return self.getToken(LaTeXParser.GTE, 0)
def NEQ(self):
return self.getToken(LaTeXParser.NEQ, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_relation
def relation(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 2
self.enterRecursionRule(localctx, 2, self.RULE_relation, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 83
self.expr()
self._ctx.stop = self._input.LT(-1)
self.state = 90
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_relation)
self.state = 85
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 86
_la = self._input.LA(1)
if not(((((_la - 77)) & ~0x3f) == 0 and ((1 << (_la - 77)) & ((1 << (LaTeXParser.EQUAL - 77)) | (1 << (LaTeXParser.NEQ - 77)) | (1 << (LaTeXParser.LT - 77)) | (1 << (LaTeXParser.LTE - 77)) | (1 << (LaTeXParser.GT - 77)) | (1 << (LaTeXParser.GTE - 77)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 87
self.relation(3)
self.state = 92
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class EqualityContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.EqualityContext, self).__init__(parent, invokingState)
self.parser = parser
def expr(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def EQUAL(self):
return self.getToken(LaTeXParser.EQUAL, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_equality
def equality(self):
localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_equality)
try:
self.enterOuterAlt(localctx, 1)
self.state = 93
self.expr()
self.state = 94
self.match(LaTeXParser.EQUAL)
self.state = 95
self.expr()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExprContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.ExprContext, self).__init__(parent, invokingState)
self.parser = parser
def additive(self):
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_expr
def expr(self):
localctx = LaTeXParser.ExprContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_expr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 97
self.additive(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AdditiveContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.AdditiveContext, self).__init__(parent, invokingState)
self.parser = parser
def mp(self):
return self.getTypedRuleContext(LaTeXParser.MpContext,0)
def additive(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.AdditiveContext)
else:
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_additive
def additive(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 8
self.enterRecursionRule(localctx, 8, self.RULE_additive, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 100
self.mp(0)
self._ctx.stop = self._input.LT(-1)
self.state = 107
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,1,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_additive)
self.state = 102
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 103
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 104
self.additive(3)
self.state = 109
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,1,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class MpContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.MpContext, self).__init__(parent, invokingState)
self.parser = parser
def unary(self):
return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
def mp(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.MpContext)
else:
return self.getTypedRuleContext(LaTeXParser.MpContext,i)
def MUL(self):
return self.getToken(LaTeXParser.MUL, 0)
def CMD_TIMES(self):
return self.getToken(LaTeXParser.CMD_TIMES, 0)
def CMD_CDOT(self):
return self.getToken(LaTeXParser.CMD_CDOT, 0)
def DIV(self):
return self.getToken(LaTeXParser.DIV, 0)
def CMD_DIV(self):
return self.getToken(LaTeXParser.CMD_DIV, 0)
def COLON(self):
return self.getToken(LaTeXParser.COLON, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mp
def mp(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.MpContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 10
self.enterRecursionRule(localctx, 10, self.RULE_mp, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 111
self.unary()
self._ctx.stop = self._input.LT(-1)
self.state = 118
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.MpContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_mp)
self.state = 113
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 114
_la = self._input.LA(1)
if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 115
self.mp(3)
self.state = 120
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Mp_nofuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Mp_nofuncContext, self).__init__(parent, invokingState)
self.parser = parser
def unary_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
def mp_nofunc(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext)
else:
return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i)
def MUL(self):
return self.getToken(LaTeXParser.MUL, 0)
def CMD_TIMES(self):
return self.getToken(LaTeXParser.CMD_TIMES, 0)
def CMD_CDOT(self):
return self.getToken(LaTeXParser.CMD_CDOT, 0)
def DIV(self):
return self.getToken(LaTeXParser.DIV, 0)
def CMD_DIV(self):
return self.getToken(LaTeXParser.CMD_DIV, 0)
def COLON(self):
return self.getToken(LaTeXParser.COLON, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mp_nofunc
def mp_nofunc(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 12
self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 122
self.unary_nofunc()
self._ctx.stop = self._input.LT(-1)
self.state = 129
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,3,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc)
self.state = 124
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 125
_la = self._input.LA(1)
if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 126
self.mp_nofunc(3)
self.state = 131
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,3,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class UnaryContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.UnaryContext, self).__init__(parent, invokingState)
self.parser = parser
def unary(self):
return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def postfix(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.PostfixContext)
else:
return self.getTypedRuleContext(LaTeXParser.PostfixContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_unary
def unary(self):
localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_unary)
self._la = 0 # Token type
try:
self.state = 139
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.ADD, LaTeXParser.SUB]:
self.enterOuterAlt(localctx, 1)
self.state = 132
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 133
self.unary()
pass
elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 135
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 134
self.postfix()
else:
raise NoViableAltException(self)
self.state = 137
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,4,self._ctx)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Unary_nofuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Unary_nofuncContext, self).__init__(parent, invokingState)
self.parser = parser
def unary_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def postfix(self):
return self.getTypedRuleContext(LaTeXParser.PostfixContext,0)
def postfix_nofunc(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_unary_nofunc
def unary_nofunc(self):
localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_unary_nofunc)
self._la = 0 # Token type
try:
self.state = 150
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.ADD, LaTeXParser.SUB]:
self.enterOuterAlt(localctx, 1)
self.state = 141
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 142
self.unary_nofunc()
pass
elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 143
self.postfix()
self.state = 147
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 144
self.postfix_nofunc()
self.state = 149
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class PostfixContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.PostfixContext, self).__init__(parent, invokingState)
self.parser = parser
def exp(self):
return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
def postfix_op(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix
def postfix(self):
localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_postfix)
try:
self.enterOuterAlt(localctx, 1)
self.state = 152
self.exp(0)
self.state = 156
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 153
self.postfix_op()
self.state = 158
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Postfix_nofuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Postfix_nofuncContext, self).__init__(parent, invokingState)
self.parser = parser
def exp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
def postfix_op(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix_nofunc
def postfix_nofunc(self):
localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_postfix_nofunc)
try:
self.enterOuterAlt(localctx, 1)
self.state = 159
self.exp_nofunc(0)
self.state = 163
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,9,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 160
self.postfix_op()
self.state = 165
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,9,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Postfix_opContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Postfix_opContext, self).__init__(parent, invokingState)
self.parser = parser
def BANG(self):
return self.getToken(LaTeXParser.BANG, 0)
def eval_at(self):
return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix_op
def postfix_op(self):
localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_postfix_op)
try:
self.state = 168
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BANG]:
self.enterOuterAlt(localctx, 1)
self.state = 166
self.match(LaTeXParser.BANG)
pass
elif token in [LaTeXParser.BAR]:
self.enterOuterAlt(localctx, 2)
self.state = 167
self.eval_at()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_atContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Eval_atContext, self).__init__(parent, invokingState)
self.parser = parser
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def eval_at_sup(self):
return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0)
def eval_at_sub(self):
return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at
def eval_at(self):
localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_eval_at)
try:
self.enterOuterAlt(localctx, 1)
self.state = 170
self.match(LaTeXParser.BAR)
self.state = 176
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,11,self._ctx)
if la_ == 1:
self.state = 171
self.eval_at_sup()
pass
elif la_ == 2:
self.state = 172
self.eval_at_sub()
pass
elif la_ == 3:
self.state = 173
self.eval_at_sup()
self.state = 174
self.eval_at_sub()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_at_subContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Eval_at_subContext, self).__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at_sub
def eval_at_sub(self):
localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_eval_at_sub)
try:
self.enterOuterAlt(localctx, 1)
self.state = 178
self.match(LaTeXParser.UNDERSCORE)
self.state = 179
self.match(LaTeXParser.L_BRACE)
self.state = 182
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,12,self._ctx)
if la_ == 1:
self.state = 180
self.expr()
pass
elif la_ == 2:
self.state = 181
self.equality()
pass
self.state = 184
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_at_supContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Eval_at_supContext, self).__init__(parent, invokingState)
self.parser = parser
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at_sup
def eval_at_sup(self):
localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_eval_at_sup)
try:
self.enterOuterAlt(localctx, 1)
self.state = 186
self.match(LaTeXParser.CARET)
self.state = 187
self.match(LaTeXParser.L_BRACE)
self.state = 190
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,13,self._ctx)
if la_ == 1:
self.state = 188
self.expr()
pass
elif la_ == 2:
self.state = 189
self.equality()
pass
self.state = 192
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExpContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.ExpContext, self).__init__(parent, invokingState)
self.parser = parser
def comp(self):
return self.getTypedRuleContext(LaTeXParser.CompContext,0)
def exp(self):
return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_exp
def exp(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 30
self.enterRecursionRule(localctx, 30, self.RULE_exp, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 195
self.comp()
self._ctx.stop = self._input.LT(-1)
self.state = 211
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,16,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp)
self.state = 197
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 198
self.match(LaTeXParser.CARET)
self.state = 204
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.state = 199
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 200
self.match(LaTeXParser.L_BRACE)
self.state = 201
self.expr()
self.state = 202
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
self.state = 207
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
if la_ == 1:
self.state = 206
self.subexpr()
self.state = 213
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,16,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Exp_nofuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Exp_nofuncContext, self).__init__(parent, invokingState)
self.parser = parser
def comp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0)
def exp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_exp_nofunc
def exp_nofunc(self, _p=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 32
self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 215
self.comp_nofunc()
self._ctx.stop = self._input.LT(-1)
self.state = 231
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,19,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc)
self.state = 217
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 218
self.match(LaTeXParser.CARET)
self.state = 224
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.state = 219
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 220
self.match(LaTeXParser.L_BRACE)
self.state = 221
self.expr()
self.state = 222
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
self.state = 227
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,18,self._ctx)
if la_ == 1:
self.state = 226
self.subexpr()
self.state = 233
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,19,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class CompContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.CompContext, self).__init__(parent, invokingState)
self.parser = parser
def group(self):
return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
def abs_group(self):
return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
def func(self):
return self.getTypedRuleContext(LaTeXParser.FuncContext,0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def frac(self):
return self.getTypedRuleContext(LaTeXParser.FracContext,0)
def binom(self):
return self.getTypedRuleContext(LaTeXParser.BinomContext,0)
def floor(self):
return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
def ceil(self):
return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_comp
def comp(self):
localctx = LaTeXParser.CompContext(self, self._ctx, self.state)
self.enterRule(localctx, 34, self.RULE_comp)
try:
self.state = 242
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,20,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 234
self.group()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 235
self.abs_group()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 236
self.func()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 237
self.atom()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 238
self.frac()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 239
self.binom()
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 240
self.floor()
pass
elif la_ == 8:
self.enterOuterAlt(localctx, 8)
self.state = 241
self.ceil()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Comp_nofuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Comp_nofuncContext, self).__init__(parent, invokingState)
self.parser = parser
def group(self):
return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
def abs_group(self):
return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def frac(self):
return self.getTypedRuleContext(LaTeXParser.FracContext,0)
def binom(self):
return self.getTypedRuleContext(LaTeXParser.BinomContext,0)
def floor(self):
return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
def ceil(self):
return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_comp_nofunc
def comp_nofunc(self):
localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 36, self.RULE_comp_nofunc)
try:
self.state = 251
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,21,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 244
self.group()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 245
self.abs_group()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 246
self.atom()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 247
self.frac()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 248
self.binom()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 249
self.floor()
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 250
self.ceil()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class GroupContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.GroupContext, self).__init__(parent, invokingState)
self.parser = parser
def L_PAREN(self):
return self.getToken(LaTeXParser.L_PAREN, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_PAREN(self):
return self.getToken(LaTeXParser.R_PAREN, 0)
def L_BRACKET(self):
return self.getToken(LaTeXParser.L_BRACKET, 0)
def R_BRACKET(self):
return self.getToken(LaTeXParser.R_BRACKET, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def L_BRACE_LITERAL(self):
return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0)
def R_BRACE_LITERAL(self):
return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_group
def group(self):
localctx = LaTeXParser.GroupContext(self, self._ctx, self.state)
self.enterRule(localctx, 38, self.RULE_group)
try:
self.state = 269
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.L_PAREN]:
self.enterOuterAlt(localctx, 1)
self.state = 253
self.match(LaTeXParser.L_PAREN)
self.state = 254
self.expr()
self.state = 255
self.match(LaTeXParser.R_PAREN)
pass
elif token in [LaTeXParser.L_BRACKET]:
self.enterOuterAlt(localctx, 2)
self.state = 257
self.match(LaTeXParser.L_BRACKET)
self.state = 258
self.expr()
self.state = 259
self.match(LaTeXParser.R_BRACKET)
pass
elif token in [LaTeXParser.L_BRACE]:
self.enterOuterAlt(localctx, 3)
self.state = 261
self.match(LaTeXParser.L_BRACE)
self.state = 262
self.expr()
self.state = 263
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.L_BRACE_LITERAL]:
self.enterOuterAlt(localctx, 4)
self.state = 265
self.match(LaTeXParser.L_BRACE_LITERAL)
self.state = 266
self.expr()
self.state = 267
self.match(LaTeXParser.R_BRACE_LITERAL)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Abs_groupContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Abs_groupContext, self).__init__(parent, invokingState)
self.parser = parser
def BAR(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.BAR)
else:
return self.getToken(LaTeXParser.BAR, i)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_abs_group
def abs_group(self):
localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state)
self.enterRule(localctx, 40, self.RULE_abs_group)
try:
self.enterOuterAlt(localctx, 1)
self.state = 271
self.match(LaTeXParser.BAR)
self.state = 272
self.expr()
self.state = 273
self.match(LaTeXParser.BAR)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AtomContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.AtomContext, self).__init__(parent, invokingState)
self.parser = parser
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def NUMBER(self):
return self.getToken(LaTeXParser.NUMBER, 0)
def DIFFERENTIAL(self):
return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
def mathit(self):
return self.getTypedRuleContext(LaTeXParser.MathitContext,0)
def bra(self):
return self.getTypedRuleContext(LaTeXParser.BraContext,0)
def ket(self):
return self.getTypedRuleContext(LaTeXParser.KetContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_atom
def atom(self):
localctx = LaTeXParser.AtomContext(self, self._ctx, self.state)
self.enterRule(localctx, 42, self.RULE_atom)
self._la = 0 # Token type
try:
self.state = 284
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 1)
self.state = 275
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 277
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,23,self._ctx)
if la_ == 1:
self.state = 276
self.subexpr()
pass
elif token in [LaTeXParser.NUMBER]:
self.enterOuterAlt(localctx, 2)
self.state = 279
self.match(LaTeXParser.NUMBER)
pass
elif token in [LaTeXParser.DIFFERENTIAL]:
self.enterOuterAlt(localctx, 3)
self.state = 280
self.match(LaTeXParser.DIFFERENTIAL)
pass
elif token in [LaTeXParser.CMD_MATHIT]:
self.enterOuterAlt(localctx, 4)
self.state = 281
self.mathit()
pass
elif token in [LaTeXParser.L_ANGLE]:
self.enterOuterAlt(localctx, 5)
self.state = 282
self.bra()
pass
elif token in [LaTeXParser.BAR, LaTeXParser.L_BAR]:
self.enterOuterAlt(localctx, 6)
self.state = 283
self.ket()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BraContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.BraContext, self).__init__(parent, invokingState)
self.parser = parser
def L_ANGLE(self):
return self.getToken(LaTeXParser.L_ANGLE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BAR(self):
return self.getToken(LaTeXParser.R_BAR, 0)
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_bra
def bra(self):
localctx = LaTeXParser.BraContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_bra)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 286
self.match(LaTeXParser.L_ANGLE)
self.state = 287
self.expr()
self.state = 288
_la = self._input.LA(1)
if not(_la==LaTeXParser.BAR or _la==LaTeXParser.R_BAR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class KetContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.KetContext, self).__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_ANGLE(self):
return self.getToken(LaTeXParser.R_ANGLE, 0)
def L_BAR(self):
return self.getToken(LaTeXParser.L_BAR, 0)
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_ket
def ket(self):
localctx = LaTeXParser.KetContext(self, self._ctx, self.state)
self.enterRule(localctx, 46, self.RULE_ket)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 290
_la = self._input.LA(1)
if not(_la==LaTeXParser.BAR or _la==LaTeXParser.L_BAR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 291
self.expr()
self.state = 292
self.match(LaTeXParser.R_ANGLE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MathitContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.MathitContext, self).__init__(parent, invokingState)
self.parser = parser
def CMD_MATHIT(self):
return self.getToken(LaTeXParser.CMD_MATHIT, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def mathit_text(self):
return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mathit
def mathit(self):
localctx = LaTeXParser.MathitContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_mathit)
try:
self.enterOuterAlt(localctx, 1)
self.state = 294
self.match(LaTeXParser.CMD_MATHIT)
self.state = 295
self.match(LaTeXParser.L_BRACE)
self.state = 296
self.mathit_text()
self.state = 297
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Mathit_textContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Mathit_textContext, self).__init__(parent, invokingState)
self.parser = parser
def LETTER(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.LETTER)
else:
return self.getToken(LaTeXParser.LETTER, i)
def getRuleIndex(self):
return LaTeXParser.RULE_mathit_text
def mathit_text(self):
localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state)
self.enterRule(localctx, 50, self.RULE_mathit_text)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 302
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==LaTeXParser.LETTER:
self.state = 299
self.match(LaTeXParser.LETTER)
self.state = 304
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FracContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.FracContext, self).__init__(parent, invokingState)
self.parser = parser
self.upper = None # ExprContext
self.lower = None # ExprContext
def CMD_FRAC(self):
return self.getToken(LaTeXParser.CMD_FRAC, 0)
def L_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def R_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def expr(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_frac
def frac(self):
localctx = LaTeXParser.FracContext(self, self._ctx, self.state)
self.enterRule(localctx, 52, self.RULE_frac)
try:
self.enterOuterAlt(localctx, 1)
self.state = 305
self.match(LaTeXParser.CMD_FRAC)
self.state = 306
self.match(LaTeXParser.L_BRACE)
self.state = 307
localctx.upper = self.expr()
self.state = 308
self.match(LaTeXParser.R_BRACE)
self.state = 309
self.match(LaTeXParser.L_BRACE)
self.state = 310
localctx.lower = self.expr()
self.state = 311
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BinomContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.BinomContext, self).__init__(parent, invokingState)
self.parser = parser
self.n = None # ExprContext
self.k = None # ExprContext
def L_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def R_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def CMD_BINOM(self):
return self.getToken(LaTeXParser.CMD_BINOM, 0)
def CMD_DBINOM(self):
return self.getToken(LaTeXParser.CMD_DBINOM, 0)
def CMD_TBINOM(self):
return self.getToken(LaTeXParser.CMD_TBINOM, 0)
def expr(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_binom
def binom(self):
localctx = LaTeXParser.BinomContext(self, self._ctx, self.state)
self.enterRule(localctx, 54, self.RULE_binom)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 313
_la = self._input.LA(1)
if not(((((_la - 67)) & ~0x3f) == 0 and ((1 << (_la - 67)) & ((1 << (LaTeXParser.CMD_BINOM - 67)) | (1 << (LaTeXParser.CMD_DBINOM - 67)) | (1 << (LaTeXParser.CMD_TBINOM - 67)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 314
self.match(LaTeXParser.L_BRACE)
self.state = 315
localctx.n = self.expr()
self.state = 316
self.match(LaTeXParser.R_BRACE)
self.state = 317
self.match(LaTeXParser.L_BRACE)
self.state = 318
localctx.k = self.expr()
self.state = 319
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FloorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.FloorContext, self).__init__(parent, invokingState)
self.parser = parser
self.val = None # ExprContext
def L_FLOOR(self):
return self.getToken(LaTeXParser.L_FLOOR, 0)
def R_FLOOR(self):
return self.getToken(LaTeXParser.R_FLOOR, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_floor
def floor(self):
localctx = LaTeXParser.FloorContext(self, self._ctx, self.state)
self.enterRule(localctx, 56, self.RULE_floor)
try:
self.enterOuterAlt(localctx, 1)
self.state = 321
self.match(LaTeXParser.L_FLOOR)
self.state = 322
localctx.val = self.expr()
self.state = 323
self.match(LaTeXParser.R_FLOOR)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CeilContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.CeilContext, self).__init__(parent, invokingState)
self.parser = parser
self.val = None # ExprContext
def L_CEIL(self):
return self.getToken(LaTeXParser.L_CEIL, 0)
def R_CEIL(self):
return self.getToken(LaTeXParser.R_CEIL, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_ceil
def ceil(self):
localctx = LaTeXParser.CeilContext(self, self._ctx, self.state)
self.enterRule(localctx, 58, self.RULE_ceil)
try:
self.enterOuterAlt(localctx, 1)
self.state = 325
self.match(LaTeXParser.L_CEIL)
self.state = 326
localctx.val = self.expr()
self.state = 327
self.match(LaTeXParser.R_CEIL)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_normalContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Func_normalContext, self).__init__(parent, invokingState)
self.parser = parser
def FUNC_EXP(self):
return self.getToken(LaTeXParser.FUNC_EXP, 0)
def FUNC_LOG(self):
return self.getToken(LaTeXParser.FUNC_LOG, 0)
def FUNC_LN(self):
return self.getToken(LaTeXParser.FUNC_LN, 0)
def FUNC_SIN(self):
return self.getToken(LaTeXParser.FUNC_SIN, 0)
def FUNC_COS(self):
return self.getToken(LaTeXParser.FUNC_COS, 0)
def FUNC_TAN(self):
return self.getToken(LaTeXParser.FUNC_TAN, 0)
def FUNC_CSC(self):
return self.getToken(LaTeXParser.FUNC_CSC, 0)
def FUNC_SEC(self):
return self.getToken(LaTeXParser.FUNC_SEC, 0)
def FUNC_COT(self):
return self.getToken(LaTeXParser.FUNC_COT, 0)
def FUNC_ARCSIN(self):
return self.getToken(LaTeXParser.FUNC_ARCSIN, 0)
def FUNC_ARCCOS(self):
return self.getToken(LaTeXParser.FUNC_ARCCOS, 0)
def FUNC_ARCTAN(self):
return self.getToken(LaTeXParser.FUNC_ARCTAN, 0)
def FUNC_ARCCSC(self):
return self.getToken(LaTeXParser.FUNC_ARCCSC, 0)
def FUNC_ARCSEC(self):
return self.getToken(LaTeXParser.FUNC_ARCSEC, 0)
def FUNC_ARCCOT(self):
return self.getToken(LaTeXParser.FUNC_ARCCOT, 0)
def FUNC_SINH(self):
return self.getToken(LaTeXParser.FUNC_SINH, 0)
def FUNC_COSH(self):
return self.getToken(LaTeXParser.FUNC_COSH, 0)
def FUNC_TANH(self):
return self.getToken(LaTeXParser.FUNC_TANH, 0)
def FUNC_ARSINH(self):
return self.getToken(LaTeXParser.FUNC_ARSINH, 0)
def FUNC_ARCOSH(self):
return self.getToken(LaTeXParser.FUNC_ARCOSH, 0)
def FUNC_ARTANH(self):
return self.getToken(LaTeXParser.FUNC_ARTANH, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_normal
def func_normal(self):
localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state)
self.enterRule(localctx, 60, self.RULE_func_normal)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 329
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.FUNC_EXP) | (1 << LaTeXParser.FUNC_LOG) | (1 << LaTeXParser.FUNC_LN) | (1 << LaTeXParser.FUNC_SIN) | (1 << LaTeXParser.FUNC_COS) | (1 << LaTeXParser.FUNC_TAN) | (1 << LaTeXParser.FUNC_CSC) | (1 << LaTeXParser.FUNC_SEC) | (1 << LaTeXParser.FUNC_COT) | (1 << LaTeXParser.FUNC_ARCSIN) | (1 << LaTeXParser.FUNC_ARCCOS) | (1 << LaTeXParser.FUNC_ARCTAN) | (1 << LaTeXParser.FUNC_ARCCSC) | (1 << LaTeXParser.FUNC_ARCSEC) | (1 << LaTeXParser.FUNC_ARCCOT) | (1 << LaTeXParser.FUNC_SINH) | (1 << LaTeXParser.FUNC_COSH) | (1 << LaTeXParser.FUNC_TANH) | (1 << LaTeXParser.FUNC_ARSINH) | (1 << LaTeXParser.FUNC_ARCOSH) | (1 << LaTeXParser.FUNC_ARTANH))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FuncContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.FuncContext, self).__init__(parent, invokingState)
self.parser = parser
self.root = None # ExprContext
self.base = None # ExprContext
def func_normal(self):
return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0)
def L_PAREN(self):
return self.getToken(LaTeXParser.L_PAREN, 0)
def func_arg(self):
return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
def R_PAREN(self):
return self.getToken(LaTeXParser.R_PAREN, 0)
def func_arg_noparens(self):
return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def supexpr(self):
return self.getTypedRuleContext(LaTeXParser.SupexprContext,0)
def args(self):
return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def FUNC_INT(self):
return self.getToken(LaTeXParser.FUNC_INT, 0)
def DIFFERENTIAL(self):
return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
def frac(self):
return self.getTypedRuleContext(LaTeXParser.FracContext,0)
def additive(self):
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
def FUNC_SQRT(self):
return self.getToken(LaTeXParser.FUNC_SQRT, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self, i=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def L_BRACKET(self):
return self.getToken(LaTeXParser.L_BRACKET, 0)
def R_BRACKET(self):
return self.getToken(LaTeXParser.R_BRACKET, 0)
def FUNC_OVERLINE(self):
return self.getToken(LaTeXParser.FUNC_OVERLINE, 0)
def mp(self):
return self.getTypedRuleContext(LaTeXParser.MpContext,0)
def FUNC_SUM(self):
return self.getToken(LaTeXParser.FUNC_SUM, 0)
def FUNC_PROD(self):
return self.getToken(LaTeXParser.FUNC_PROD, 0)
def subeq(self):
return self.getTypedRuleContext(LaTeXParser.SubeqContext,0)
def FUNC_LIM(self):
return self.getToken(LaTeXParser.FUNC_LIM, 0)
def limit_sub(self):
return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func
def func(self):
localctx = LaTeXParser.FuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 62, self.RULE_func)
self._la = 0 # Token type
try:
self.state = 409
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH]:
self.enterOuterAlt(localctx, 1)
self.state = 331
self.func_normal()
self.state = 344
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
if la_ == 1:
self.state = 333
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 332
self.subexpr()
self.state = 336
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 335
self.supexpr()
pass
elif la_ == 2:
self.state = 339
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 338
self.supexpr()
self.state = 342
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 341
self.subexpr()
pass
self.state = 351
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,31,self._ctx)
if la_ == 1:
self.state = 346
self.match(LaTeXParser.L_PAREN)
self.state = 347
self.func_arg()
self.state = 348
self.match(LaTeXParser.R_PAREN)
pass
elif la_ == 2:
self.state = 350
self.func_arg_noparens()
pass
pass
elif token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 353
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 355
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 354
self.subexpr()
self.state = 357
self.match(LaTeXParser.L_PAREN)
self.state = 358
self.args()
self.state = 359
self.match(LaTeXParser.R_PAREN)
pass
elif token in [LaTeXParser.FUNC_INT]:
self.enterOuterAlt(localctx, 3)
self.state = 361
self.match(LaTeXParser.FUNC_INT)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.UNDERSCORE]:
self.state = 362
self.subexpr()
self.state = 363
self.supexpr()
pass
elif token in [LaTeXParser.CARET]:
self.state = 365
self.supexpr()
self.state = 366
self.subexpr()
pass
elif token in [LaTeXParser.ADD, LaTeXParser.SUB, LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
pass
else:
pass
self.state = 376
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,35,self._ctx)
if la_ == 1:
self.state = 371
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,34,self._ctx)
if la_ == 1:
self.state = 370
self.additive(0)
self.state = 373
self.match(LaTeXParser.DIFFERENTIAL)
pass
elif la_ == 2:
self.state = 374
self.frac()
pass
elif la_ == 3:
self.state = 375
self.additive(0)
pass
pass
elif token in [LaTeXParser.FUNC_SQRT]:
self.enterOuterAlt(localctx, 4)
self.state = 378
self.match(LaTeXParser.FUNC_SQRT)
self.state = 383
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.L_BRACKET:
self.state = 379
self.match(LaTeXParser.L_BRACKET)
self.state = 380
localctx.root = self.expr()
self.state = 381
self.match(LaTeXParser.R_BRACKET)
self.state = 385
self.match(LaTeXParser.L_BRACE)
self.state = 386
localctx.base = self.expr()
self.state = 387
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.FUNC_OVERLINE]:
self.enterOuterAlt(localctx, 5)
self.state = 389
self.match(LaTeXParser.FUNC_OVERLINE)
self.state = 390
self.match(LaTeXParser.L_BRACE)
self.state = 391
localctx.base = self.expr()
self.state = 392
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD]:
self.enterOuterAlt(localctx, 6)
self.state = 394
_la = self._input.LA(1)
if not(_la==LaTeXParser.FUNC_SUM or _la==LaTeXParser.FUNC_PROD):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 401
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.UNDERSCORE]:
self.state = 395
self.subeq()
self.state = 396
self.supexpr()
pass
elif token in [LaTeXParser.CARET]:
self.state = 398
self.supexpr()
self.state = 399
self.subeq()
pass
else:
raise NoViableAltException(self)
self.state = 403
self.mp(0)
pass
elif token in [LaTeXParser.FUNC_LIM]:
self.enterOuterAlt(localctx, 7)
self.state = 405
self.match(LaTeXParser.FUNC_LIM)
self.state = 406
self.limit_sub()
self.state = 407
self.mp(0)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ArgsContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.ArgsContext, self).__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def args(self):
return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_args
def args(self):
localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state)
self.enterRule(localctx, 64, self.RULE_args)
try:
self.state = 416
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,39,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 411
self.expr()
self.state = 412
self.match(LaTeXParser.T__0)
self.state = 413
self.args()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 415
self.expr()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Limit_subContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Limit_subContext, self).__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def LIM_APPROACH_SYM(self):
return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self, i=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_limit_sub
def limit_sub(self):
localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state)
self.enterRule(localctx, 66, self.RULE_limit_sub)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 418
self.match(LaTeXParser.UNDERSCORE)
self.state = 419
self.match(LaTeXParser.L_BRACE)
self.state = 420
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 421
self.match(LaTeXParser.LIM_APPROACH_SYM)
self.state = 422
self.expr()
self.state = 427
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 423
self.match(LaTeXParser.CARET)
self.state = 424
self.match(LaTeXParser.L_BRACE)
self.state = 425
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 426
self.match(LaTeXParser.R_BRACE)
self.state = 429
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_argContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Func_argContext, self).__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def func_arg(self):
return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_arg
def func_arg(self):
localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state)
self.enterRule(localctx, 68, self.RULE_func_arg)
try:
self.state = 436
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,41,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 431
self.expr()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 432
self.expr()
self.state = 433
self.match(LaTeXParser.T__0)
self.state = 434
self.func_arg()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_arg_noparensContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.Func_arg_noparensContext, self).__init__(parent, invokingState)
self.parser = parser
def mp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_arg_noparens
def func_arg_noparens(self):
localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state)
self.enterRule(localctx, 70, self.RULE_func_arg_noparens)
try:
self.enterOuterAlt(localctx, 1)
self.state = 438
self.mp_nofunc(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SubexprContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.SubexprContext, self).__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_subexpr
def subexpr(self):
localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state)
self.enterRule(localctx, 72, self.RULE_subexpr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 440
self.match(LaTeXParser.UNDERSCORE)
self.state = 446
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.state = 441
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 442
self.match(LaTeXParser.L_BRACE)
self.state = 443
self.expr()
self.state = 444
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SupexprContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.SupexprContext, self).__init__(parent, invokingState)
self.parser = parser
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_supexpr
def supexpr(self):
localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state)
self.enterRule(localctx, 74, self.RULE_supexpr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 448
self.match(LaTeXParser.CARET)
self.state = 454
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]:
self.state = 449
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 450
self.match(LaTeXParser.L_BRACE)
self.state = 451
self.expr()
self.state = 452
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SubeqContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.SubeqContext, self).__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_subeq
def subeq(self):
localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state)
self.enterRule(localctx, 76, self.RULE_subeq)
try:
self.enterOuterAlt(localctx, 1)
self.state = 456
self.match(LaTeXParser.UNDERSCORE)
self.state = 457
self.match(LaTeXParser.L_BRACE)
self.state = 458
self.equality()
self.state = 459
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SupeqContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(LaTeXParser.SupeqContext, self).__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_supeq
def supeq(self):
localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state)
self.enterRule(localctx, 78, self.RULE_supeq)
try:
self.enterOuterAlt(localctx, 1)
self.state = 461
self.match(LaTeXParser.UNDERSCORE)
self.state = 462
self.match(LaTeXParser.L_BRACE)
self.state = 463
self.equality()
self.state = 464
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
def sempred(self, localctx, ruleIndex, predIndex):
if self._predicates == None:
self._predicates = dict()
self._predicates[1] = self.relation_sempred
self._predicates[4] = self.additive_sempred
self._predicates[5] = self.mp_sempred
self._predicates[6] = self.mp_nofunc_sempred
self._predicates[15] = self.exp_sempred
self._predicates[16] = self.exp_nofunc_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def relation_sempred(self, localctx, predIndex):
if predIndex == 0:
return self.precpred(self._ctx, 2)
def additive_sempred(self, localctx, predIndex):
if predIndex == 1:
return self.precpred(self._ctx, 2)
def mp_sempred(self, localctx, predIndex):
if predIndex == 2:
return self.precpred(self._ctx, 2)
def mp_nofunc_sempred(self, localctx, predIndex):
if predIndex == 3:
return self.precpred(self._ctx, 2)
def exp_sempred(self, localctx, predIndex):
if predIndex == 4:
return self.precpred(self._ctx, 2)
def exp_nofunc_sempred(self, localctx, predIndex):
if predIndex == 5:
return self.precpred(self._ctx, 2)
|
a987fec2ff25a870d9c6c4bcf0f62cfde1272ce7bea834387ba2ce08933198ab | """Quantum mechanical angular momemtum."""
from sympy import (Add, binomial, cos, exp, Expr, factorial, I, Integer, Mul,
pi, Rational, S, sin, simplify, sqrt, Sum, symbols, sympify,
Tuple, Dummy)
from sympy.matrices import zeros
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import pretty_symbol
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.operator import (HermitianOperator, Operator,
UnitaryOperator)
from sympy.physics.quantum.state import Bra, Ket, State
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.cg import CG
from sympy.physics.quantum.qapply import qapply
__all__ = [
'm_values',
'Jplus',
'Jminus',
'Jx',
'Jy',
'Jz',
'J2',
'Rotation',
'WignerD',
'JxKet',
'JxBra',
'JyKet',
'JyBra',
'JzKet',
'JzBra',
'JzOp',
'J2Op',
'JxKetCoupled',
'JxBraCoupled',
'JyKetCoupled',
'JyBraCoupled',
'JzKetCoupled',
'JzBraCoupled',
'couple',
'uncouple'
]
def m_values(j):
j = sympify(j)
size = 2*j + 1
if not size.is_Integer or not size > 0:
raise ValueError(
'Only integer or half-integer values allowed for j, got: : %r' % j
)
return size, [j - i for i in range(int(2*j + 1))]
#-----------------------------------------------------------------------------
# Spin Operators
#-----------------------------------------------------------------------------
class SpinOpBase:
"""Base class for spin operators."""
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def name(self):
return self.args[0]
def _print_contents(self, printer, *args):
return '%s%s' % (self.name, self._coord)
def _print_contents_pretty(self, printer, *args):
a = stringPict(str(self.name))
b = stringPict(self._coord)
return self._print_subscript_pretty(a, b)
def _print_contents_latex(self, printer, *args):
return r'%s_%s' % ((self.name, self._coord))
def _represent_base(self, basis, **options):
j = options.get('j', S.Half)
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
result[p, q] = me
return result
def _apply_op(self, ket, orig_basis, **options):
state = ket.rewrite(self.basis)
# If the state has only one term
if isinstance(state, State):
ret = (hbar*state.m)*state
# state is a linear combination of states
elif isinstance(state, Sum):
ret = self._apply_operator_Sum(state, **options)
else:
ret = qapply(self*state)
if ret == self*state:
raise NotImplementedError
return ret.rewrite(orig_basis)
def _apply_operator_JxKet(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_TensorProduct(self, tp, **options):
# Uncoupling operator is only easily found for coordinate basis spin operators
# TODO: add methods for uncoupling operators
if not (isinstance(self, JxOp) or isinstance(self, JyOp) or isinstance(self, JzOp)):
raise NotImplementedError
result = []
for n in range(len(tp.args)):
arg = []
arg.extend(tp.args[:n])
arg.append(self._apply_operator(tp.args[n]))
arg.extend(tp.args[n + 1:])
result.append(tp.__class__(*arg))
return Add(*result).expand()
# TODO: move this to qapply_Mul
def _apply_operator_Sum(self, s, **options):
new_func = qapply(self*s.function)
if new_func == self*s.function:
raise NotImplementedError
return Sum(new_func, *s.limits)
def _eval_trace(self, **options):
#TODO: use options to use different j values
#For now eval at default basis
# is it efficient to represent each time
# to do a trace?
return self._represent_default_basis().trace()
class JplusOp(SpinOpBase, Operator):
"""The J+ operator."""
_coord = '+'
basis = 'Jz'
def _eval_commutator_JminusOp(self, other):
return 2*hbar*JzOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
result *= KroneckerDelta(m, mp + 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) + I*JyOp(args[0])
class JminusOp(SpinOpBase, Operator):
"""The J- operator."""
_coord = '-'
basis = 'Jz'
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
result *= KroneckerDelta(m, mp - 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) - I*JyOp(args[0])
class JxOp(SpinOpBase, HermitianOperator):
"""The Jx operator."""
_coord = 'x'
basis = 'Jx'
def _eval_commutator_JyOp(self, other):
return I*hbar*JzOp(self.name)
def _eval_commutator_JzOp(self, other):
return -I*hbar*JyOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp + jm)/Integer(2)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp + jm)/Integer(2)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp + jm)/Integer(2)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) + JminusOp(args[0]))/2
class JyOp(SpinOpBase, HermitianOperator):
"""The Jy operator."""
_coord = 'y'
basis = 'Jy'
def _eval_commutator_JzOp(self, other):
return I*hbar*JxOp(self.name)
def _eval_commutator_JxOp(self, other):
return -I*hbar*J2Op(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp - jm)/(Integer(2)*I)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
class JzOp(SpinOpBase, HermitianOperator):
"""The Jz operator."""
_coord = 'z'
basis = 'Jz'
def _eval_commutator_JxOp(self, other):
return I*hbar*JyOp(self.name)
def _eval_commutator_JyOp(self, other):
return -I*hbar*JxOp(self.name)
def _eval_commutator_JplusOp(self, other):
return hbar*JplusOp(self.name)
def _eval_commutator_JminusOp(self, other):
return -hbar*JminusOp(self.name)
def matrix_element(self, j, m, jp, mp):
result = hbar*mp
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
class J2Op(SpinOpBase, HermitianOperator):
"""The J^2 operator."""
_coord = '2'
def _eval_commutator_JxOp(self, other):
return S.Zero
def _eval_commutator_JyOp(self, other):
return S.Zero
def _eval_commutator_JzOp(self, other):
return S.Zero
def _eval_commutator_JplusOp(self, other):
return S.Zero
def _eval_commutator_JminusOp(self, other):
return S.Zero
def _apply_operator_JxKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JxKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def matrix_element(self, j, m, jp, mp):
result = (hbar**2)*j*(j + 1)
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _print_contents_pretty(self, printer, *args):
a = prettyForm(str(self.name))
b = prettyForm('2')
return a**b
def _print_contents_latex(self, printer, *args):
return r'%s^2' % str(self.name)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
a = args[0]
return JzOp(a)**2 + \
S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
class Rotation(UnitaryOperator):
"""Wigner D operator in terms of Euler angles.
Defines the rotation operator in terms of the Euler angles defined by
the z-y-z convention for a passive transformation. That is the coordinate
axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
this new coordinate system is rotated about the new y'-axis, giving new
x''-y''-z'' axes. Then this new coordinate system is rotated about the
z''-axis. Conventions follow those laid out in [1]_.
Parameters
==========
alpha : Number, Symbol
First Euler Angle
beta : Number, Symbol
Second Euler angle
gamma : Number, Symbol
Third Euler angle
Examples
========
A simple example rotation operator:
>>> from sympy import pi
>>> from sympy.physics.quantum.spin import Rotation
>>> Rotation(pi, 0, pi/2)
R(pi,0,pi/2)
With symbolic Euler angles and calculating the inverse rotation operator:
>>> from sympy import symbols
>>> a, b, c = symbols('a b c')
>>> Rotation(a, b, c)
R(a,b,c)
>>> Rotation(a, b, c).inverse()
R(-c,-b,-a)
See Also
========
WignerD: Symbolic Wigner-D function
D: Wigner-D function
d: Wigner small-d function
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
@classmethod
def _eval_args(cls, args):
args = QExpr._eval_args(args)
if len(args) != 3:
raise ValueError('3 Euler angles required, got: %r' % args)
return args
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def alpha(self):
return self.label[0]
@property
def beta(self):
return self.label[1]
@property
def gamma(self):
return self.label[2]
def _print_operator_name(self, printer, *args):
return 'R'
def _print_operator_name_pretty(self, printer, *args):
if printer._use_unicode:
return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
else:
return prettyForm("R ")
def _print_operator_name_latex(self, printer, *args):
return r'\mathcal{R}'
def _eval_inverse(self):
return Rotation(-self.gamma, -self.beta, -self.alpha)
@classmethod
def D(cls, j, m, mp, alpha, beta, gamma):
"""Wigner D-function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> alpha, beta, gamma = symbols('alpha beta gamma')
>>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
WignerD(1, 1, 0, pi, pi/2, -pi)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, alpha, beta, gamma)
@classmethod
def d(cls, j, m, mp, beta):
"""Wigner small-d function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters with the alpha and gamma angles
given as 0.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
beta : Number, Symbol
Second Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> beta = symbols('beta')
>>> Rotation.d(1, 1, 0, pi/2)
WignerD(1, 1, 0, 0, pi/2, 0)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, 0, beta, 0)
def matrix_element(self, j, m, jp, mp):
result = self.__class__.D(
jp, m, mp, self.alpha, self.beta, self.gamma
)
result *= KroneckerDelta(j, jp)
return result
def _represent_base(self, basis, **options):
j = sympify(options.get('j', S.Half))
# TODO: move evaluation up to represent function/implement elsewhere
evaluate = sympify(options.get('doit'))
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
if evaluate:
result[p, q] = me.doit()
else:
result[p, q] = me
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
def _apply_operator_JxKet(self, ket, **options):
return self._apply_operator_uncoupled(JxKet, ket, **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_operator_uncoupled(JyKet, ket, **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_operator_uncoupled(JzKet, ket, **options)
def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp, jn, coupling))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(
j, mp, jn, coupling), (mp, -j, j))
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JxKetCoupled, ket, **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JyKetCoupled, ket, **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JzKetCoupled, ket, **options)
class WignerD(Expr):
r"""Wigner-D function
The Wigner D-function gives the matrix elements of the rotation
operator in the jm-representation. For the Euler angles `\alpha`,
`\beta`, `\gamma`, the D-function is defined such that:
.. math ::
<j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
Where the rotation operator is as defined by the Rotation class [1]_.
The Wigner D-function defined in this way gives:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the Wigner small-d function, which is given by Rotation.d.
The Wigner small-d function gives the component of the Wigner
D-function that is determined by the second Euler angle. That is the
Wigner D-function is:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the small-d function. The Wigner D-function is given by
Rotation.D.
Note that to evaluate the D-function, the j, m and mp parameters must
be integer or half integer numbers.
Parameters
==========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Evaluate the Wigner-D matrix elements of a simple rotation:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi
>>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
>>> rot
WignerD(1, 1, 0, pi, pi/2, 0)
>>> rot.doit()
sqrt(2)/2
Evaluate the Wigner-d matrix elements of a simple rotation
>>> rot = Rotation.d(1, 1, 0, pi/2)
>>> rot
WignerD(1, 1, 0, 0, pi/2, 0)
>>> rot.doit()
-sqrt(2)/2
See Also
========
Rotation: Rotation operator
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, *args, **hints):
if not len(args) == 6:
raise ValueError('6 parameters expected, got %s' % args)
args = sympify(args)
evaluate = hints.get('evaluate', False)
if evaluate:
return Expr.__new__(cls, *args)._eval_wignerd()
return Expr.__new__(cls, *args)
@property
def j(self):
return self.args[0]
@property
def m(self):
return self.args[1]
@property
def mp(self):
return self.args[2]
@property
def alpha(self):
return self.args[3]
@property
def beta(self):
return self.args[4]
@property
def gamma(self):
return self.args[5]
def _latex(self, printer, *args):
if self.alpha == 0 and self.gamma == 0:
return r'd^{%s}_{%s,%s}\left(%s\right)' % \
(
printer._print(self.j), printer._print(
self.m), printer._print(self.mp),
printer._print(self.beta) )
return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
(
printer._print(
self.j), printer._print(self.m), printer._print(self.mp),
printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
def _pretty(self, printer, *args):
top = printer._print(self.j)
bot = printer._print(self.m)
bot = prettyForm(*bot.right(','))
bot = prettyForm(*bot.right(printer._print(self.mp)))
pad = max(top.width(), bot.width())
top = prettyForm(*top.left(' '))
bot = prettyForm(*bot.left(' '))
if pad > top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
if pad > bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if self.alpha == 0 and self.gamma == 0:
args = printer._print(self.beta)
s = stringPict('d' + ' '*pad)
else:
args = printer._print(self.alpha)
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.beta)))
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.gamma)))
s = stringPict('D' + ' '*pad)
args = prettyForm(*args.parens())
s = prettyForm(*s.above(top))
s = prettyForm(*s.below(bot))
s = prettyForm(*s.right(args))
return s
def doit(self, **hints):
hints['evaluate'] = True
return WignerD(*self.args, **hints)
def _eval_wignerd(self):
j = sympify(self.j)
m = sympify(self.m)
mp = sympify(self.mp)
alpha = sympify(self.alpha)
beta = sympify(self.beta)
gamma = sympify(self.gamma)
if alpha == 0 and beta == 0 and gamma == 0:
return KroneckerDelta(m, mp)
if not j.is_number:
raise ValueError(
'j parameter must be numerical to evaluate, got %s' % j)
r = 0
if beta == pi/2:
# Varshalovich Equation (5), Section 4.16, page 113, setting
# alpha=gamma=0.
for k in range(2*j + 1):
if k > j + mp or k > j - m or k < mp - m:
continue
r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
else:
# Varshalovich Equation(5), Section 4.7.2, page 87, where we set
# beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
# then we use the Eq. (1), Section 4.4. page 79, to simplify:
# d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
# This happens to be almost the same as in Eq.(10), Section 4.16,
# except that we need to substitute -mp for mp.
size, mvals = m_values(j)
for mpp in mvals:
r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
Rotation.d(j, mpp, -mp, pi/2).doit()
# Empirical normalization factor so results match Varshalovich
# Tables 4.3-4.12
# Note that this exact normalization does not follow from the
# above equations
r = r*I**(2*j - m - mp)*(-1)**(2*m)
# Finally, simplify the whole expression
r = simplify(r)
r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
return r
Jx = JxOp('J')
Jy = JyOp('J')
Jz = JzOp('J')
J2 = J2Op('J')
Jplus = JplusOp('J')
Jminus = JminusOp('J')
#-----------------------------------------------------------------------------
# Spin States
#-----------------------------------------------------------------------------
class SpinState(State):
"""Base class for angular momentum states."""
_label_separator = ','
def __new__(cls, j, m):
j = sympify(j)
m = sympify(m)
if j.is_number:
if 2*j != int(2*j):
raise ValueError(
'j must be integer or half-integer, got: %s' % j)
if j < 0:
raise ValueError('j must be >= 0, got: %s' % j)
if m.is_number:
if 2*m != int(2*m):
raise ValueError(
'm must be integer or half-integer, got: %s' % m)
if j.is_number and m.is_number:
if abs(m) > j:
raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
if int(j - m) != j - m:
raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
return State.__new__(cls, j, m)
@property
def j(self):
return self.label[0]
@property
def m(self):
return self.label[1]
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(2*label[0] + 1)
def _represent_base(self, **options):
j = self.j
m = self.m
alpha = sympify(options.get('alpha', 0))
beta = sympify(options.get('beta', 0))
gamma = sympify(options.get('gamma', 0))
size, mvals = m_values(j)
result = zeros(size, 1)
# breaks finding angles on L930
for p, mval in enumerate(mvals):
if m.is_number:
result[p, 0] = Rotation.D(
self.j, mval, self.m, alpha, beta, gamma).doit()
else:
result[p, 0] = Rotation.D(self.j, mval,
self.m, alpha, beta, gamma)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBra, **options)
return self._rewrite_basis(Jx, JxKet, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBra, **options)
return self._rewrite_basis(Jy, JyKet, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBra, **options)
return self._rewrite_basis(Jz, JzKet, **options)
def _rewrite_basis(self, basis, evect, **options):
from sympy.physics.quantum.represent import represent
j = self.j
args = self.args[2:]
if j.is_number:
if isinstance(self, CoupledSpinState):
if j == int(j):
start = j**2
else:
start = (2*j - 1)*(2*j + 1)/4
else:
start = 0
vect = represent(self, basis=basis, **options)
result = Add(
*[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
return uncouple(result)
return result
else:
i = 0
mi = symbols('mi')
# make sure not to introduce a symbol already in the state
while self.subs(mi, 0) != self:
i += 1
mi = symbols('mi%d' % i)
break
# TODO: better way to get angles of rotation
if isinstance(self, CoupledSpinState):
test_args = (0, mi, (0, 0))
else:
test_args = (0, mi)
if isinstance(self, Ket):
angles = represent(
self.__class__(*test_args), basis=basis)[0].args[3:6]
else:
angles = represent(self.__class__(
*test_args), basis=basis)[0].args[0].args[3:6]
if angles == (0, 0, 0):
return self
else:
state = evect(j, mi, *args)
lt = Rotation.D(j, mi, self.m, *angles)
return Sum(lt*state, (mi, -j, j))
def _eval_innerproduct_JxBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JxOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JyBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JyOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JzBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JzOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_trace(self, bra, **hints):
# One way to implement this method is to assume the basis set k is
# passed.
# Then we can apply the discrete form of Trace formula here
# Tr(|i><j| ) = \Sum_k <k|i><j|k>
#then we do qapply() on each each inner product and sum over them.
# OR
# Inner product of |i><j| = Trace(Outer Product).
# we could just use this unless there are cases when this is not true
return (bra*self).doit()
class JxKet(SpinState, Ket):
"""Eigenket of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxBra
@classmethod
def coupled_class(self):
return JxKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JxOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(beta=pi/2, **options)
class JxBra(SpinState, Bra):
"""Eigenbra of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxKet
@classmethod
def coupled_class(self):
return JxBraCoupled
class JyKet(SpinState, Ket):
"""Eigenket of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyBra
@classmethod
def coupled_class(self):
return JyKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JyOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBra(SpinState, Bra):
"""Eigenbra of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyKet
@classmethod
def coupled_class(self):
return JyBraCoupled
class JzKet(SpinState, Ket):
"""Eigenket of Jz.
Spin state which is an eigenstate of the Jz operator. Uncoupled states,
that is states representing the interaction of multiple separate spin
states, are defined as a tensor product of states.
Parameters
==========
j : Number, Symbol
Total spin angular momentum
m : Number, Symbol
Eigenvalue of the Jz spin operator
Examples
========
*Normal States:*
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKet, JxKet
>>> from sympy import symbols
>>> JzKet(1, 0)
|1,0>
>>> j, m = symbols('j m')
>>> JzKet(j, m)
|j,m>
Rewriting the JzKet in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKet's
>>> JzKet(1,1).rewrite("Jx")
|1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx, Jz
>>> represent(JzKet(1,-1), basis=Jx)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
Apply innerproducts between states:
>>> from sympy.physics.quantum.innerproduct import InnerProduct
>>> from sympy.physics.quantum.spin import JxBra
>>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
>>> i
<1,1|1,1>
>>> i.doit()
1/2
*Uncoupled States:*
Define an uncoupled state as a TensorProduct between two Jz eigenkets:
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> TensorProduct(JzKet(1,0), JzKet(1,1))
|1,0>x|1,1>
>>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
|j1,m1>x|j2,m2>
A TensorProduct can be rewritten, in which case the eigenstates that make
up the tensor product is rewritten to the new basis:
>>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
|1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
The represent method for TensorProduct's gives the vector representation of
the state. Note that the state in the product basis is the equivalent of the
tensor product of the vector representation of the component eigenstates:
>>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
Matrix([
[0],
[0],
[0],
[1],
[0],
[0],
[0],
[0],
[0]])
>>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0]])
See Also
========
JzKetCoupled: Coupled eigenstates
sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
uncouple: Uncouples states given coupling parameters
couple: Couples uncoupled states
"""
@classmethod
def dual_class(self):
return JzBra
@classmethod
def coupled_class(self):
return JzKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(**options)
class JzBra(SpinState, Bra):
"""Eigenbra of Jz.
See the JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JzKet
@classmethod
def coupled_class(self):
return JzBraCoupled
# Method used primarily to create coupled_n and coupled_jn by __new__ in
# CoupledSpinState
# This same method is also used by the uncouple method, and is separated from
# the CoupledSpinState class to maintain consistency in defining coupling
def _build_coupled(jcoupling, length):
n_list = [ [n + 1] for n in range(length) ]
coupled_jn = []
coupled_n = []
for n1, n2, j_new in jcoupling:
coupled_jn.append(j_new)
coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
n_list[n_sort[0] - 1] = n_sort
return coupled_n, coupled_jn
class CoupledSpinState(SpinState):
"""Base class for coupled angular momentum states."""
def __new__(cls, j, m, jn, *jcoupling):
# Check j and m values using SpinState
SpinState(j, m)
# Build and check coupling scheme from arguments
if len(jcoupling) == 0:
# Use default coupling scheme
jcoupling = []
for n in range(2, len(jn)):
jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
jcoupling.append( (1, len(jn), j) )
elif len(jcoupling) == 1:
# Use specified coupling scheme
jcoupling = jcoupling[0]
else:
raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
# Check arguments have correct form
if not (isinstance(jn, list) or isinstance(jn, tuple) or isinstance(jn, Tuple)):
raise TypeError('jn must be Tuple, list or tuple, got %s' %
jn.__class__.__name__)
if not (isinstance(jcoupling, list) or isinstance(jcoupling, tuple) or isinstance(jcoupling, Tuple)):
raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
jcoupling.__class__.__name__)
if not all(isinstance(term, list) or isinstance(term, tuple) or isinstance(term, Tuple) for term in jcoupling):
raise TypeError(
'All elements of jcoupling must be list, tuple or Tuple')
if not len(jn) - 1 == len(jcoupling):
raise ValueError('jcoupling must have length of %d, got %d' %
(len(jn) - 1, len(jcoupling)))
if not all(len(x) == 3 for x in jcoupling):
raise ValueError('All elements of jcoupling must have length 3')
# Build sympified args
j = sympify(j)
m = sympify(m)
jn = Tuple( *[sympify(ji) for ji in jn] )
jcoupling = Tuple( *[Tuple(sympify(
n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
# Check values in coupling scheme give physical state
if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
raise ValueError('Indices in jcoupling must be integers')
if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
jvals = list(jn)
for n, (n1, n2) in enumerate(coupled_n):
j1 = jvals[min(n1) - 1]
j2 = jvals[min(n2) - 1]
j3 = coupled_jn[n]
if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
if j1 + j2 < j3:
raise ValueError('All couplings must have j1+j2 >= j3, '
'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
if abs(j1 - j2) > j3:
raise ValueError("All couplings must have |j1+j2| <= j3, "
"in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
if int(j1 + j2) == j1 + j2:
pass
jvals[min(n1 + n2) - 1] = j3
if len(jcoupling) > 0 and jcoupling[-1][2] != j:
raise ValueError('Last j value coupled together must be the final j of the state')
# Return state
return State.__new__(cls, j, m, jn, jcoupling)
def _print_label(self, printer, *args):
label = [printer._print(self.j), printer._print(self.m)]
for i, ji in enumerate(self.jn, start=1):
label.append('j%d=%s' % (
i, printer._print(ji)
))
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
label.append('j(%s)=%s' % (
','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
))
return ','.join(label)
def _print_label_pretty(self, printer, *args):
label = [self.j, self.m]
for i, ji in enumerate(self.jn, start=1):
symb = 'j%d' % i
symb = pretty_symbol(symb)
symb = prettyForm(symb + '=')
item = prettyForm(*symb.right(printer._print(ji)))
label.append(item)
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
symb = prettyForm('j' + n + '=')
item = prettyForm(*symb.right(printer._print(jn)))
label.append(item)
return self._print_sequence_pretty(
label, self._label_separator, printer, *args
)
def _print_label_latex(self, printer, *args):
label = [
printer._print(self.j, *args),
printer._print(self.m, *args)
]
for i, ji in enumerate(self.jn, start=1):
label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(str(i) for i in sorted(n1 + n2))
label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
return self._label_separator.join(label)
@property
def jn(self):
return self.label[2]
@property
def coupling(self):
return self.label[3]
@property
def coupled_jn(self):
return _build_coupled(self.label[3], len(self.label[2]))[1]
@property
def coupled_n(self):
return _build_coupled(self.label[3], len(self.label[2]))[0]
@classmethod
def _eval_hilbert_space(cls, label):
j = Add(*label[2])
if j.is_number:
return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
else:
# TODO: Need hilbert space fix, see issue 5732
# Desired behavior:
#ji = symbols('ji')
#ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
# Temporary fix:
return ComplexSpace(2*j + 1)
def _represent_coupled_base(self, **options):
evect = self.uncoupled_class()
if not self.j.is_number:
raise ValueError(
'State must not have symbolic j value to represent')
if not self.hilbert_space.dimension.is_number:
raise ValueError(
'State must not have symbolic j values to represent')
result = zeros(self.hilbert_space.dimension, 1)
if self.j == int(self.j):
start = self.j**2
else:
start = (2*self.j - 1)*(1 + 2*self.j)/4
result[start:start + 2*self.j + 1, 0] = evect(
self.j, self.m)._represent_base(**options)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBraCoupled, **options)
return self._rewrite_basis(Jx, JxKetCoupled, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBraCoupled, **options)
return self._rewrite_basis(Jy, JyKetCoupled, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBraCoupled, **options)
return self._rewrite_basis(Jz, JzKetCoupled, **options)
class JxKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxBraCoupled
@classmethod
def uncoupled_class(self):
return JxKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(beta=pi/2, **options)
class JxBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxKetCoupled
@classmethod
def uncoupled_class(self):
return JxBra
class JyKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyBraCoupled
@classmethod
def uncoupled_class(self):
return JyKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyKetCoupled
@classmethod
def uncoupled_class(self):
return JyBra
class JzKetCoupled(CoupledSpinState, Ket):
r"""Coupled eigenket of Jz
Spin state that is an eigenket of Jz which represents the coupling of
separate spin spaces.
The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
are the total angular momentum quantum numbers, as used for normal states
(e.g. JzKet).
The other required parameter in ``jn``, which is a tuple defining the `j_n`
angular momentum quantum numbers of the product spaces. So for example, if
a state represented the coupling of the product basis state
`\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
for this state would be ``(j1,j2)``.
The final option is ``jcoupling``, which is used to define how the spaces
specified by ``jn`` are coupled, which includes both the order these spaces
are coupled together and the quantum numbers that arise from these
couplings. The ``jcoupling`` parameter itself is a list of lists, such that
each of the sublists defines a single coupling between the spin spaces. If
there are N coupled angular momentum spaces, that is ``jn`` has N elements,
then there must be N-1 sublists. Each of these sublists making up the
``jcoupling`` parameter have length 3. The first two elements are the
indices of the product spaces that are considered to be coupled together.
For example, if we want to couple `j_1` and `j_4`, the indices would be 1
and 4. If a state has already been coupled, it is referenced by the
smallest index that is coupled, so if `j_2` and `j_4` has already been
coupled to some `j_{24}`, then this value can be coupled by referencing it
with index 2. The final element of the sublist is the quantum number of the
coupled state. So putting everything together, into a valid sublist for
``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
with quantum number `j_{12}` with the value ``j12``, the sublist would be
``(1,2,j12)``, N-1 of these sublists are used in the list for
``jcoupling``.
Note the ``jcoupling`` parameter is optional, if it is not specified, the
default coupling is taken. This default value is to coupled the spaces in
order and take the quantum number of the coupling to be the maximum value.
For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
`j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
`j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
correspond to this is:
``((1,2,j1+j2),(1,3,j1+j2+j3))``
Parameters
==========
args : tuple
The arguments that must be passed are ``j``, ``m``, ``jn``, and
``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
value is the eigenvalue of the Jz spin operator. The ``jn`` list are
the j values of argular momentum spaces coupled together. The
``jcoupling`` parameter is an optional parameter defining how the spaces
are coupled together. See the above description for how these coupling
parameters are defined.
Examples
========
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKetCoupled
>>> from sympy import symbols
>>> JzKetCoupled(1, 0, (1, 1))
|1,0,j1=1,j2=1>
>>> j, m, j1, j2 = symbols('j m j1 j2')
>>> JzKetCoupled(j, m, (j1, j2))
|j,m,j1=j1,j2=j2>
Defining coupled spin states for more than 2 coupled spaces with various
coupling parameters:
>>> JzKetCoupled(2, 1, (1, 1, 1))
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
|2,1,j1=1,j2=1,j3=1,j(2,3)=1>
Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKetCoupled
>>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
|1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
The rewrite method can be used to convert a coupled state to an uncoupled
state. This is done by passing coupled=False to the rewrite function:
>>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
-sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx
>>> from sympy import S
>>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
Matrix([
[ 0],
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
See Also
========
JzKet: Normal spin eigenstates
uncouple: Uncoupling of coupling spin states
couple: Coupling of uncoupled spin states
"""
@classmethod
def dual_class(self):
return JzBraCoupled
@classmethod
def uncoupled_class(self):
return JzKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(**options)
class JzBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jz.
See the JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JzKetCoupled
@classmethod
def uncoupled_class(self):
return JzBra
#-----------------------------------------------------------------------------
# Coupling/uncoupling
#-----------------------------------------------------------------------------
def couple(expr, jcoupling_list=None):
""" Couple a tensor product of spin states
This function can be used to couple an uncoupled tensor product of spin
states. All of the eigenstates to be coupled must be of the same class. It
will return a linear combination of eigenstates that are subclasses of
CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
coefficients.
Parameters
==========
expr : Expr
An expression involving TensorProducts of spin states to be coupled.
Each state must be a subclass of SpinState and they all must be the
same class.
jcoupling_list : list or tuple
Elements of this list are sub-lists of length 2 specifying the order of
the coupling of the spin spaces. The length of this must be N-1, where N
is the number of states in the tensor product to be coupled. The
elements of this sublist are the same as the first two elements of each
sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
parameter is not specified, the default value is taken, which couples
the first and second product basis spaces, then couples this new coupled
space to the third product space, etc
Examples
========
Couple a tensor product of numerical states for two spaces:
>>> from sympy.physics.quantum.spin import JzKet, couple
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
-sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
Numerical coupling of three spaces using the default coupling method, i.e.
first and second spaces couple, then this couples to the third space:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
Perform this same coupling, but we define the coupling to first couple
the first and third spaces:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
Couple a tensor product of symbolic states:
>>> from sympy import symbols
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
"""
a = expr.atoms(TensorProduct)
for tp in a:
# Allow other tensor products to be in expression
if not all([ isinstance(state, SpinState) for state in tp.args]):
continue
# If tensor product has all spin states, raise error for invalid tensor product state
if not all([state.__class__ is tp.args[0].__class__ for state in tp.args]):
raise TypeError('All states must be the same basis')
expr = expr.subs(tp, _couple(tp, jcoupling_list))
return expr
def _couple(tp, jcoupling_list):
states = tp.args
coupled_evect = states[0].coupled_class()
# Define default coupling if none is specified
if jcoupling_list is None:
jcoupling_list = []
for n in range(1, len(states)):
jcoupling_list.append( (1, n + 1) )
# Check jcoupling_list valid
if not len(jcoupling_list) == len(states) - 1:
raise TypeError('jcoupling_list must be length %d, got %d' %
(len(states) - 1, len(jcoupling_list)))
if not all( len(coupling) == 2 for coupling in jcoupling_list):
raise ValueError('Each coupling must define 2 spaces')
if any([n1 == n2 for n1, n2 in jcoupling_list]):
raise ValueError('Spin spaces cannot couple to themselves')
if all([sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list]):
j_test = [0]*len(states)
for n1, n2 in jcoupling_list:
if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
j_test[max(n1, n2) - 1] = -1
# j values of states to be coupled together
jn = [state.j for state in states]
mn = [state.m for state in states]
# Create coupling_list, which defines all the couplings between all
# the spaces from jcoupling_list
coupling_list = []
n_list = [ [i + 1] for i in range(len(states)) ]
for j_coupling in jcoupling_list:
# Least n for all j_n which is coupled as first and second spaces
n1, n2 = j_coupling
# List of all n's coupled in first and second spaces
j1_n = list(n_list[n1 - 1])
j2_n = list(n_list[n2 - 1])
coupling_list.append( (j1_n, j2_n) )
# Set new j_n to be coupling of all j_n in both first and second spaces
n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
if all(state.j.is_number and state.m.is_number for state in states):
# Numerical coupling
# Iterate over difference between maximum possible j value of each coupling and the actual value
diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
coupling[1] ] ) for coupling in coupling_list ]
result = []
for diff in range(diff_max[-1] + 1):
# Determine available configurations
n = len(coupling_list)
tot = binomial(diff + n - 1, diff)
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
# Skip the configuration if non-physical
# This is a lazy check for physical states given the loose restrictions of diff_max
if any( [ d > m for d, m in zip(diff_list, diff_max) ] ):
continue
# Determine term
cg_terms = []
coupled_j = list(jn)
jcoupling = []
for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
j3 = j1 + j2 - coupling_diff
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
# Better checks that state is physical
if any([ abs(term[5]) > term[4] for term in cg_terms ]):
continue
if any([ term[0] + term[2] < term[4] for term in cg_terms ]):
continue
if any([ abs(term[0] - term[2]) > term[4] for term in cg_terms ]):
continue
coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
cg_terms = []
jcoupling = []
sum_terms = []
coupled_j = list(jn)
for j1_n, j2_n in coupling_list:
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
if len(j1_n + j2_n) == len(states):
j3 = symbols('j')
else:
j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
j3 = symbols(j3_name)
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
sum_terms.append((j3, m3, j1 + j2))
coeff = Mul( *[ CG(*term) for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
return Sum(coeff*state, *sum_terms)
def uncouple(expr, jn=None, jcoupling_list=None):
""" Uncouple a coupled spin state
Gives the uncoupled representation of a coupled spin state. Arguments must
be either a spin state that is a subclass of CoupledSpinState or a spin
state that is a subclass of SpinState and an array giving the j values
of the spaces that are to be coupled
Parameters
==========
expr : Expr
The expression containing states that are to be coupled. If the states
are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
must be defined. If the states are a subclass of CoupledSpinState,
``jn`` and ``jcoupling`` will be taken from the state.
jn : list or tuple
The list of the j-values that are coupled. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jn`` parameter of JzKetCoupled.
jcoupling_list : list or tuple
The list defining how the j-values are coupled together. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
Examples
========
Uncouple a numerical state using a CoupledSpinState state:
>>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
>>> from sympy import S
>>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Perform the same calculation using a SpinState state:
>>> from sympy.physics.quantum.spin import JzKet
>>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
>>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Perform the same calculation using a SpinState state:
>>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Uncouple a symbolic state using a CoupledSpinState state:
>>> from sympy import symbols
>>> j,m,j1,j2 = symbols('j m j1 j2')
>>> uncouple(JzKetCoupled(j, m, (j1, j2)))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
Perform the same calculation using a SpinState state
>>> uncouple(JzKet(j, m), (j1, j2))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
"""
a = expr.atoms(SpinState)
for state in a:
expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
return expr
def _uncouple(state, jn, jcoupling_list):
if isinstance(state, CoupledSpinState):
jn = state.jn
coupled_n = state.coupled_n
coupled_jn = state.coupled_jn
evect = state.uncoupled_class()
elif isinstance(state, SpinState):
if jn is None:
raise ValueError("Must specify j-values for coupled state")
if not (isinstance(jn, list) or isinstance(jn, tuple)):
raise TypeError("jn must be list or tuple")
if jcoupling_list is None:
# Use default
jcoupling_list = []
for i in range(1, len(jn)):
jcoupling_list.append(
(1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
if not (isinstance(jcoupling_list, list) or isinstance(jcoupling_list, tuple)):
raise TypeError("jcoupling must be a list or tuple")
if not len(jcoupling_list) == len(jn) - 1:
raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
evect = state.__class__
else:
raise TypeError("state must be a spin state")
j = state.j
m = state.m
coupling_list = []
j_list = list(jn)
# Create coupling, which defines all the couplings between all the spaces
for j3, (n1, n2) in zip(coupled_jn, coupled_n):
# j's which are coupled as first and second spaces
j1 = j_list[n1[0] - 1]
j2 = j_list[n2[0] - 1]
# Build coupling list
coupling_list.append( (n1, n2, j1, j2, j3) )
# Set new value in j_list
j_list[min(n1 + n2) - 1] = j3
if j.is_number and m.is_number:
diff_max = [ 2*x for x in jn ]
diff = Add(*jn) - m
n = len(jn)
tot = binomial(diff + n - 1, diff)
result = []
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
if any( [ d > p for d, p in zip(diff_list, diff_max) ] ):
continue
cg_terms = []
for coupling in coupling_list:
j1_n, j2_n, j1, j2, j3 = coupling
m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
state = TensorProduct(
*[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
m_str = "m1:%d" % (len(jn) + 1)
mvals = symbols(m_str)
cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
return Sum(cg_coeff*state, *sum_terms)
def _confignum_to_difflist(config_num, diff, list_len):
# Determines configuration of diffs into list_len number of slots
diff_list = []
for n in range(list_len):
prev_diff = diff
# Number of spots after current one
rem_spots = list_len - n - 1
# Number of configurations of distributing diff among the remaining spots
rem_configs = binomial(diff + rem_spots - 1, diff)
while config_num >= rem_configs:
config_num -= rem_configs
diff -= 1
rem_configs = binomial(diff + rem_spots - 1, diff)
diff_list.append(prev_diff - diff)
return diff_list
|
4535887b8cd1bbc654e7206cfe5e16b5ab8f5a4495881eab7aef979e2b1b2c82 | from sympy import cos, exp, expand, I, Matrix, pi, S, sin, sqrt, Sum, symbols, Rational
from sympy.abc import alpha, beta, gamma, j, m
from sympy.physics.quantum import hbar, represent, Commutator, InnerProduct
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.cg import CG
from sympy.physics.quantum.spin import (
Jx, Jy, Jz, Jplus, Jminus, J2,
JxBra, JyBra, JzBra,
JxKet, JyKet, JzKet,
JxKetCoupled, JyKetCoupled, JzKetCoupled,
couple, uncouple,
Rotation, WignerD
)
from sympy.testing.pytest import raises, slow
j1, j2, j3, j4, m1, m2, m3, m4 = symbols('j1:5 m1:5')
j12, j13, j24, j34, j123, j134, mi, mi1, mp = symbols(
'j12 j13 j24 j34 j123 j134 mi mi1 mp')
def test_represent_spin_operators():
assert represent(Jx) == hbar*Matrix([[0, 1], [1, 0]])/2
assert represent(
Jx, j=1) == hbar*sqrt(2)*Matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])/2
assert represent(Jy) == hbar*I*Matrix([[0, -1], [1, 0]])/2
assert represent(Jy, j=1) == hbar*I*sqrt(2)*Matrix([[0, -1, 0], [1,
0, -1], [0, 1, 0]])/2
assert represent(Jz) == hbar*Matrix([[1, 0], [0, -1]])/2
assert represent(
Jz, j=1) == hbar*Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]])
def test_represent_spin_states():
# Jx basis
assert represent(JxKet(S.Half, S.Half), basis=Jx) == Matrix([1, 0])
assert represent(JxKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, 1])
assert represent(JxKet(1, 1), basis=Jx) == Matrix([1, 0, 0])
assert represent(JxKet(1, 0), basis=Jx) == Matrix([0, 1, 0])
assert represent(JxKet(1, -1), basis=Jx) == Matrix([0, 0, 1])
assert represent(
JyKet(S.Half, S.Half), basis=Jx) == Matrix([exp(-I*pi/4), 0])
assert represent(
JyKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, exp(I*pi/4)])
assert represent(JyKet(1, 1), basis=Jx) == Matrix([-I, 0, 0])
assert represent(JyKet(1, 0), basis=Jx) == Matrix([0, 1, 0])
assert represent(JyKet(1, -1), basis=Jx) == Matrix([0, 0, I])
assert represent(
JzKet(S.Half, S.Half), basis=Jx) == sqrt(2)*Matrix([-1, 1])/2
assert represent(
JzKet(S.Half, Rational(-1, 2)), basis=Jx) == sqrt(2)*Matrix([-1, -1])/2
assert represent(JzKet(1, 1), basis=Jx) == Matrix([1, -sqrt(2), 1])/2
assert represent(JzKet(1, 0), basis=Jx) == sqrt(2)*Matrix([1, 0, -1])/2
assert represent(JzKet(1, -1), basis=Jx) == Matrix([1, sqrt(2), 1])/2
# Jy basis
assert represent(
JxKet(S.Half, S.Half), basis=Jy) == Matrix([exp(I*pi*Rational(-3, 4)), 0])
assert represent(
JxKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, exp(I*pi*Rational(3, 4))])
assert represent(JxKet(1, 1), basis=Jy) == Matrix([I, 0, 0])
assert represent(JxKet(1, 0), basis=Jy) == Matrix([0, 1, 0])
assert represent(JxKet(1, -1), basis=Jy) == Matrix([0, 0, -I])
assert represent(JyKet(S.Half, S.Half), basis=Jy) == Matrix([1, 0])
assert represent(JyKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, 1])
assert represent(JyKet(1, 1), basis=Jy) == Matrix([1, 0, 0])
assert represent(JyKet(1, 0), basis=Jy) == Matrix([0, 1, 0])
assert represent(JyKet(1, -1), basis=Jy) == Matrix([0, 0, 1])
assert represent(
JzKet(S.Half, S.Half), basis=Jy) == sqrt(2)*Matrix([-1, I])/2
assert represent(
JzKet(S.Half, Rational(-1, 2)), basis=Jy) == sqrt(2)*Matrix([I, -1])/2
assert represent(JzKet(1, 1), basis=Jy) == Matrix([1, -I*sqrt(2), -1])/2
assert represent(
JzKet(1, 0), basis=Jy) == Matrix([-sqrt(2)*I, 0, -sqrt(2)*I])/2
assert represent(JzKet(1, -1), basis=Jy) == Matrix([-1, -sqrt(2)*I, 1])/2
# Jz basis
assert represent(
JxKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([1, 1])/2
assert represent(
JxKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-1, 1])/2
assert represent(JxKet(1, 1), basis=Jz) == Matrix([1, sqrt(2), 1])/2
assert represent(JxKet(1, 0), basis=Jz) == sqrt(2)*Matrix([-1, 0, 1])/2
assert represent(JxKet(1, -1), basis=Jz) == Matrix([1, -sqrt(2), 1])/2
assert represent(
JyKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([-1, -I])/2
assert represent(
JyKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-I, -1])/2
assert represent(JyKet(1, 1), basis=Jz) == Matrix([1, sqrt(2)*I, -1])/2
assert represent(JyKet(1, 0), basis=Jz) == sqrt(2)*Matrix([I, 0, I])/2
assert represent(JyKet(1, -1), basis=Jz) == Matrix([-1, sqrt(2)*I, 1])/2
assert represent(JzKet(S.Half, S.Half), basis=Jz) == Matrix([1, 0])
assert represent(JzKet(S.Half, Rational(-1, 2)), basis=Jz) == Matrix([0, 1])
assert represent(JzKet(1, 1), basis=Jz) == Matrix([1, 0, 0])
assert represent(JzKet(1, 0), basis=Jz) == Matrix([0, 1, 0])
assert represent(JzKet(1, -1), basis=Jz) == Matrix([0, 0, 1])
def test_represent_uncoupled_states():
# Jx basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jx) == \
Matrix([-I, 0, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jx) == \
Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([S.Half, S.Half, Rational(-1, 2), Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jx) == \
Matrix([S.Half, Rational(-1, 2), S.Half, Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([S.Half, S.Half, S.Half, S.Half])
# Jy basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jy) == \
Matrix([I, 0, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jy) == \
Matrix([S.Half, -I/2, -I/2, Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([-I/2, S.Half, Rational(-1, 2), -I/2])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jy) == \
Matrix([-I/2, Rational(-1, 2), S.Half, -I/2])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([Rational(-1, 2), -I/2, -I/2, S.Half])
# Jz basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jz) == \
Matrix([S.Half, S.Half, S.Half, S.Half])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([Rational(-1, 2), S.Half, Rational(-1, 2), S.Half])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jz) == \
Matrix([Rational(-1, 2), Rational(-1, 2), S.Half, S.Half])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jz) == \
Matrix([S.Half, I/2, I/2, Rational(-1, 2)])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([I/2, S.Half, Rational(-1, 2), I/2])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jz) == \
Matrix([I/2, Rational(-1, 2), S.Half, I/2])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([Rational(-1, 2), I/2, I/2, S.Half])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([0, 0, 0, 1])
def test_represent_coupled_states():
# Jx basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, -I, 0, 0])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, S.Half, -sqrt(2)/2, S.Half])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, sqrt(2)/2, 0, -sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, S.Half, sqrt(2)/2, S.Half])
# Jy basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, I, 0, 0])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, S.Half, -I*sqrt(2)/2, Rational(-1, 2)])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, -I*sqrt(2)/2, 0, -I*sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, Rational(-1, 2), -I*sqrt(2)/2, S.Half])
# Jz basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, sqrt(2)/2, S.Half])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, -sqrt(2)/2, 0, sqrt(2)/2])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, -sqrt(2)/2, S.Half])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, I*sqrt(2)/2, Rational(-1, 2)])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, I*sqrt(2)/2, 0, I*sqrt(2)/2])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, Rational(-1, 2), I*sqrt(2)/2, S.Half])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 0, 1])
def test_represent_rotation():
assert represent(Rotation(0, pi/2, 0)) == \
Matrix(
[[WignerD(
S(
1)/2, S(
1)/2, S(
1)/2, 0, pi/2, 0), WignerD(
S.Half, S.Half, Rational(-1, 2), 0, pi/2, 0)],
[WignerD(S.Half, Rational(-1, 2), S.Half, 0, pi/2, 0), WignerD(S.Half, Rational(-1, 2), Rational(-1, 2), 0, pi/2, 0)]])
assert represent(Rotation(0, pi/2, 0), doit=True) == \
Matrix([[sqrt(2)/2, -sqrt(2)/2],
[sqrt(2)/2, sqrt(2)/2]])
def test_rewrite_same():
# Rewrite to same basis
assert JxBra(1, 1).rewrite('Jx') == JxBra(1, 1)
assert JxBra(j, m).rewrite('Jx') == JxBra(j, m)
assert JxKet(1, 1).rewrite('Jx') == JxKet(1, 1)
assert JxKet(j, m).rewrite('Jx') == JxKet(j, m)
def test_rewrite_Bra():
# Numerical
assert JxBra(1, 1).rewrite('Jy') == -I*JyBra(1, 1)
assert JxBra(1, 0).rewrite('Jy') == JyBra(1, 0)
assert JxBra(1, -1).rewrite('Jy') == I*JyBra(1, -1)
assert JxBra(1, 1).rewrite(
'Jz') == JzBra(1, 1)/2 + JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2
assert JxBra(
1, 0).rewrite('Jz') == -sqrt(2)*JzBra(1, 1)/2 + sqrt(2)*JzBra(1, -1)/2
assert JxBra(1, -1).rewrite(
'Jz') == JzBra(1, 1)/2 - JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2
assert JyBra(1, 1).rewrite('Jx') == I*JxBra(1, 1)
assert JyBra(1, 0).rewrite('Jx') == JxBra(1, 0)
assert JyBra(1, -1).rewrite('Jx') == -I*JxBra(1, -1)
assert JyBra(1, 1).rewrite(
'Jz') == JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 - JzBra(1, -1)/2
assert JyBra(1, 0).rewrite(
'Jz') == -sqrt(2)*I*JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, -1)/2
assert JyBra(1, -1).rewrite(
'Jz') == -JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 + JzBra(1, -1)/2
assert JzBra(1, 1).rewrite(
'Jx') == JxBra(1, 1)/2 - sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2
assert JzBra(
1, 0).rewrite('Jx') == sqrt(2)*JxBra(1, 1)/2 - sqrt(2)*JxBra(1, -1)/2
assert JzBra(1, -1).rewrite(
'Jx') == JxBra(1, 1)/2 + sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2
assert JzBra(1, 1).rewrite(
'Jy') == JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 - JyBra(1, -1)/2
assert JzBra(1, 0).rewrite(
'Jy') == sqrt(2)*I*JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, -1)/2
assert JzBra(1, -1).rewrite(
'Jy') == -JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 + JyBra(1, -1)/2
# Symbolic
assert JxBra(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyBra(j, mi), (mi, -j, j))
assert JxBra(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, 0, pi/2, 0) * JzBra(j, mi), (mi, -j, j))
assert JyBra(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 0, pi/2) * JxBra(j, mi), (mi, -j, j))
assert JyBra(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyBra(j, mi), (mi, -j, j))
def test_rewrite_Ket():
# Numerical
assert JxKet(1, 1).rewrite('Jy') == I*JyKet(1, 1)
assert JxKet(1, 0).rewrite('Jy') == JyKet(1, 0)
assert JxKet(1, -1).rewrite('Jy') == -I*JyKet(1, -1)
assert JxKet(1, 1).rewrite(
'Jz') == JzKet(1, 1)/2 + JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2
assert JxKet(
1, 0).rewrite('Jz') == -sqrt(2)*JzKet(1, 1)/2 + sqrt(2)*JzKet(1, -1)/2
assert JxKet(1, -1).rewrite(
'Jz') == JzKet(1, 1)/2 - JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2
assert JyKet(1, 1).rewrite('Jx') == -I*JxKet(1, 1)
assert JyKet(1, 0).rewrite('Jx') == JxKet(1, 0)
assert JyKet(1, -1).rewrite('Jx') == I*JxKet(1, -1)
assert JyKet(1, 1).rewrite(
'Jz') == JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 - JzKet(1, -1)/2
assert JyKet(1, 0).rewrite(
'Jz') == sqrt(2)*I*JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, -1)/2
assert JyKet(1, -1).rewrite(
'Jz') == -JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 + JzKet(1, -1)/2
assert JzKet(1, 1).rewrite(
'Jx') == JxKet(1, 1)/2 - sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2
assert JzKet(
1, 0).rewrite('Jx') == sqrt(2)*JxKet(1, 1)/2 - sqrt(2)*JxKet(1, -1)/2
assert JzKet(1, -1).rewrite(
'Jx') == JxKet(1, 1)/2 + sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2
assert JzKet(1, 1).rewrite(
'Jy') == JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 - JyKet(1, -1)/2
assert JzKet(1, 0).rewrite(
'Jy') == -sqrt(2)*I*JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, -1)/2
assert JzKet(1, -1).rewrite(
'Jy') == -JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 + JyKet(1, -1)/2
# Symbolic
assert JxKet(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKet(j, mi), (mi, -j, j))
assert JxKet(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, 0, pi/2, 0) * JzKet(j, mi), (mi, -j, j))
assert JyKet(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 0, pi/2) * JxKet(j, mi), (mi, -j, j))
assert JyKet(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi), (mi, -j, j))
def test_rewrite_uncoupled_state():
# Numerical
assert TensorProduct(JyKet(1, 1), JxKet(
1, 1)).rewrite('Jx') == -I*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert TensorProduct(JyKet(1, 0), JxKet(
1, 1)).rewrite('Jx') == TensorProduct(JxKet(1, 0), JxKet(1, 1))
assert TensorProduct(JyKet(1, -1), JxKet(
1, 1)).rewrite('Jx') == I*TensorProduct(JxKet(1, -1), JxKet(1, 1))
assert TensorProduct(JzKet(1, 1), JxKet(1, 1)).rewrite('Jx') == \
TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 - sqrt(2)*TensorProduct(JxKet(
1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JzKet(1, 0), JxKet(1, 1)).rewrite('Jx') == \
-sqrt(2)*TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt(
2)*TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JzKet(1, -1), JxKet(1, 1)).rewrite('Jx') == \
TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JxKet(1, 1), JyKet(
1, 1)).rewrite('Jy') == I*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert TensorProduct(JxKet(1, 0), JyKet(
1, 1)).rewrite('Jy') == TensorProduct(JyKet(1, 0), JyKet(1, 1))
assert TensorProduct(JxKet(1, -1), JyKet(
1, 1)).rewrite('Jy') == -I*TensorProduct(JyKet(1, -1), JyKet(1, 1))
assert TensorProduct(JzKet(1, 1), JyKet(1, 1)).rewrite('Jy') == \
-TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 + TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JzKet(1, 0), JyKet(1, 1)).rewrite('Jy') == \
-sqrt(2)*I*TensorProduct(JyKet(1, -1), JyKet(
1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JzKet(1, -1), JyKet(1, 1)).rewrite('Jy') == \
TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 - TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JxKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JxKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(
1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JxKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \
-TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \
sqrt(2)*I*TensorProduct(JzKet(1, -1), JzKet(
1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 - TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
# Symbolic
assert TensorProduct(JyKet(j1, m1), JxKet(j2, m2)).rewrite('Jy') == \
TensorProduct(JyKet(j1, m1), Sum(
WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * JyKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JzKet(j1, m1), JxKet(j2, m2)).rewrite('Jz') == \
TensorProduct(JzKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, pi/2, 0) * JzKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JxKet(j1, m1), JyKet(j2, m2)).rewrite('Jx') == \
TensorProduct(JxKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, 0, pi/2) * JxKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JzKet(j1, m1), JyKet(j2, m2)).rewrite('Jz') == \
TensorProduct(JzKet(j1, m1), Sum(WignerD(
j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JxKet(j1, m1), JzKet(j2, m2)).rewrite('Jx') == \
TensorProduct(JxKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JyKet(j1, m1), JzKet(j2, m2)).rewrite('Jy') == \
TensorProduct(JyKet(j1, m1), Sum(WignerD(
j2, mi, m2, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi), (mi, -j2, j2)))
def test_rewrite_coupled_state():
# Numerical
assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S.Half, S.Half))
assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \
-I*JxKetCoupled(1, 1, (S.Half, S.Half))
assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 0, (S.Half, S.Half))
assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \
I*JxKetCoupled(1, -1, (S.Half, S.Half))
assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S.Half, S.Half))
assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JxKetCoupled(1, 0, (
S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \
sqrt(2)*JxKetCoupled(1, 1, (S(
1)/2, S.Half))/2 - sqrt(2)*JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JxKetCoupled(1, 0, (
S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S.Half, S.Half))
assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \
I*JyKetCoupled(1, 1, (S.Half, S.Half))
assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(1, 0, (S.Half, S.Half))
assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \
-I*JyKetCoupled(1, -1, (S.Half, S.Half))
assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S.Half, S.Half))
assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (
S.Half, S.Half))/2 - JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \
-I*sqrt(2)*JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(
2)*JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \
-JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (S.Half, S.Half))/2 + JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S.Half, S.Half))
assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \
-sqrt(2)*JzKetCoupled(1, 1, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S.Half, S.Half))
assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 - JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \
I*sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(
2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \
-JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
# Symbolic
assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \
Sum(WignerD(j, mi, m, 0, 0, pi/2) * JxKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \
Sum(WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKetCoupled(j,
mi, (j1, j2)), (mi, -j, j))
assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \
Sum(WignerD(j, mi, m, 0, pi/2, 0) * JzKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKetCoupled(
j, mi, (j1, j2)), (mi, -j, j))
def test_innerproducts_of_rewritten_states():
# Numerical
assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JzBra(1, 1)*JzKet(1, 1).rewrite('Jy')).doit() == 1
assert qapply(JzBra(1, 0)*JzKet(1, 0).rewrite('Jy')).doit() == 1
assert qapply(JzBra(1, -1)*JzKet(1, -1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jz')) == 0
assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jz')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jz')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jy')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jy')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jz')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jx')) == 0
assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jz')) == 0
assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jx')) == 0
assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jy')) == 0
assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jy')).doit() == 0
def test_uncouple_2_coupled_states():
# j1=1/2, j2=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) )))
# j1=1, j2=1
assert TensorProduct(JzKet(1, 1), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, 1), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, 1), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, -1)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, -1)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, -1)) )))
def test_uncouple_3_coupled_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/
2), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
# Coupling j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/
2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
@slow
def test_uncouple_4_coupled_states():
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
# Couple j1+j3=j13, j2+j4=j24, j13+j24=j
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
def test_uncouple_2_coupled_states_numerical():
# j1=1/2, j2=1/2
assert uncouple(JzKetCoupled(0, 0, (S.Half, S.Half))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half))) == \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))
# j1=1, j2=1/2
assert uncouple(JzKetCoupled(S.Half, S.Half, (1, S.Half))) == \
-sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 - \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half))) == \
TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))) == \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half))) == \
TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2)))
# j1=1, j2=1
assert uncouple(JzKetCoupled(0, 0, (1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/3
assert uncouple(JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 - \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(1, 0, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(1, -1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 2, (1, 1))) == \
TensorProduct(JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(2, 1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(2, 0, (1, 1))) == \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/6
assert uncouple(JzKetCoupled(2, -1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 + \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, -2, (1, 1))) == \
TensorProduct(JzKet(1, -1), JzKet(1, -1))
def test_uncouple_3_coupled_states_numerical():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(3)*TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half))) == \
TensorProduct(JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))
# j1=1/2, j2=1/2, j3=1
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1))) == \
TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1))) == \
TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2
# j1=1/2, j2=1, j3=1
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/5 + \
sqrt(5)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1))) == \
-sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 - \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1))) == \
-4*sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 - \
2*sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1))) == \
-sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
2*sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 - \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
4*sqrt(5)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1))) == \
-sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/2
assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3
# j1=1, j2=1, j3=1
assert uncouple(JzKetCoupled(3, 3, (1, 1, 1))) == \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (1, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (1, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (1, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(3, -3, (1, 1, 1))) == \
TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (1, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(2, 1, (1, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, 0, (1, 1, 1))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (1, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -2, (1, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(1, 1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 - \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(1, 0, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 - \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 - \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 - \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/30
# Defined j13
# j1=1/2, j2=1/2, j3=1, j13=1/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/3
# j1=1/2, j2=1, j3=1, j13=1/2
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/3
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-2*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \
2*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3
# j1=1, j2=1, j3=1, j13=1
assert uncouple(JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 + \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2
def test_uncouple_4_coupled_states_numerical():
# j1=1/2, j2=1/2, j3=1, j4=1, default coupling
assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, -S(
1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/4 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/30 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 - \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/20 - \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/30
# j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=1
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4
# j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=2
assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(S.Half, -S(
1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/6
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/30
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/5
def test_uncouple_symbolic():
assert uncouple(JzKetCoupled(j, m, (j1, j2) )) == \
Sum(CG(j1, m1, j2, m2, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2)),
(m1, -j1, j1), (m2, -j2, j2))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3) )) == \
Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) )) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4) )) == \
Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j1 + j2 + j3, m1 + m2 + m3) * CG(j1 + j2 + j3, m1 + m2 + m3, j4, m4, j, m) *
TensorProduct(
JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4), ((1, 3, j13), (2, 4, j24), (1, 2, j)) )) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j2, m2, j4, m4, j24, m2 + m4) * CG(j13, m1 + m3, j24, m2 + m4, j, m) *
TensorProduct(
JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4))
def test_couple_2_states():
# j1=1/2, j2=1/2
assert JzKetCoupled(0, 0, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half)) )))
assert JzKetCoupled(1, 1, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half)) )))
# j1=1, j2=1/2
assert JzKetCoupled(S.Half, S.Half, (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (1, S.Half)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) )))
# j1=1, j2=1
assert JzKetCoupled(0, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (1, 1)) )))
assert JzKetCoupled(1, 1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (1, 1)) )))
assert JzKetCoupled(1, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (1, 1)) )))
assert JzKetCoupled(1, -1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (1, 1)) )))
assert JzKetCoupled(2, 2, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (1, 1)) )))
assert JzKetCoupled(2, 1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (1, 1)) )))
assert JzKetCoupled(2, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (1, 1)) )))
assert JzKetCoupled(2, -1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (1, 1)) )))
assert JzKetCoupled(2, -2, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (1, 1)) )))
# j1=1/2, j2=3/2
assert JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) )))
def test_couple_3_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) )))
# j1=1/2, j2=1/2, j3=1
assert JzKetCoupled(0, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, 1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 2, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, -1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, -2, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, S.Half, 1)) )))
# Couple j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2, j13=0
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S(
1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S(
1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
# j1=1, j2=1/2, j3=1, j13=1
assert JzKetCoupled(S.Half, S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (
1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
def test_couple_4_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) )))
# j1=1/2, j2=1/2, j3=1/2, j4=1
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) )))
# Coupling j1+j3=j13, j2+j4=j24, j13+j24=j
# j1=1/2, j2=1/2, j3=1/2, j4=1/2, j13=1, j24=0
assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1/2, j3=1/2, j4=1, j13=1, j24=1/2
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) )), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1, j3=1/2, j4=1, j13=0, j24=1
assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1, j3=1/2, j4=1, j13=1, j24=1
assert JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 0)) ) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 0))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
def test_couple_2_states_numerical():
# j1=1/2, j2=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(1, 1, (S.Half, S.Half))
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(1, -1, (S.Half, S.Half))
# j1=1, j2=1/2
assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half))) == \
JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half))
assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + sqrt(
3)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))/3 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S(
1)/2))/3 + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half))
# j1=1, j2=1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(2, 2, (1, 1))
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(
1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 + sqrt(2)*JzKetCoupled(
1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(
1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0))) == \
-sqrt(3)*JzKetCoupled(
0, 0, (1, 1))/3 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(
1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 - sqrt(2)*JzKetCoupled(
1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(
1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(2, -2, (1, 1))
# j1=3/2, j2=1/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, S.Half))) == \
JzKetCoupled(2, 2, (Rational(3, 2), S.Half))
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(
1, 1, (Rational(3, 2), S.Half))/2 + JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, S.Half))) == \
-JzKetCoupled(1, 1, (S(
3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(1, -1, (S(
3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(1, -1, (Rational(3, 2), S.Half))/2 + \
JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(2, -2, (Rational(3, 2), S.Half))
def test_couple_3_states_numerical():
# Default coupling
# j1=1/2,j2=1/2,j3=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(Rational(3, 2), S(
3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(Rational(3, 2), -S(
3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) )
# j1=S.Half, j2=S.Half, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )
# j1=S.Half, j2=1, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(
Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))) == \
-2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))) == \
-2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(S(
5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )
# j1=1, j2=1, j3=1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(3, 3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))) == \
-JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))) == \
-sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/5
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))) == \
-JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(3, -3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )
# j1=S.Half, j2=S.Half, j3=Rational(3, 2)
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \
JzKetCoupled(Rational(5, 2), S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
2*sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
2*sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(
3)/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
JzKetCoupled(Rational(5, 2), -S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )
# Couple j1 to j3
# j1=1/2, j2=1/2, j3=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), S(
3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), -S(
3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) )
# j1=1/2, j2=1/2, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \
JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )
# j 1=1/2, j 2=1, j 3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(
Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(
5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )
# j1=1, 1, 1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(3, 3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/5
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(3, -3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )
# j1=1/2, j2=1/2, j3=3/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(5, 2), S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 + \
3*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 - \
3*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
-2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(15)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(
3)/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(5, 2), -S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )
def test_couple_4_states_numerical():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(2, 2, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 0), (1, 3, S.Half), (1, 4, 0)))/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, S.Half), (1, 4, 0)))/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 0), (1, 3, S.Half), (1, 4, 1)))/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, S.Half), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)))/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(2, -2, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )
# j1=S.Half, S.Half, S.Half, 1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )
# Couple j1 to j2, j3 to j4
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, 2, (S(
1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, -2, (S(
1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
# j1=S.Half, S.Half, S.Half, 1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )
def test_couple_symbolic():
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
Sum(CG(j1, m1, j2, m2, j, m1 + m2) * JzKetCoupled(j, m1 + m2, (
j1, j2)), (j, m1 + m2, j1 + j2))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3))) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j, m1 + m2 + m3) *
JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 2, j12), (1, 3, j)) ),
(j12, m1 + m2, j1 + j2), (j, m1 + m2 + m3, j12 + j3))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)), ((1, 3), (1, 2)) ) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m1 + m2 + m3) *
JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) ),
(j13, m1 + m3, j1 + j3), (j, m1 + m2 + m3, j13 + j2))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4))) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j123, m1 + m2 + m3) * CG(j123, m1 + m2 + m3, j4, m4, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 2, j12), (1, 3, j123), (1, 4, j)) ),
(j12, m1 + m2, j1 + j2), (j123, m1 + m2 + m3, j12 + j3), (j, m1 + m2 + m3 + m4, j123 + j4))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 2), (3, 4), (1, 3)) ) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j3, m3, j4, m4, j34, m3 + m4) * CG(j12, m1 + m2, j34, m3 + m4, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 2, j12), (3, 4, j34), (1, 3, j)) ),
(j12, m1 + m2, j1 + j2), (j34, m3 + m4, j3 + j4), (j, m1 + m2 + m3 + m4, j12 + j34))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 3), (1, 4), (1, 2)) ) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j4, m4, j134, m1 + m3 + m4) * CG(j134, m1 + m3 + m4, j2, m2, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 3, j13), (1, 4, j134), (1, 2, j)) ),
(j13, m1 + m3, j1 + j3), (j134, m1 + m3 + m4, j13 + j4), (j, m1 + m2 + m3 + m4, j134 + j2))
def test_innerproduct():
assert InnerProduct(JzBra(1, 1), JzKet(1, 1)).doit() == 1
assert InnerProduct(
JzBra(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))).doit() == 0
assert InnerProduct(JzBra(j, m), JzKet(j, m)).doit() == 1
assert InnerProduct(JzBra(1, 0), JyKet(1, 1)).doit() == I/sqrt(2)
assert InnerProduct(
JxBra(S.Half, S.Half), JzKet(S.Half, S.Half)).doit() == -sqrt(2)/2
assert InnerProduct(JyBra(1, 1), JzKet(1, 1)).doit() == S.Half
assert InnerProduct(JxBra(1, -1), JyKet(1, 1)).doit() == 0
def test_rotation_small_d():
# Symbolic tests
# j = 1/2
assert Rotation.d(S.Half, S.Half, S.Half, beta).doit() == cos(beta/2)
assert Rotation.d(S.Half, S.Half, Rational(-1, 2), beta).doit() == -sin(beta/2)
assert Rotation.d(S.Half, Rational(-1, 2), S.Half, beta).doit() == sin(beta/2)
assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), beta).doit() == cos(beta/2)
# j = 1
assert Rotation.d(1, 1, 1, beta).doit() == (1 + cos(beta))/2
assert Rotation.d(1, 1, 0, beta).doit() == -sin(beta)/sqrt(2)
assert Rotation.d(1, 1, -1, beta).doit() == (1 - cos(beta))/2
assert Rotation.d(1, 0, 1, beta).doit() == sin(beta)/sqrt(2)
assert Rotation.d(1, 0, 0, beta).doit() == cos(beta)
assert Rotation.d(1, 0, -1, beta).doit() == -sin(beta)/sqrt(2)
assert Rotation.d(1, -1, 1, beta).doit() == (1 - cos(beta))/2
assert Rotation.d(1, -1, 0, beta).doit() == sin(beta)/sqrt(2)
assert Rotation.d(1, -1, -1, beta).doit() == (1 + cos(beta))/2
# j = 3/2
assert Rotation.d(S(
3)/2, Rational(3, 2), Rational(3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, S.Half, beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, Rational(-3, 2), beta).doit() == (-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, S.Half, S.Half, beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, S.Half, Rational(-1, 2), beta).doit() == (sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
1)/2, Rational(-3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, S.Half, beta).doit() == (-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(-1, 2), beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(-3, 2), beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, Rational(-3, 2), Rational(3, 2), beta).doit() == (3*sin(beta/2) - sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, S.Half, beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, Rational(-3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4
# j = 2
assert Rotation.d(2, 2, 2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, 2, 1, beta).doit() == -((cos(beta) + 1)*sin(beta))/2
assert Rotation.d(2, 2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, 2, -1, beta).doit() == (cos(beta) - 1)*sin(beta)/2
assert Rotation.d(2, 2, -2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, 1, 2, beta).doit() == (cos(beta) + 1)*sin(beta)/2
assert Rotation.d(2, 1, 1, beta).doit() == (cos(beta) + cos(2*beta))/2
assert Rotation.d(2, 1, 0, beta).doit() == -sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 1, -1, beta).doit() == (cos(beta) - cos(2*beta))/2
assert Rotation.d(2, 1, -2, beta).doit() == (cos(beta) - 1)*sin(beta)/2
assert Rotation.d(2, 0, 2, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, 0, 1, beta).doit() == sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 0, 0, beta).doit() == (1 + 3*cos(2*beta))/4
assert Rotation.d(2, 0, -1, beta).doit() == -sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 0, -2, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, -1, 2, beta).doit() == (2*sin(beta) - sin(2*beta))/4
assert Rotation.d(2, -1, 1, beta).doit() == (cos(beta) - cos(2*beta))/2
assert Rotation.d(2, -1, 0, beta).doit() == sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, -1, -1, beta).doit() == (cos(beta) + cos(2*beta))/2
assert Rotation.d(2, -1, -2, beta).doit() == -((cos(beta) + 1)*sin(beta))/2
assert Rotation.d(2, -2, 2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, -2, 1, beta).doit() == (2*sin(beta) - sin(2*beta))/4
assert Rotation.d(2, -2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, -2, -1, beta).doit() == (cos(beta) + 1)*sin(beta)/2
assert Rotation.d(2, -2, -2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8
# Numerical tests
# j = 1/2
assert Rotation.d(S.Half, S.Half, S.Half, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S.Half, S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/2
assert Rotation.d(S.Half, Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), pi/2).doit() == sqrt(2)/2
# j = 1
assert Rotation.d(1, 1, 1, pi/2).doit() == S.Half
assert Rotation.d(1, 1, 0, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(1, 1, -1, pi/2).doit() == S.Half
assert Rotation.d(1, 0, 1, pi/2).doit() == sqrt(2)/2
assert Rotation.d(1, 0, 0, pi/2).doit() == 0
assert Rotation.d(1, 0, -1, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(1, -1, 1, pi/2).doit() == S.Half
assert Rotation.d(1, -1, 0, pi/2).doit() == sqrt(2)/2
assert Rotation.d(1, -1, -1, pi/2).doit() == S.Half
# j = 3/2
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), S.Half, pi/2).doit() == -sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), S.Half, S.Half, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(-3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2).doit() == -sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), S.Half, pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2).doit() == sqrt(2)/4
# j = 2
assert Rotation.d(2, 2, 2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, 2, 1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, 2, -1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 2, -2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, 1, 2, pi/2).doit() == S.Half
assert Rotation.d(2, 1, 1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 1, 0, pi/2).doit() == 0
assert Rotation.d(2, 1, -1, pi/2).doit() == S.Half
assert Rotation.d(2, 1, -2, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 0, 2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, 0, 1, pi/2).doit() == 0
assert Rotation.d(2, 0, 0, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 0, -1, pi/2).doit() == 0
assert Rotation.d(2, 0, -2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, -1, 2, pi/2).doit() == S.Half
assert Rotation.d(2, -1, 1, pi/2).doit() == S.Half
assert Rotation.d(2, -1, 0, pi/2).doit() == 0
assert Rotation.d(2, -1, -1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, -1, -2, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, -2, 2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, -2, 1, pi/2).doit() == S.Half
assert Rotation.d(2, -2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, -2, -1, pi/2).doit() == S.Half
assert Rotation.d(2, -2, -2, pi/2).doit() == Rational(1, 4)
def test_rotation_d():
# Symbolic tests
# j = 1/2
assert Rotation.D(S.Half, S.Half, S.Half, alpha, beta, gamma).doit() == \
cos(beta/2)*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S.Half, S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \
-sin(beta/2)*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S.Half, Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \
sin(beta/2)*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S.Half, Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
cos(beta/2)*exp(I*alpha/2)*exp(I*gamma/2)
# j = 1
assert Rotation.D(1, 1, 1, alpha, beta, gamma).doit() == \
(1 + cos(beta))/2*exp(-I*alpha)*exp(-I*gamma)
assert Rotation.D(1, 1, 0, alpha, beta, gamma).doit() == -sin(
beta)/sqrt(2)*exp(-I*alpha)
assert Rotation.D(1, 1, -1, alpha, beta, gamma).doit() == \
(1 - cos(beta))/2*exp(-I*alpha)*exp(I*gamma)
assert Rotation.D(1, 0, 1, alpha, beta, gamma).doit() == \
sin(beta)/sqrt(2)*exp(-I*gamma)
assert Rotation.D(1, 0, 0, alpha, beta, gamma).doit() == cos(beta)
assert Rotation.D(1, 0, -1, alpha, beta, gamma).doit() == \
-sin(beta)/sqrt(2)*exp(I*gamma)
assert Rotation.D(1, -1, 1, alpha, beta, gamma).doit() == \
(1 - cos(beta))/2*exp(I*alpha)*exp(-I*gamma)
assert Rotation.D(1, -1, 0, alpha, beta, gamma).doit() == \
sin(beta)/sqrt(2)*exp(I*alpha)
assert Rotation.D(1, -1, -1, alpha, beta, gamma).doit() == \
(1 + cos(beta))/2*exp(I*alpha)*exp(I*gamma)
# j = 3/2
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(3, 2), S.Half, alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
(-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), S.Half, Rational(3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), S.Half, S.Half, alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \
(sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), S.Half, Rational(-3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \
(-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
(3*sin(beta/2) - sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(-3, 2), S.Half, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(3, 2))
# j = 2
assert Rotation.D(2, 2, 2, alpha, beta, gamma).doit() == \
(3 + 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, 2, 1, alpha, beta, gamma).doit() == \
-((cos(beta) + 1)*exp(-2*I*alpha)*exp(-I*gamma)*sin(beta))/2
assert Rotation.D(2, 2, 0, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(-2*I*alpha)
assert Rotation.D(2, 2, -1, alpha, beta, gamma).doit() == \
(cos(beta) - 1)*sin(beta)/2*exp(-2*I*alpha)*exp(I*gamma)
assert Rotation.D(2, 2, -2, alpha, beta, gamma).doit() == \
(3 - 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, 1, 2, alpha, beta, gamma).doit() == \
(cos(beta) + 1)*sin(beta)/2*exp(-I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, 1, 1, alpha, beta, gamma).doit() == \
(cos(beta) + cos(2*beta))/2*exp(-I*alpha)*exp(-I*gamma)
assert Rotation.D(2, 1, 0, alpha, beta, gamma).doit() == -sqrt(6)* \
sin(2*beta)/4*exp(-I*alpha)
assert Rotation.D(2, 1, -1, alpha, beta, gamma).doit() == \
(cos(beta) - cos(2*beta))/2*exp(-I*alpha)*exp(I*gamma)
assert Rotation.D(2, 1, -2, alpha, beta, gamma).doit() == \
(cos(beta) - 1)*sin(beta)/2*exp(-I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, 0, 2, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(-2*I*gamma)
assert Rotation.D(2, 0, 1, alpha, beta, gamma).doit() == sqrt(6)* \
sin(2*beta)/4*exp(-I*gamma)
assert Rotation.D(
2, 0, 0, alpha, beta, gamma).doit() == (1 + 3*cos(2*beta))/4
assert Rotation.D(2, 0, -1, alpha, beta, gamma).doit() == -sqrt(6)* \
sin(2*beta)/4*exp(I*gamma)
assert Rotation.D(2, 0, -2, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(2*I*gamma)
assert Rotation.D(2, -1, 2, alpha, beta, gamma).doit() == \
(2*sin(beta) - sin(2*beta))/4*exp(I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, -1, 1, alpha, beta, gamma).doit() == \
(cos(beta) - cos(2*beta))/2*exp(I*alpha)*exp(-I*gamma)
assert Rotation.D(2, -1, 0, alpha, beta, gamma).doit() == sqrt(6)* \
sin(2*beta)/4*exp(I*alpha)
assert Rotation.D(2, -1, -1, alpha, beta, gamma).doit() == \
(cos(beta) + cos(2*beta))/2*exp(I*alpha)*exp(I*gamma)
assert Rotation.D(2, -1, -2, alpha, beta, gamma).doit() == \
-((cos(beta) + 1)*sin(beta))/2*exp(I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, -2, 2, alpha, beta, gamma).doit() == \
(3 - 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, -2, 1, alpha, beta, gamma).doit() == \
(2*sin(beta) - sin(2*beta))/4*exp(2*I*alpha)*exp(-I*gamma)
assert Rotation.D(2, -2, 0, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(2*I*alpha)
assert Rotation.D(2, -2, -1, alpha, beta, gamma).doit() == \
(cos(beta) + 1)*sin(beta)/2*exp(2*I*alpha)*exp(I*gamma)
assert Rotation.D(2, -2, -2, alpha, beta, gamma).doit() == \
(3 + 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(2*I*gamma)
# Numerical tests
# j = 1/2
assert Rotation.D(
S.Half, S.Half, S.Half, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(
S.Half, S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/2
assert Rotation.D(
S.Half, Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/2
assert Rotation.D(
S.Half, Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
# j = 1
assert Rotation.D(1, 1, 1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
assert Rotation.D(1, 1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
assert Rotation.D(1, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(1, 0, 1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(1, 0, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(1, 0, -1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(1, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(1, -1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
assert Rotation.D(1, -1, -1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
# j = 3/2
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
Rational(3, 2), S.Half, S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(-3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4
# j = 2
assert Rotation.D(2, 2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, 2, 1, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, 2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, 2, -1, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, 2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, 1, 2, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, 1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, 1, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, 1, -2, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, 0, 2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, 0, 1, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 0, 0, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
assert Rotation.D(2, 0, -1, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 0, -2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, -1, 2, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, -1, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, -1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, -1, -2, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, -2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, -2, 1, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, -2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, -2, -1, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, -2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
def test_wignerd():
assert Rotation.D(
j, m, mp, alpha, beta, gamma) == WignerD(j, m, mp, alpha, beta, gamma)
assert Rotation.d(j, m, mp, beta) == WignerD(j, m, mp, 0, beta, 0)
def test_wignerD():
i,j=symbols('i j')
assert Rotation.D(1, 1, 1, 0, 0, 0) == WignerD(1, 1, 1, 0, 0, 0)
assert Rotation.D(1, 1, 2, 0, 0, 0) == WignerD(1, 1, 2, 0, 0, 0)
assert Rotation.D(1, i**2 - j**2, i**2 - j**2, 0, 0, 0) == WignerD(1, i**2 - j**2, i**2 - j**2, 0, 0, 0)
assert Rotation.D(1, i, i, 0, 0, 0) == WignerD(1, i, i, 0, 0, 0)
assert Rotation.D(1, i, i+1, 0, 0, 0) == WignerD(1, i, i+1, 0, 0, 0)
assert Rotation.D(1, 0, 0, 0, 0, 0) == WignerD(1, 0, 0, 0, 0, 0)
def test_jplus():
assert Commutator(Jplus, Jminus).doit() == 2*hbar*Jz
assert Jplus.matrix_element(1, 1, 1, 1) == 0
assert Jplus.rewrite('xyz') == Jx + I*Jy
# Normal operators, normal states
# Numerical
assert qapply(Jplus*JxKet(1, 1)) == \
-hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1)
assert qapply(Jplus*JyKet(1, 1)) == \
hbar*sqrt(2)*JyKet(1, 0)/2 + I*hbar*JyKet(1, 1)
assert qapply(Jplus*JzKet(1, 1)) == 0
# Symbolic
assert qapply(Jplus*JxKet(j, m)) == \
Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JyKet(j, m)) == \
Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)
# Normal operators, coupled states
# Numerical
assert qapply(Jplus*JxKetCoupled(1, 1, (1, 1))) == -hbar*sqrt(2) * \
JxKetCoupled(1, 0, (1, 1))/2 + hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jplus*JyKetCoupled(1, 1, (1, 1))) == hbar*sqrt(2) * \
JyKetCoupled(1, 0, (1, 1))/2 + I*hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jplus*JzKet(1, 1)) == 0
# Symbolic
assert qapply(Jplus*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) *
Sum(
WignerD(
j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) *
JyKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 + \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(
TensorProduct(Jplus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))
# Symbolic
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar * sqrt(-mi**2 - mi + j1**2 + j1) * WignerD(j1, mi, m1, 0, pi/2, 0) *
Sum(WignerD(j1, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar * sqrt(-mi**2 - mi + j2**2 + j2) * WignerD(j2, mi, m2, 0, pi/2, 0) *
Sum(WignerD(j2, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar * sqrt(j1**2 + j1 - mi**2 - mi) * WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar * sqrt(j2**2 + j2 - mi**2 - mi) * WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))
def test_jminus():
assert qapply(Jminus*JzKet(1, -1)) == 0
assert Jminus.matrix_element(1, 0, 1, 1) == sqrt(2)*hbar
assert Jminus.rewrite('xyz') == Jx - I*Jy
# Normal operators, normal states
# Numerical
assert qapply(Jminus*JxKet(1, 1)) == \
hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1)
assert qapply(Jminus*JyKet(1, 1)) == \
hbar*sqrt(2)*JyKet(1, 0)/2 - hbar*I*JyKet(1, 1)
assert qapply(Jminus*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)
# Symbolic
assert qapply(Jminus*JxKet(j, m)) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JyKet(j, m)) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)
# Normal operators, coupled states
# Numerical
assert qapply(Jminus*JxKetCoupled(1, 1, (1, 1))) == \
hbar*sqrt(2)*JxKetCoupled(1, 0, (1, 1))/2 + \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jminus*JyKetCoupled(1, 1, (1, 1))) == \
hbar*sqrt(2)*JyKetCoupled(1, 0, (1, 1))/2 - \
hbar*I*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jminus*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))
# Symbolic
assert qapply(Jminus*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*
JyKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) - \
hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 - \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, -1))
assert qapply(TensorProduct(
1, Jminus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
# Symbolic
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, 0, pi/2, 0) *
Sum(WignerD(j1, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, 0, pi/2, 0) *
Sum(WignerD(j2, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))
def test_j2():
assert Commutator(J2, Jz).doit() == 0
assert J2.matrix_element(1, 1, 1, 1) == 2*hbar**2
# Normal operators, normal states
# Numerical
assert qapply(J2*JxKet(1, 1)) == 2*hbar**2*JxKet(1, 1)
assert qapply(J2*JyKet(1, 1)) == 2*hbar**2*JyKet(1, 1)
assert qapply(J2*JzKet(1, 1)) == 2*hbar**2*JzKet(1, 1)
# Symbolic
assert qapply(J2*JxKet(j, m)) == \
hbar**2*j**2*JxKet(j, m) + hbar**2*j*JxKet(j, m)
assert qapply(J2*JyKet(j, m)) == \
hbar**2*j**2*JyKet(j, m) + hbar**2*j*JyKet(j, m)
assert qapply(J2*JzKet(j, m)) == \
hbar**2*j**2*JzKet(j, m) + hbar**2*j*JzKet(j, m)
# Normal operators, coupled states
# Numerical
assert qapply(J2*JxKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JxKetCoupled(1, 1, (1, 1))
assert qapply(J2*JyKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JyKetCoupled(1, 1, (1, 1))
assert qapply(J2*JzKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JzKetCoupled(1, 1, (1, 1))
# Symbolic
assert qapply(J2*JxKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JxKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JxKetCoupled(j, m, (j1, j2))
assert qapply(J2*JyKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JyKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JyKetCoupled(j, m, (j1, j2))
assert qapply(J2*JzKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JzKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JzKetCoupled(j, m, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
# Symbolic
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
def test_jx():
assert Commutator(Jx, Jz).doit() == -I*hbar*Jy
assert Jx.rewrite('plusminus') == (Jminus + Jplus)/2
assert represent(Jx, basis=Jz, j=1) == (
represent(Jplus, basis=Jz, j=1) + represent(Jminus, basis=Jz, j=1))/2
# Normal operators, normal states
# Numerical
assert qapply(Jx*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jx*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jx*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)/2
# Symbolic
assert qapply(Jx*JxKet(j, m)) == hbar*m*JxKet(j, m)
assert qapply(Jx*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j,
mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)/2 + hbar*sqrt(j**2 +
j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jx*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jx*JxKetCoupled(j, m, (j1, j2))) == \
hbar*m*JxKetCoupled(j, m, (j1, j2))
assert qapply(Jx*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
2*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jx*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jx*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == 0
# Symbolic
assert qapply(Jx*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(Jx*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(Jx*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2
# Symbolic
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2) * Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2) * Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
def test_jy():
assert Commutator(Jy, Jz).doit() == I*hbar*Jx
assert Jy.rewrite('plusminus') == (Jplus - Jminus)/(2*I)
assert represent(Jy, basis=Jz) == (
represent(Jplus, basis=Jz) - represent(Jminus, basis=Jz))/(2*I)
# Normal operators, normal states
# Numerical
assert qapply(Jy*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jy*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jy*JzKet(1, 1)) == sqrt(2)*hbar*I*JzKet(1, 0)/2
# Symbolic
assert qapply(Jy*JxKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD(
j, mi1, mi, 0, 0, pi/2)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKet(j, m)) == hbar*m*JyKet(j, m)
assert qapply(Jy*JzKet(j, m)) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKet(
j, m + 1)/2 + hbar*I*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jy*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*I*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jy*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j, mi1, mi, 0, 0, pi/2)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKetCoupled(j, m, (j1, j2))) == \
hbar*m*JyKetCoupled(j, m, (j1, j2))
assert qapply(Jy*JzKetCoupled(j, m, (j1, j2))) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*I*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jy*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
2*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jy*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == 0
# Symbolic
assert qapply(Jy*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(Jy*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m1*TensorProduct(JyKet(j1, m1), JyKet(
j2, m2)) + hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(Jy*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*I*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \
-hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*I*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2
assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
-hbar*sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2
# Symbolic
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*I*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2
assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*I*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
def test_jz():
assert Commutator(Jz, Jminus).doit() == -hbar*Jminus
# Normal operators, normal states
# Numerical
assert qapply(Jz*JxKet(1, 1)) == -sqrt(2)*hbar*JxKet(1, 0)/2
assert qapply(Jz*JyKet(1, 1)) == -sqrt(2)*hbar*I*JyKet(1, 0)/2
assert qapply(Jz*JzKet(2, 1)) == hbar*JzKet(2, 1)
# Symbolic
assert qapply(Jz*JxKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j,
mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1,
mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JzKet(j, m)) == hbar*m*JzKet(j, m)
# Normal operators, coupled states
# Numerical
assert qapply(Jz*JxKetCoupled(1, 1, (1, 1))) == \
-sqrt(2)*hbar*JxKetCoupled(1, 0, (1, 1))/2
assert qapply(Jz*JyKetCoupled(1, 1, (1, 1))) == \
-sqrt(2)*hbar*I*JyKetCoupled(1, 0, (1, 1))/2
assert qapply(Jz*JzKetCoupled(1, 1, (1, 1))) == \
hbar*JzKetCoupled(1, 1, (1, 1))
# Symbolic
assert qapply(Jz*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JzKetCoupled(j, m, (j1, j2))) == \
hbar*m*JzKetCoupled(j, m, (j1, j2))
# Normal operators, uncoupled states
# Numerical
assert qapply(Jz*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 - \
sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2
assert qapply(Jz*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
-sqrt(2)*hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 - \
sqrt(2)*hbar*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2
assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
2*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 1))
assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
# Symbolic
assert qapply(Jz*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(Jz*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(Jz*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m1*TensorProduct(JzKet(j1, m1), JzKet(
j2, m2)) + hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
# Uncoupled Operators
# Numerical
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2
assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-sqrt(2)*I*hbar*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2
assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
sqrt(2)*I*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
-hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1))
# Symbolic
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
def test_rotation():
a, b, g = symbols('a b g')
j, m = symbols('j m')
#Uncoupled
answ = [JxKet(1,-1)/2 - sqrt(2)*JxKet(1,0)/2 + JxKet(1,1)/2 ,
JyKet(1,-1)/2 - sqrt(2)*JyKet(1,0)/2 + JyKet(1,1)/2 ,
JzKet(1,-1)/2 - sqrt(2)*JzKet(1,0)/2 + JzKet(1,1)/2]
fun = [state(1, 1) for state in (JxKet, JyKet, JzKet)]
for state in fun:
got = qapply(Rotation(0, pi/2, 0)*state)
assert got in answ
answ.remove(got)
assert not answ
arg = Rotation(a, b, g)*fun[0]
assert qapply(arg) == (-exp(-I*a)*exp(I*g)*cos(b)*JxKet(1,-1)/2 +
exp(-I*a)*exp(I*g)*JxKet(1,-1)/2 - sqrt(2)*exp(-I*a)*sin(b)*JxKet(1,0)/2 +
exp(-I*a)*exp(-I*g)*cos(b)*JxKet(1,1)/2 + exp(-I*a)*exp(-I*g)*JxKet(1,1)/2)
#dummy effective
assert str(qapply(Rotation(a, b, g)*JzKet(j, m), dummy=False)) == str(
qapply(Rotation(a, b, g)*JzKet(j, m), dummy=True)).replace('_','')
#Coupled
ans = [JxKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JxKetCoupled(1,0,(1,1))/2 +
JxKetCoupled(1,1,(1,1))/2 ,
JyKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JyKetCoupled(1,0,(1,1))/2 +
JyKetCoupled(1,1,(1,1))/2 ,
JzKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JzKetCoupled(1,0,(1,1))/2 +
JzKetCoupled(1,1,(1,1))/2]
fun = [state(1, 1, (1,1)) for state in (JxKetCoupled, JyKetCoupled, JzKetCoupled)]
for state in fun:
got = qapply(Rotation(0, pi/2, 0)*state)
assert got in ans
ans.remove(got)
assert not ans
arg = Rotation(a, b, g)*fun[0]
assert qapply(arg) == (
-exp(-I*a)*exp(I*g)*cos(b)*JxKetCoupled(1,-1,(1,1))/2 +
exp(-I*a)*exp(I*g)*JxKetCoupled(1,-1,(1,1))/2 -
sqrt(2)*exp(-I*a)*sin(b)*JxKetCoupled(1,0,(1,1))/2 +
exp(-I*a)*exp(-I*g)*cos(b)*JxKetCoupled(1,1,(1,1))/2 +
exp(-I*a)*exp(-I*g)*JxKetCoupled(1,1,(1,1))/2)
#dummy effective
assert str(qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=False)) == str(
qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=True)).replace('_','')
def test_jzket():
j, m = symbols('j m')
# j not integer or half integer
raises(ValueError, lambda: JzKet(Rational(2, 3), Rational(-1, 3)))
raises(ValueError, lambda: JzKet(Rational(2, 3), m))
# j < 0
raises(ValueError, lambda: JzKet(-1, 1))
raises(ValueError, lambda: JzKet(-1, m))
# m not integer or half integer
raises(ValueError, lambda: JzKet(j, Rational(-1, 3)))
# abs(m) > j
raises(ValueError, lambda: JzKet(1, 2))
raises(ValueError, lambda: JzKet(1, -2))
# j-m not integer
raises(ValueError, lambda: JzKet(1, S.Half))
def test_jzketcoupled():
j, m = symbols('j m')
# j not integer or half integer
raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), Rational(-1, 3), (1,)))
raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), m, (1,)))
# j < 0
raises(ValueError, lambda: JzKetCoupled(-1, 1, (1,)))
raises(ValueError, lambda: JzKetCoupled(-1, m, (1,)))
# m not integer or half integer
raises(ValueError, lambda: JzKetCoupled(j, Rational(-1, 3), (1,)))
# abs(m) > j
raises(ValueError, lambda: JzKetCoupled(1, 2, (1,)))
raises(ValueError, lambda: JzKetCoupled(1, -2, (1,)))
# j-m not integer
raises(ValueError, lambda: JzKetCoupled(1, S.Half, (1,)))
# checks types on coupling scheme
raises(TypeError, lambda: JzKetCoupled(1, 1, 1))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1,), 1))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1), (1,)))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1, 1), (1, 2, 1),
(1, 3, 1)))
# checks length of coupling terms
raises(ValueError, lambda: JzKetCoupled(1, 1, (1,), ((1, 2, 1),)))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2),)))
# all jn are integer or half-integer
raises(ValueError, lambda: JzKetCoupled(1, 1, (Rational(1, 3), Rational(2, 3))))
# indices in coupling scheme must be integers
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((S.Half, 1, 2),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, S.Half, 2),) ))
# indices out of range
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((0, 2, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((3, 2, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 0, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 3, 1),) ))
# all j values in coupling scheme must by integer or half-integer
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, S(
4)/3), (1, 3, 1)) ))
# each coupling must satisfy |j1-j2| <= j3 <= j1+j2
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 5)))
raises(ValueError, lambda: JzKetCoupled(5, 1, (1, 1)))
# final j of coupling must be j of the state
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2, 2),) ))
|
6b02e04a426466910473daccb1bf132ca5d039cea9bcda20c7ebd0927f6d4fe3 | 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
assert v.evalf(5, subs={a: 1.234, b:5.8973}) == Float('3.1415926536', 5) * A.x + Float('6.17', 5) * A.y - Float('5.8973', 5) * A.z
def test_vector_xreplace():
x, y, z = symbols('x y z')
v = x**2 * A.x + x*y * A.y + x*y*z * A.z
assert v.xreplace({x : cos(x)}) == cos(x)**2 * A.x + y*cos(x) * A.y + y*z*cos(x) * A.z
assert v.xreplace({x*y : pi}) == x**2 * A.x + pi * A.y + x*y*z * A.z
assert v.xreplace({x*y*z : 1}) == x**2*A.x + x*y*A.y + A.z
assert v.xreplace({x:1, z:0}) == A.x + y * A.y
raises(TypeError, lambda: v.xreplace())
raises(TypeError, lambda: v.xreplace([x, y]))
|
70c9e18440525efbec04c265ecd5262f2d5d58a8a86cac9222744704415997c0 | from sympy import sin, cos, symbols, pi, Float, ImmutableMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, outer
from sympy.physics.vector.dyadic import _check_dyadic
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_dyadic():
d1 = A.x | A.x
d2 = A.y | A.y
d3 = A.x | A.y
assert d1 * 0 == 0
assert d1 != 0
assert d1 * 2 == 2 * A.x | A.x
assert d1 / 2. == 0.5 * d1
assert d1 & (0 * d1) == 0
assert d1 & d2 == 0
assert d1 & A.x == A.x
assert d1 ^ A.x == 0
assert d1 ^ A.y == A.x | A.z
assert d1 ^ A.z == - A.x | A.y
assert d2 ^ A.x == - A.y | A.z
assert A.x ^ d1 == 0
assert A.y ^ d1 == - A.z | A.x
assert A.z ^ d1 == A.y | A.x
assert A.x & d1 == A.x
assert A.y & d1 == 0
assert A.y & d2 == A.y
assert d1 & d3 == A.x | A.y
assert d3 & d1 == 0
assert d1.dt(A) == 0
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
B = A.orientnew('B', 'Axis', [q, A.z])
assert d1.express(B) == d1.express(B, B)
assert d1.express(B) == ((cos(q)**2) * (B.x | B.x) + (-sin(q) * cos(q)) *
(B.x | B.y) + (-sin(q) * cos(q)) * (B.y | B.x) + (sin(q)**2) *
(B.y | B.y))
assert d1.express(B, A) == (cos(q)) * (B.x | A.x) + (-sin(q)) * (B.y | A.x)
assert d1.express(A, B) == (cos(q)) * (A.x | B.x) + (-sin(q)) * (A.x | B.y)
assert d1.dt(B) == (-qd) * (A.y | A.x) + (-qd) * (A.x | A.y)
assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]])
assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0],
[0, 0, 0],
[0, 0, 0]])
assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]])
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
v1 = a * A.x + b * A.y + c * A.z
v2 = d * A.x + e * A.y + f * A.z
d4 = v1.outer(v2)
assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f],
[b * d, b * e, b * f],
[c * d, c * e, c * f]])
d5 = v1.outer(v1)
C = A.orientnew('C', 'Axis', [q, A.x])
for expected, actual in zip(C.dcm(A) * d5.to_matrix(A) * C.dcm(A).T,
d5.to_matrix(C)):
assert (expected - actual).simplify() == 0
raises(TypeError, lambda: d1.applyfunc(0))
def test_dyadic_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')
dy = N.x | N.x
test1 = (1 / x + 1 / y) * dy
assert (N.x & test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (N.x & test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy
test2 = test2.simplify()
assert (N.x & test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy
test3 = test3.simplify()
assert (N.x & test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy
test4 = test4.simplify()
assert (N.x & test4 & N.x) == -2 * y
def test_dyadic_subs():
N = ReferenceFrame('N')
s = symbols('s')
a = s*(N.x | N.x)
assert a.subs({s: 2}) == 2*(N.x | N.x)
def test_check_dyadic():
raises(TypeError, lambda: _check_dyadic(0))
def test_dyadic_evalf():
N = ReferenceFrame('N')
a = pi * (N.x | N.x)
assert a.evalf(3) == Float('3.1416', 3) * (N.x | N.x)
s = symbols('s')
a = 5 * s * pi* (N.x | N.x)
assert a.evalf(2) == Float('5', 2) * Float('3.1416', 2) * s * (N.x | N.x)
assert a.evalf(9, subs={s: 5.124}) == Float('80.48760378', 9) * (N.x | N.x)
def test_dyadic_xreplace():
x, y, z = symbols('x y z')
N = ReferenceFrame('N')
D = outer(N.x, N.x)
v = x*y * D
assert v.xreplace({x : cos(x)}) == cos(x)*y * D
assert v.xreplace({x*y : pi}) == pi * D
v = (x*y)**z * D
assert v.xreplace({(x*y)**z : 1}) == D
assert v.xreplace({x:1, z:0}) == D
raises(TypeError, lambda: v.xreplace())
raises(TypeError, lambda: v.xreplace([x, y]))
|
7de12f9ed17683179987d4e2f888de76795f4200f59e87b3755ac84192c2f2a0 | from sympy import Basic
from sympy import S
from sympy.core.expr import Expr
from sympy.core.numbers import Integer
from sympy.core.sympify import sympify
from sympy.core.kind import Kind, NumberKind, UndefinedKind
from sympy.core.compatibility import SYMPY_INTS
from sympy.printing.defaults import Printable
import itertools
from collections.abc import Iterable
class ArrayKind(Kind):
"""
Kind for N-dimensional array in SymPy.
This kind represents the multidimensional array that algebraic
operations are defined. Basic class for this kind is ``NDimArray``,
but any expression representing the array can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the array contains only numbers.
Examples
========
Any instance of array class has ``ArrayKind``.
>>> from sympy import NDimArray
>>> NDimArray([1,2,3]).kind
ArrayKind(NumberKind)
Although expressions representing an array may be not instance of
array class, it will have ``ArrayKind`` as well.
>>> from sympy import Integral
>>> from sympy.tensor.array import NDimArray
>>> from sympy.abc import x
>>> intA = Integral(NDimArray([1,2,3]), x)
>>> isinstance(intA, NDimArray)
False
>>> intA.kind
ArrayKind(NumberKind)
Use ``isinstance()`` to check for ``ArrayKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy.tensor.array import ArrayKind
>>> from sympy.core.kind import NumberKind
>>> boolA = NDimArray([True, False])
>>> isinstance(boolA.kind, ArrayKind)
True
>>> boolA.kind is ArrayKind(NumberKind)
False
See Also
========
shape : Function to return the shape of objects with ``MatrixKind``.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "ArrayKind(%s)" % self.element_kind
class NDimArray(Printable):
"""
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
is_scalar = False
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
@property
def kind(self):
elem_kinds = set(e.kind for e in self._array)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return ArrayKind(elemkind)
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
raise ValueError("Only a tuple index is accepted")
if self._loop_size == 0:
raise ValueError("Index not valide with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any([(isinstance(i, Expr) and (not i.is_number)) for i in tuple_index]):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy import Dict, Tuple
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if any([not isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape]):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
def _eval_derivative(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def _sympystr(self, printer):
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return printer._print(self[()])
return f(self._loop_size, self.shape, 0, self._loop_size)
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __truediv__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rtruediv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index, )
if len(index) < self.rank():
index = tuple([i for i in index] + \
[slice(None) for i in range(len(index), self.rank())])
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
69dd942ca6d971834d6ea79038f58cfb0b68c807e440d8ea9d4b1659bfaafe0c | from sympy import Expr, ImmutableDenseNDimArray, S
from sympy.core.sympify import _sympify
class ZeroArray(Expr):
"""
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.Zero
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if any(not i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray.zeros(*self.shape)
|
35ea65b0972ebc49a7ff4158351aacaf3c7100e69ac1303e612f5ef5d6d2abd4 | import operator
from functools import reduce, singledispatch
from sympy import Expr, Transpose, Identity, MatrixSymbol, S
from sympy.codegen.array_utils import CodegenArrayElementwiseAdd, CodegenArrayPermuteDims, CodegenArrayContraction, \
get_shape, CodegenArrayTensorProduct
from sympy.combinatorics.permutations import _af_invert
from sympy.tensor.array.expressions.array_expressions import ZeroArray
@singledispatch
def array_derive(expr, x):
raise NotImplementedError(f"not implemented for type {type(expr)}")
@array_derive.register(Expr)
def _(expr: Expr, x: Expr):
return ZeroArray(*x.shape)
@array_derive.register(CodegenArrayTensorProduct)
def _(expr: CodegenArrayTensorProduct, x: Expr):
args = expr.args
addend_list = []
for i, arg in enumerate(expr.args):
darg = array_derive(arg, x)
if darg == 0:
continue
args_prev = args[:i]
args_succ = args[i+1:]
shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
addend = CodegenArrayTensorProduct(*args_prev, darg, *args_succ)
tot1 = len(get_shape(x))
tot2 = tot1 + len(shape_prev)
tot3 = tot2 + len(get_shape(arg))
tot4 = tot3 + len(shape_succ)
perm = [i for i in range(tot1, tot2)] + \
[i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \
[i for i in range(tot3, tot4)]
addend = CodegenArrayPermuteDims(addend, _af_invert(perm))
addend_list.append(addend)
if len(addend_list) == 1:
return addend_list[0]
elif len(addend_list) == 0:
return S.Zero
else:
return CodegenArrayElementwiseAdd(*addend_list)
@array_derive.register(MatrixSymbol)
def _(expr: MatrixSymbol, x: Expr):
m, n = expr.shape
if expr == x:
return CodegenArrayPermuteDims(
CodegenArrayTensorProduct(Identity(m), Identity(n)),
[0, 2, 1, 3]
)
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Identity)
def _(expr: Identity, x: Expr):
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Transpose)
def _(expr: Transpose, x: Expr):
# D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
# D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
fd = array_derive(expr.arg, x)
return CodegenArrayPermuteDims(fd, [0, 1, 3, 2])
@array_derive.register(CodegenArrayContraction)
def _(expr: CodegenArrayContraction, x: Expr):
fd = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
contraction_indices = expr.contraction_indices
new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
return CodegenArrayContraction(fd, *new_contraction_indices)
@array_derive.register(CodegenArrayElementwiseAdd)
def _(expr: CodegenArrayElementwiseAdd, x: Expr):
return CodegenArrayElementwiseAdd(*[array_derive(arg, x) for arg in expr.args])
@array_derive.register(CodegenArrayPermuteDims)
def _(expr: CodegenArrayPermuteDims, x: Expr):
de = array_derive(expr.expr, x)
perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
return CodegenArrayPermuteDims(de, perm)
def matrix_derive(expr, x):
from sympy.codegen.array_utils import parse_matrix_expression, recognize_matrix_expression
ce = parse_matrix_expression(expr)
dce = array_derive(ce, x)
return recognize_matrix_expression(dce).doit()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.